summaryrefslogtreecommitdiff
path: root/Userland/Shell/AST.cpp
blob: c6bf44137c57709a8528aad8fab74b9e5344445c (plain)
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
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "AST.h"
#include "Shell.h"
#include <AK/MemoryStream.h>
#include <AK/ScopeGuard.h>
#include <AK/ScopedValueRollback.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/URL.h>
#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

ErrorOr<void> AK::Formatter<Shell::AST::Command>::format(FormatBuilder& builder, Shell::AST::Command const& value)
{
    if (m_sign_mode != FormatBuilder::SignMode::Default)
        VERIFY_NOT_REACHED();
    if (m_alternative_form)
        VERIFY_NOT_REACHED();
    if (m_zero_pad)
        VERIFY_NOT_REACHED();
    if (m_mode != Mode::Default && m_mode != Mode::String)
        VERIFY_NOT_REACHED();
    if (m_width.has_value())
        VERIFY_NOT_REACHED();
    if (m_precision.has_value())
        VERIFY_NOT_REACHED();

    if (value.argv.is_empty()) {
        TRY(builder.put_literal("(ShellInternal)"sv));
    } else {
        bool first = true;
        for (auto& arg : value.argv) {
            if (!first)
                TRY(builder.put_literal(" "sv));
            first = false;
            TRY(builder.put_literal(arg));
        }
    }

    for (auto& redir : value.redirections) {
        TRY(builder.put_padding(' ', 1));
        if (redir.is_path_redirection()) {
            auto path_redir = (Shell::AST::PathRedirection const*)&redir;
            TRY(builder.put_i64(path_redir->fd));
            switch (path_redir->direction) {
            case Shell::AST::PathRedirection::Read:
                TRY(builder.put_literal("<"sv));
                break;
            case Shell::AST::PathRedirection::Write:
                TRY(builder.put_literal(">"sv));
                break;
            case Shell::AST::PathRedirection::WriteAppend:
                TRY(builder.put_literal(">>"sv));
                break;
            case Shell::AST::PathRedirection::ReadWrite:
                TRY(builder.put_literal("<>"sv));
                break;
            }
            TRY(builder.put_literal(path_redir->path));
        } else if (redir.is_fd_redirection()) {
            auto* fdredir = (Shell::AST::FdRedirection const*)&redir;
            TRY(builder.put_i64(fdredir->new_fd));
            TRY(builder.put_literal(">"sv));
            TRY(builder.put_i64(fdredir->old_fd));
        } else if (redir.is_close_redirection()) {
            auto close_redir = (Shell::AST::CloseRedirection const*)&redir;
            TRY(builder.put_i64(close_redir->fd));
            TRY(builder.put_literal(">&-"sv));
        } else {
            VERIFY_NOT_REACHED();
        }
    }

    if (!value.next_chain.is_empty()) {
        for (auto& command : value.next_chain) {
            switch (command.action) {
            case Shell::AST::NodeWithAction::And:
                TRY(builder.put_literal(" && "sv));
                break;
            case Shell::AST::NodeWithAction::Or:
                TRY(builder.put_literal(" || "sv));
                break;
            case Shell::AST::NodeWithAction::Sequence:
                TRY(builder.put_literal("; "sv));
                break;
            }

            TRY(builder.put_literal("("sv));
            TRY(builder.put_literal(command.node->class_name()));
            TRY(builder.put_literal("...)"sv));
        }
    }
    if (!value.should_wait)
        TRY(builder.put_literal("&"sv));
    return {};
}

namespace Shell::AST {

static inline void print_indented(StringView str, int indent)
{
    dbgln("{}{}", String::repeated(' ', indent * 2), str);
}

static inline Optional<Position> merge_positions(Optional<Position> const& left, Optional<Position> const& right)
{
    if (!left.has_value())
        return right;

    if (!right.has_value())
        return left;

    return Position {
        .start_offset = left->start_offset,
        .end_offset = right->end_offset,
        .start_line = left->start_line,
        .end_line = right->end_line,
    };
}

static inline Vector<Command> join_commands(Vector<Command> left, Vector<Command> right)
{
    Command command;

    auto last_in_left = left.take_last();
    auto first_in_right = right.take_first();

    command.argv.extend(last_in_left.argv);
    command.argv.extend(first_in_right.argv);

    command.redirections.extend(last_in_left.redirections);
    command.redirections.extend(first_in_right.redirections);

    command.should_wait = first_in_right.should_wait && last_in_left.should_wait;
    command.is_pipe_source = first_in_right.is_pipe_source;
    command.should_notify_if_in_background = first_in_right.should_notify_if_in_background || last_in_left.should_notify_if_in_background;

    command.position = merge_positions(last_in_left.position, first_in_right.position);

    Vector<Command> commands;
    commands.extend(left);
    commands.append(command);
    commands.extend(right);

    return commands;
}

static String resolve_slices(RefPtr<Shell> shell, String&& input_value, NonnullRefPtrVector<Slice> slices)
{
    if (slices.is_empty())
        return move(input_value);

    for (auto& slice : slices) {
        auto value = slice.run(shell);
        if (shell && shell->has_any_error())
            break;

        if (!value) {
            shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice.position());
            return move(input_value);
        }

        auto index_values = value->resolve_as_list(shell);
        Vector<size_t> indices;
        indices.ensure_capacity(index_values.size());

        size_t i = 0;
        for (auto& value : index_values) {
            auto maybe_index = value.to_int();
            if (!maybe_index.has_value()) {
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice.position());
                return move(input_value);
            }
            ++i;

            auto index = maybe_index.value();
            auto original_index = index;
            if (index < 0)
                index += input_value.length();

            if (index < 0 || (size_t)index >= input_value.length()) {
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, input_value.length()), slice.position());
                return move(input_value);
            }
            indices.unchecked_append(index);
        }

        StringBuilder builder { indices.size() };
        for (auto& index : indices)
            builder.append(input_value[index]);

        input_value = builder.build();
    }

    return move(input_value);
}

static Vector<String> resolve_slices(RefPtr<Shell> shell, Vector<String>&& values, NonnullRefPtrVector<Slice> slices)
{
    if (slices.is_empty())
        return move(values);

    for (auto& slice : slices) {
        auto value = slice.run(shell);
        if (shell && shell->has_any_error())
            break;

        if (!value) {
            shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice.position());
            return move(values);
        }

        auto index_values = value->resolve_as_list(shell);
        Vector<size_t> indices;
        indices.ensure_capacity(index_values.size());

        size_t i = 0;
        for (auto& value : index_values) {
            auto maybe_index = value.to_int();
            if (!maybe_index.has_value()) {
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice.position());
                return move(values);
            }
            ++i;

            auto index = maybe_index.value();
            auto original_index = index;
            if (index < 0)
                index += values.size();

            if (index < 0 || (size_t)index >= values.size()) {
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, values.size()), slice.position());
                return move(values);
            }
            indices.unchecked_append(index);
        }

        Vector<String> result;
        result.ensure_capacity(indices.size());
        for (auto& index : indices)
            result.unchecked_append(values[index]);

        values = move(result);
    }

    return move(values);
}

void Node::clear_syntax_error()
{
    m_syntax_error_node->clear_syntax_error();
}

void Node::set_is_syntax_error(SyntaxError const& error_node)
{
    if (!m_syntax_error_node) {
        m_syntax_error_node = error_node;
    } else {
        m_syntax_error_node->set_is_syntax_error(error_node);
    }
}

bool Node::is_syntax_error() const
{
    return m_syntax_error_node && m_syntax_error_node->is_syntax_error();
}

void Node::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
{
    auto value = run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return;

    if (value->is_job()) {
        callback(value);
        return;
    }

    if (value->is_list_without_resolution()) {
        auto list = value->resolve_without_cast(shell);
        for (auto& element : static_cast<ListValue*>(list.ptr())->values()) {
            if (callback(element) == IterationDecision::Break)
                break;
        }
        return;
    }

    auto list = value->resolve_as_list(shell);
    for (auto& element : list) {
        if (callback(make_ref_counted<StringValue>(move(element))) == IterationDecision::Break)
            break;
    }
}

Vector<Command> Node::to_lazy_evaluated_commands(RefPtr<Shell> shell)
{
    if (would_execute()) {
        // Wrap the node in a "should immediately execute next" command.
        return {
            Command { {}, {}, true, false, true, true, {}, { NodeWithAction(*this, NodeWithAction::Sequence) }, position() }
        };
    }

    return run(shell)->resolve_as_commands(shell);
}

void Node::dump(int level) const
{
    print_indented(String::formatted("{} at {}:{} (from {}.{} to {}.{})",
                       class_name().characters(),
                       m_position.start_offset,
                       m_position.end_offset,
                       m_position.start_line.line_number,
                       m_position.start_line.line_column,
                       m_position.end_line.line_number,
                       m_position.end_line.line_column),
        level);
}

Node::Node(Position position)
    : m_position(position)
{
}

Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (matching_node) {
        auto kind = matching_node->kind();
        StringLiteral::EnclosureType enclosure_type = StringLiteral::EnclosureType::None;
        if (kind == Kind::StringLiteral)
            enclosure_type = static_cast<StringLiteral*>(matching_node.ptr())->enclosure_type();

        auto set_results_trivia = [enclosure_type](Vector<Line::CompletionSuggestion>&& suggestions) {
            if (enclosure_type != StringLiteral::EnclosureType::None) {
                for (auto& entry : suggestions)
                    entry.trailing_trivia = { static_cast<u32>(enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? '\'' : '"') };
            }
            return suggestions;
        };
        if (kind == Kind::BarewordLiteral || kind == Kind::StringLiteral) {
            Shell::EscapeMode escape_mode;
            StringView text;
            size_t corrected_offset;
            if (kind == Kind::BarewordLiteral) {
                auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
                text = node->text();
                escape_mode = Shell::EscapeMode::Bareword;
                corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset, escape_mode);
            } else {
                auto* node = static_cast<StringLiteral*>(matching_node.ptr());
                text = node->text();
                escape_mode = enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? Shell::EscapeMode::SingleQuotedString : Shell::EscapeMode::DoubleQuotedString;
                corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset + 1, escape_mode);
            }

            if (corrected_offset > text.length())
                return {};

            // If the literal isn't an option, treat it as a path.
            if (!(text.starts_with('-') || text == "--" || text == "-"))
                return set_results_trivia(shell.complete_path(""sv, text, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node, escape_mode));

            // If the literal is an option, we have to know the program name
            // should we have no way to get that, bail early.

            if (!hit_test_result.closest_command_node)
                return {};

            auto program_name_node = hit_test_result.closest_command_node->leftmost_trivial_literal();
            if (!program_name_node)
                return {};

            String program_name;
            if (program_name_node->is_bareword())
                program_name = static_cast<BarewordLiteral*>(program_name_node.ptr())->text();
            else
                program_name = static_cast<StringLiteral*>(program_name_node.ptr())->text();

            return set_results_trivia(shell.complete_option(program_name, text, corrected_offset, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node));
        }
        return {};
    }
    auto result = hit_test_position(offset);
    if (!result.matching_node)
        return shell.complete_path(""sv, ""sv, 0, Shell::ExecutableOnly::No, result.closest_command_node.ptr(), nullptr, Shell::EscapeMode::Bareword);

    auto node = result.matching_node;
    if (node->is_bareword() || node != result.closest_node_with_semantic_meaning)
        node = result.closest_node_with_semantic_meaning;

    if (!node)
        return {};

    return node->complete_for_editor(shell, offset, result);
}

Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset)
{
    return Node::complete_for_editor(shell, offset, { nullptr, nullptr, nullptr });
}

void And::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> And::run(RefPtr<Shell> shell)
{
    auto commands = m_left->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    commands.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::And });
    return make_ref_counted<CommandSequenceValue>(move(commands));
}

void And::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    metadata.is_first_in_list = true;
    m_left->highlight_in_editor(editor, shell, metadata);
    m_right->highlight_in_editor(editor, shell, metadata);
}

HitTestResult And::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (result.matching_node) {
        if (!result.closest_command_node)
            result.closest_command_node = m_right;
        return result;
    }

    result = m_right->hit_test_position(offset);
    if (!result.closest_command_node)
        result.closest_command_node = m_right;
    return result;
}

And::And(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position and_position)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
    , m_and_position(and_position)
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

void ListConcatenate::dump(int level) const
{
    Node::dump(level);
    for (auto& element : m_list)
        element->dump(level + 1);
}

RefPtr<Value> ListConcatenate::run(RefPtr<Shell> shell)
{
    RefPtr<Value> result = nullptr;

    for (auto& element : m_list) {
        if (shell && shell->has_any_error())
            break;
        if (!result) {
            result = make_ref_counted<ListValue>({ element->run(shell)->resolve_without_cast(shell) });
            continue;
        }
        auto element_value = element->run(shell)->resolve_without_cast(shell);
        if (shell && shell->has_any_error())
            break;

        if (result->is_command() || element_value->is_command()) {
            auto joined_commands = join_commands(result->resolve_as_commands(shell), element_value->resolve_as_commands(shell));

            if (joined_commands.size() == 1) {
                auto& command = joined_commands[0];
                command.position = position();
                result = make_ref_counted<CommandValue>(command);
            } else {
                result = make_ref_counted<CommandSequenceValue>(move(joined_commands));
            }
        } else {
            NonnullRefPtrVector<Value> values;

            if (result->is_list_without_resolution()) {
                values.extend(static_cast<ListValue*>(result.ptr())->values());
            } else {
                for (auto& result : result->resolve_as_list(shell))
                    values.append(make_ref_counted<StringValue>(result));
            }

            values.append(element_value);

            result = make_ref_counted<ListValue>(move(values));
        }
    }
    if (!result)
        return make_ref_counted<ListValue>({});

    return result;
}

void ListConcatenate::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
{
    for (auto& entry : m_list) {
        auto value = entry->run(shell);
        if (shell && shell->has_any_error())
            break;
        if (!value)
            continue;
        if (callback(value.release_nonnull()) == IterationDecision::Break)
            break;
    }
}

void ListConcatenate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    auto first = metadata.is_first_in_list;
    metadata.is_first_in_list = false;

    metadata.is_first_in_list = first;
    for (auto& element : m_list) {
        element->highlight_in_editor(editor, shell, metadata);
        metadata.is_first_in_list = false;
    }
}

HitTestResult ListConcatenate::hit_test_position(size_t offset) const
{
    bool first = true;
    for (auto& element : m_list) {
        auto result = element->hit_test_position(offset);
        if (!result.closest_node_with_semantic_meaning && !first)
            result.closest_node_with_semantic_meaning = this;
        if (result.matching_node)
            return result;
        first = false;
    }

    return {};
}

RefPtr<Node> ListConcatenate::leftmost_trivial_literal() const
{
    if (m_list.is_empty())
        return nullptr;

    return m_list.first()->leftmost_trivial_literal();
}

ListConcatenate::ListConcatenate(Position position, Vector<NonnullRefPtr<Node>> list)
    : Node(move(position))
    , m_list(move(list))
{
    for (auto& element : m_list) {
        if (element->is_syntax_error()) {
            set_is_syntax_error(element->syntax_error_node());
            break;
        }
    }
}

void Background::dump(int level) const
{
    Node::dump(level);
    m_command->dump(level + 1);
}

RefPtr<Value> Background::run(RefPtr<Shell> shell)
{
    auto commands = m_command->to_lazy_evaluated_commands(shell);
    for (auto& command : commands)
        command.should_wait = false;

    return make_ref_counted<CommandSequenceValue>(move(commands));
}

void Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_command->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Background::hit_test_position(size_t offset) const
{
    return m_command->hit_test_position(offset);
}

Background::Background(Position position, NonnullRefPtr<Node> command)
    : Node(move(position))
    , m_command(move(command))
{
    if (m_command->is_syntax_error())
        set_is_syntax_error(m_command->syntax_error_node());
}

void BarewordLiteral::dump(int level) const
{
    Node::dump(level);
    print_indented(m_text, level + 1);
}

RefPtr<Value> BarewordLiteral::run(RefPtr<Shell>)
{
    return make_ref_counted<StringValue>(m_text);
}

void BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    if (metadata.is_first_in_list) {
        auto runnable = shell.runnable_path_for(m_text);
        if (runnable.has_value()) {
            Line::Style bold = { Line::Style::Bold };
            Line::Style style = bold;

#ifdef __serenity__
            if (runnable->kind == Shell::RunnablePath::Kind::Executable || runnable->kind == Shell::RunnablePath::Kind::Alias) {
                auto name = shell.help_path_for({}, *runnable);
                if (name.has_value()) {
                    auto url = URL::create_with_help_scheme(name.release_value(), shell.hostname);
                    style = bold.unified_with(Line::Style::Hyperlink(url.to_string()));
                }
            }
#endif

            editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
        } else {
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
        }

        return;
    }

    if (m_text.starts_with('-')) {
        if (m_text == "--") {
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
            return;
        }
        if (m_text == "-")
            return;

        if (m_text.starts_with("--"sv)) {
            auto index = m_text.find('=').value_or(m_text.length() - 1) + 1;
            editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
        } else {
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
        }
    }
    if (Core::File::exists(m_text)) {
        auto realpath = shell.resolve_path(m_text);
        auto url = URL::create_with_file_protocol(realpath);
        url.set_host(shell.hostname);
        editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
    }
}

BarewordLiteral::BarewordLiteral(Position position, String text)
    : Node(move(position))
    , m_text(move(text))
{
}

void BraceExpansion::dump(int level) const
{
    Node::dump(level);
    for (auto& entry : m_entries)
        entry.dump(level + 1);
}

RefPtr<Value> BraceExpansion::run(RefPtr<Shell> shell)
{
    NonnullRefPtrVector<Value> values;
    for (auto& entry : m_entries) {
        if (shell && shell->has_any_error())
            break;
        auto value = entry.run(shell);
        if (value)
            values.append(value.release_nonnull());
    }

    return make_ref_counted<ListValue>(move(values));
}

HitTestResult BraceExpansion::hit_test_position(size_t offset) const
{
    for (auto& entry : m_entries) {
        auto result = entry.hit_test_position(offset);
        if (result.matching_node) {
            if (!result.closest_command_node)
                result.closest_command_node = &entry;
            return result;
        }
    }

    return {};
}

void BraceExpansion::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    for (auto& entry : m_entries) {
        entry.highlight_in_editor(editor, shell, metadata);
        metadata.is_first_in_list = false;
    }
}

BraceExpansion::BraceExpansion(Position position, NonnullRefPtrVector<Node> entries)
    : Node(move(position))
    , m_entries(move(entries))
{
    for (auto& entry : m_entries) {
        if (entry.is_syntax_error()) {
            set_is_syntax_error(entry.syntax_error_node());
            break;
        }
    }
}

void CastToCommand::dump(int level) const
{
    Node::dump(level);
    m_inner->dump(level + 1);
}

RefPtr<Value> CastToCommand::run(RefPtr<Shell> shell)
{
    if (m_inner->is_command())
        return m_inner->run(shell);

    auto value = m_inner->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (value->is_command())
        return value;

    auto argv = value->resolve_as_list(shell);
    return make_ref_counted<CommandValue>(move(argv), position());
}

void CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_inner->highlight_in_editor(editor, shell, metadata);
}

HitTestResult CastToCommand::hit_test_position(size_t offset) const
{
    auto result = m_inner->hit_test_position(offset);
    if (!result.closest_node_with_semantic_meaning)
        result.closest_node_with_semantic_meaning = this;
    if (!result.closest_command_node && position().contains(offset))
        result.closest_command_node = this;
    return result;
}

Vector<Line::CompletionSuggestion> CastToCommand::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node || !matching_node->is_bareword())
        return {};

    auto corrected_offset = offset - matching_node->position().start_offset;
    auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());

    if (corrected_offset > node->text().length())
        return {};

    return shell.complete_program_name(node->text(), corrected_offset);
}

RefPtr<Node> CastToCommand::leftmost_trivial_literal() const
{
    return m_inner->leftmost_trivial_literal();
}

CastToCommand::CastToCommand(Position position, NonnullRefPtr<Node> inner)
    : Node(move(position))
    , m_inner(move(inner))
{
    if (m_inner->is_syntax_error())
        set_is_syntax_error(m_inner->syntax_error_node());
}

void CastToList::dump(int level) const
{
    Node::dump(level);
    if (m_inner)
        m_inner->dump(level + 1);
    else
        print_indented("(empty)"sv, level + 1);
}

RefPtr<Value> CastToList::run(RefPtr<Shell> shell)
{
    if (!m_inner)
        return make_ref_counted<ListValue>({});

    auto inner_value = m_inner->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (inner_value->is_command() || inner_value->is_list())
        return inner_value;

    auto values = inner_value->resolve_as_list(shell);
    NonnullRefPtrVector<Value> cast_values;
    for (auto& value : values)
        cast_values.append(make_ref_counted<StringValue>(value));

    return make_ref_counted<ListValue>(cast_values);
}

void CastToList::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
{
    if (m_inner)
        m_inner->for_each_entry(shell, move(callback));
}

void CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    if (m_inner)
        m_inner->highlight_in_editor(editor, shell, metadata);
}

HitTestResult CastToList::hit_test_position(size_t offset) const
{
    if (!m_inner)
        return {};

    return m_inner->hit_test_position(offset);
}

RefPtr<Node> CastToList::leftmost_trivial_literal() const
{
    return m_inner->leftmost_trivial_literal();
}

CastToList::CastToList(Position position, RefPtr<Node> inner)
    : Node(move(position))
    , m_inner(move(inner))
{
    if (m_inner && m_inner->is_syntax_error())
        set_is_syntax_error(m_inner->syntax_error_node());
}

void CloseFdRedirection::dump(int level) const
{
    Node::dump(level);
    print_indented(String::formatted("{} -> Close", m_fd), level);
}

RefPtr<Value> CloseFdRedirection::run(RefPtr<Shell>)
{
    Command command;
    command.position = position();
    command.redirections.append(adopt_ref(*new CloseRedirection(m_fd)));
    return make_ref_counted<CommandValue>(move(command));
}

void CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
    editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) });   // Amber
}

CloseFdRedirection::CloseFdRedirection(Position position, int fd)
    : Node(move(position))
    , m_fd(fd)
{
}

CloseFdRedirection::~CloseFdRedirection()
{
}

void CommandLiteral::dump(int level) const
{
    Node::dump(level);
    print_indented(String::formatted("(Generated command literal: {})", m_command), level + 1);
}

RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
{
    return make_ref_counted<CommandValue>(m_command);
}

CommandLiteral::CommandLiteral(Position position, Command command)
    : Node(move(position))
    , m_command(move(command))
{
}

CommandLiteral::~CommandLiteral()
{
}

void Comment::dump(int level) const
{
    Node::dump(level);
    print_indented(m_text, level + 1);
}

RefPtr<Value> Comment::run(RefPtr<Shell>)
{
    return make_ref_counted<ListValue>({});
}

void Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
}

Comment::Comment(Position position, String text)
    : Node(move(position))
    , m_text(move(text))
{
}

Comment::~Comment()
{
}

void ContinuationControl::dump(int level) const
{
    Node::dump(level);
    print_indented(m_kind == Continue ? "(Continue)"sv : "(Break)"sv, level + 1);
}

RefPtr<Value> ContinuationControl::run(RefPtr<Shell> shell)
{
    if (m_kind == Break)
        shell->raise_error(Shell::ShellError::InternalControlFlowBreak, {}, position());
    else if (m_kind == Continue)
        shell->raise_error(Shell::ShellError::InternalControlFlowContinue, {}, position());
    else
        VERIFY_NOT_REACHED();
    return make_ref_counted<ListValue>({});
}

void ContinuationControl::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
}

void DoubleQuotedString::dump(int level) const
{
    Node::dump(level);
    m_inner->dump(level + 1);
}

RefPtr<Value> DoubleQuotedString::run(RefPtr<Shell> shell)
{
    StringBuilder builder;
    auto values = m_inner->run(shell)->resolve_as_list(shell);

    builder.join(""sv, values);

    return make_ref_counted<StringValue>(builder.to_string());
}

void DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
    if (metadata.is_first_in_list)
        style.unify_with({ Line::Style::Bold });

    editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
    metadata.is_first_in_list = false;
    m_inner->highlight_in_editor(editor, shell, metadata);
}

HitTestResult DoubleQuotedString::hit_test_position(size_t offset) const
{
    return m_inner->hit_test_position(offset);
}

DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
    : Node(move(position))
    , m_inner(move(inner))
{
    if (m_inner->is_syntax_error())
        set_is_syntax_error(m_inner->syntax_error_node());
}

DoubleQuotedString::~DoubleQuotedString()
{
}

void DynamicEvaluate::dump(int level) const
{
    Node::dump(level);
    m_inner->dump(level + 1);
}

RefPtr<Value> DynamicEvaluate::run(RefPtr<Shell> shell)
{
    auto result = m_inner->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    // Dynamic Evaluation behaves differently between strings and lists.
    // Strings are treated as variables, and Lists are treated as commands.
    if (result->is_string()) {
        auto name_part = result->resolve_as_list(shell);
        VERIFY(name_part.size() == 1);
        return make_ref_counted<SimpleVariableValue>(name_part[0]);
    }

    // If it's anything else, we're just gonna cast it to a list.
    auto list = result->resolve_as_list(shell);
    return make_ref_counted<CommandValue>(move(list), position());
}

void DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
    m_inner->highlight_in_editor(editor, shell, metadata);
}

HitTestResult DynamicEvaluate::hit_test_position(size_t offset) const
{
    return m_inner->hit_test_position(offset);
}

DynamicEvaluate::DynamicEvaluate(Position position, NonnullRefPtr<Node> inner)
    : Node(move(position))
    , m_inner(move(inner))
{
    if (m_inner->is_syntax_error())
        set_is_syntax_error(m_inner->syntax_error_node());
}

DynamicEvaluate::~DynamicEvaluate()
{
}

void Fd2FdRedirection::dump(int level) const
{
    Node::dump(level);
    print_indented(String::formatted("{} -> {}", m_old_fd, m_new_fd), level);
}

RefPtr<Value> Fd2FdRedirection::run(RefPtr<Shell>)
{
    Command command;
    command.position = position();
    command.redirections.append(FdRedirection::create(m_new_fd, m_old_fd, Rewiring::Close::None));
    return make_ref_counted<CommandValue>(move(command));
}

void Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
}

Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
    : Node(move(position))
    , m_old_fd(src)
    , m_new_fd(dst)
{
}

Fd2FdRedirection::~Fd2FdRedirection()
{
}

void FunctionDeclaration::dump(int level) const
{
    Node::dump(level);
    print_indented(String::formatted("(name: {})\n", m_name.name), level + 1);
    print_indented("(argument names)"sv, level + 1);
    for (auto& arg : m_arguments)
        print_indented(String::formatted("(name: {})\n", arg.name), level + 2);

    print_indented("(body)"sv, level + 1);
    if (m_block)
        m_block->dump(level + 2);
    else
        print_indented("(null)"sv, level + 2);
}

RefPtr<Value> FunctionDeclaration::run(RefPtr<Shell> shell)
{
    Vector<String> args;
    for (auto& arg : m_arguments)
        args.append(arg.name);

    shell->define_function(m_name.name, move(args), m_block);

    return make_ref_counted<ListValue>({});
}

void FunctionDeclaration::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    editor.stylize({ m_name.position.start_offset, m_name.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });

    for (auto& arg : m_arguments)
        editor.stylize({ arg.position.start_offset, arg.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });

    metadata.is_first_in_list = true;
    if (m_block)
        m_block->highlight_in_editor(editor, shell, metadata);
}

HitTestResult FunctionDeclaration::hit_test_position(size_t offset) const
{
    if (!m_block)
        return {};

    auto result = m_block->hit_test_position(offset);
    if (result.matching_node && result.matching_node->is_simple_variable())
        result.closest_node_with_semantic_meaning = this;
    return result;
}

Vector<Line::CompletionSuggestion> FunctionDeclaration::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node)
        return {};

    if (!matching_node->is_simple_variable())
        return matching_node->complete_for_editor(shell, offset, hit_test_result);

    auto corrected_offset = offset - matching_node->position().start_offset - 1; // Skip the first '$'
    auto* node = static_cast<SimpleVariable*>(matching_node.ptr());

    auto name = node->name().substring_view(0, corrected_offset);

    Vector<Line::CompletionSuggestion> results;
    for (auto& arg : m_arguments) {
        if (arg.name.starts_with(name))
            results.append(arg.name);
    }

    results.extend(matching_node->complete_for_editor(shell, offset, hit_test_result));

    return results;
}

FunctionDeclaration::FunctionDeclaration(Position position, NameWithPosition name, Vector<NameWithPosition> arguments, RefPtr<AST::Node> body)
    : Node(move(position))
    , m_name(move(name))
    , m_arguments(arguments)
    , m_block(move(body))
{
    if (m_block && m_block->is_syntax_error())
        set_is_syntax_error(m_block->syntax_error_node());
}

FunctionDeclaration::~FunctionDeclaration()
{
}

void ForLoop::dump(int level) const
{
    Node::dump(level);
    if (m_variable.has_value())
        print_indented(String::formatted("iterating with {} in", m_variable->name), level + 1);
    if (m_index_variable.has_value())
        print_indented(String::formatted("with index name {} in", m_index_variable->name), level + 1);
    if (m_iterated_expression)
        m_iterated_expression->dump(level + 2);
    else
        print_indented("(ever)"sv, level + 2);
    print_indented("Running"sv, level + 1);
    if (m_block)
        m_block->dump(level + 2);
    else
        print_indented("(null)"sv, level + 2);
}

RefPtr<Value> ForLoop::run(RefPtr<Shell> shell)
{
    if (!m_block)
        return make_ref_counted<ListValue>({});

    size_t consecutive_interruptions = 0;
    auto run = [&](auto& block_value) {
        if (shell->has_error(Shell::ShellError::InternalControlFlowBreak)) {
            shell->take_error();
            return IterationDecision::Break;
        }

        if (shell->has_error(Shell::ShellError::InternalControlFlowContinue)) {
            shell->take_error();
            return IterationDecision::Continue;
        }

        if (shell->has_any_error() && !shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
            return IterationDecision::Break;

        if (block_value->is_job()) {
            auto job = static_cast<JobValue*>(block_value.ptr())->job();
            if (!job || job->is_running_in_background())
                return IterationDecision::Continue;
            shell->block_on_job(job);

            if (shell->has_any_error()) {
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
                    ++consecutive_interruptions;

                if (shell->has_error(Shell::ShellError::InternalControlFlowKilled))
                    return IterationDecision::Break;
            }
        }
        return IterationDecision::Continue;
    };

    if (m_iterated_expression) {
        auto variable_name = m_variable.has_value() ? m_variable->name : "it";
        Optional<StringView> index_name = m_index_variable.has_value() ? Optional<StringView>(m_index_variable->name) : Optional<StringView>();
        size_t i = 0;
        m_iterated_expression->for_each_entry(shell, [&](auto value) {
            if (consecutive_interruptions >= 2)
                return IterationDecision::Break;

            if (shell) {
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
                    shell->take_error();

                if (shell->has_any_error())
                    return IterationDecision::Break;
            }

            RefPtr<Value> block_value;

            {
                auto frame = shell->push_frame(String::formatted("for ({})", this));
                shell->set_local_variable(variable_name, value, true);

                if (index_name.has_value())
                    shell->set_local_variable(index_name.value(), make_ref_counted<AST::StringValue>(String::number(i)), true);

                ++i;

                block_value = m_block->run(shell);
            }

            return run(block_value);
        });
    } else {
        for (;;) {
            if (consecutive_interruptions >= 2)
                break;

            if (shell) {
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
                    shell->take_error();

                if (shell->has_any_error())
                    break;
            }

            RefPtr<Value> block_value = m_block->run(shell);
            if (run(block_value) == IterationDecision::Break)
                break;
        }
    }

    return make_ref_counted<ListValue>({});
}

void ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    auto is_loop = m_iterated_expression.is_null();
    editor.stylize({ m_position.start_offset, m_position.start_offset + (is_loop ? 4 : 3) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
    if (!is_loop) {
        if (m_in_kw_position.has_value())
            editor.stylize({ m_in_kw_position.value().start_offset, m_in_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

        if (m_index_kw_position.has_value())
            editor.stylize({ m_index_kw_position.value().start_offset, m_index_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

        metadata.is_first_in_list = false;
        m_iterated_expression->highlight_in_editor(editor, shell, metadata);
    }

    if (m_index_variable.has_value())
        editor.stylize({ m_index_variable->position.start_offset, m_index_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });

    if (m_variable.has_value())
        editor.stylize({ m_variable->position.start_offset, m_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });

    metadata.is_first_in_list = true;
    if (m_block)
        m_block->highlight_in_editor(editor, shell, metadata);
}

HitTestResult ForLoop::hit_test_position(size_t offset) const
{
    if (m_iterated_expression) {
        if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
            return result;
    }

    if (!m_block)
        return {};

    return m_block->hit_test_position(offset);
}

ForLoop::ForLoop(Position position, Optional<NameWithPosition> variable, Optional<NameWithPosition> index_variable, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<Position> in_kw_position, Optional<Position> index_kw_position)
    : Node(move(position))
    , m_variable(move(variable))
    , m_index_variable(move(index_variable))
    , m_iterated_expression(move(iterated_expr))
    , m_block(move(block))
    , m_in_kw_position(move(in_kw_position))
    , m_index_kw_position(move(index_kw_position))
{
    if (m_iterated_expression && m_iterated_expression->is_syntax_error())
        set_is_syntax_error(m_iterated_expression->syntax_error_node());
    else if (m_block && m_block->is_syntax_error())
        set_is_syntax_error(m_block->syntax_error_node());
}

ForLoop::~ForLoop()
{
}

void Glob::dump(int level) const
{
    Node::dump(level);
    print_indented(m_text, level + 1);
}

RefPtr<Value> Glob::run(RefPtr<Shell>)
{
    return make_ref_counted<GlobValue>(m_text, position());
}

void Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
{
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
    if (metadata.is_first_in_list)
        style.unify_with({ Line::Style::Bold });
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
}

Glob::Glob(Position position, String text)
    : Node(move(position))
    , m_text(move(text))
{
}

Glob::~Glob()
{
}

void Heredoc::dump(int level) const
{
    Node::dump(level);
    print_indented("(End Key)"sv, level + 1);
    print_indented(m_end, level + 2);
    print_indented("(Allows Interpolation)"sv, level + 1);
    print_indented(String::formatted("{}", m_allows_interpolation), level + 2);
    print_indented("(Contents)"sv, level + 1);
    if (m_contents)
        m_contents->dump(level + 2);
    else
        print_indented("(null)"sv, level + 2);
}

RefPtr<Value> Heredoc::run(RefPtr<Shell> shell)
{
    if (!m_deindent)
        return m_contents->run(shell);

    // To deindent, first split to lines...
    auto value = m_contents->run(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (!value)
        return value;
    auto list = value->resolve_as_list(shell);
    // The list better have one entry, otherwise we've put the wrong kind of node inside this heredoc
    VERIFY(list.size() == 1);
    auto lines = list.first().split_view('\n');

    // Now just trim each line and put them back in a string
    StringBuilder builder { list.first().length() };
    for (auto& line : lines) {
        builder.append(line.trim_whitespace(TrimMode::Left));
        builder.append('\n');
    }

    return make_ref_counted<StringValue>(builder.to_string());
}

void Heredoc::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    Line::Style content_style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
    if (metadata.is_first_in_list)
        content_style.unify_with({ Line::Style::Bold });

    if (!m_contents)
        content_style.unify_with({ Line::Style::Foreground(Line::Style::XtermColor::Red) }, true);

    editor.stylize({ m_position.start_offset, m_position.end_offset }, content_style);
    if (m_contents)
        m_contents->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Heredoc::hit_test_position(size_t offset) const
{
    if (!m_contents)
        return {};

    return m_contents->hit_test_position(offset);
}

Heredoc::Heredoc(Position position, String end, bool allow_interpolation, bool deindent)
    : Node(move(position))
    , m_end(move(end))
    , m_allows_interpolation(allow_interpolation)
    , m_deindent(deindent)
{
}

Heredoc::~Heredoc()
{
}

void HistoryEvent::dump(int level) const
{
    Node::dump(level);
    print_indented("Event Selector"sv, level + 1);
    switch (m_selector.event.kind) {
    case HistorySelector::EventKind::IndexFromStart:
        print_indented("IndexFromStart"sv, level + 2);
        break;
    case HistorySelector::EventKind::IndexFromEnd:
        print_indented("IndexFromEnd"sv, level + 2);
        break;
    case HistorySelector::EventKind::ContainingStringLookup:
        print_indented("ContainingStringLookup"sv, level + 2);
        break;
    case HistorySelector::EventKind::StartingStringLookup:
        print_indented("StartingStringLookup"sv, level + 2);
        break;
    }
    print_indented(String::formatted("{}({})", m_selector.event.index, m_selector.event.text), level + 3);

    print_indented("Word Selector"sv, level + 1);
    auto print_word_selector = [&](HistorySelector::WordSelector const& selector) {
        switch (selector.kind) {
        case HistorySelector::WordSelectorKind::Index:
            print_indented(String::formatted("Index {}", selector.selector), level + 3);
            break;
        case HistorySelector::WordSelectorKind::Last:
            print_indented(String::formatted("Last"), level + 3);
            break;
        }
    };

    if (m_selector.word_selector_range.end.has_value()) {
        print_indented("Range Start"sv, level + 2);
        print_word_selector(m_selector.word_selector_range.start);
        print_indented("Range End"sv, level + 2);
        print_word_selector(m_selector.word_selector_range.end.value());
    } else {
        print_indented("Direct Address"sv, level + 2);
        print_word_selector(m_selector.word_selector_range.start);
    }
}

RefPtr<Value> HistoryEvent::run(RefPtr<Shell> shell)
{
    if (!shell)
        return make_ref_counted<AST::ListValue>({});

    auto editor = shell->editor();
    if (!editor) {
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "No history available!", position());
        return make_ref_counted<AST::ListValue>({});
    }
    auto& history = editor->history();

    // FIXME: Implement reverse iterators and find()?
    auto find_reverse = [](auto it_start, auto it_end, auto finder) {
        auto it = it_end;
        while (it != it_start) {
            --it;
            if (finder(*it))
                return it;
        }
        return it_end;
    };
    // First, resolve the event itself.
    String resolved_history;
    switch (m_selector.event.kind) {
    case HistorySelector::EventKind::IndexFromStart:
        if (m_selector.event.index >= history.size()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
            return make_ref_counted<AST::ListValue>({});
        }
        resolved_history = history[m_selector.event.index].entry;
        break;
    case HistorySelector::EventKind::IndexFromEnd:
        if (m_selector.event.index >= history.size()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
            return make_ref_counted<AST::ListValue>({});
        }
        resolved_history = history[history.size() - m_selector.event.index - 1].entry;
        break;
    case HistorySelector::EventKind::ContainingStringLookup: {
        auto it = find_reverse(history.begin(), history.end(), [&](auto& entry) { return entry.entry.contains(m_selector.event.text); });
        if (it.is_end()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
            return make_ref_counted<AST::ListValue>({});
        }
        resolved_history = it->entry;
        break;
    }
    case HistorySelector::EventKind::StartingStringLookup: {
        auto it = find_reverse(history.begin(), history.end(), [&](auto& entry) { return entry.entry.starts_with(m_selector.event.text); });
        if (it.is_end()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
            return make_ref_counted<AST::ListValue>({});
        }
        resolved_history = it->entry;
        break;
    }
    }

    // Then, split it up to "words".
    auto nodes = Parser { resolved_history }.parse_as_multiple_expressions();

    // Now take the "words" as described by the word selectors.
    bool is_range = m_selector.word_selector_range.end.has_value();
    if (is_range) {
        auto start_index = m_selector.word_selector_range.start.resolve(nodes.size());
        auto end_index = m_selector.word_selector_range.end->resolve(nodes.size());
        if (start_index >= nodes.size()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
            return make_ref_counted<AST::ListValue>({});
        }
        if (end_index >= nodes.size()) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.end->position);
            return make_ref_counted<AST::ListValue>({});
        }

        decltype(nodes) resolved_nodes;
        resolved_nodes.append(nodes.data() + start_index, end_index - start_index + 1);
        NonnullRefPtr<AST::Node> list = make_ref_counted<AST::ListConcatenate>(position(), move(resolved_nodes));
        return list->run(shell);
    }

    auto index = m_selector.word_selector_range.start.resolve(nodes.size());
    if (index >= nodes.size()) {
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
        return make_ref_counted<AST::ListValue>({});
    }
    return nodes[index].run(shell);
}

void HistoryEvent::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
{
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Green) };
    if (metadata.is_first_in_list)
        style.unify_with({ Line::Style::Bold });
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
}

HistoryEvent::HistoryEvent(Position position, HistorySelector selector)
    : Node(move(position))
    , m_selector(move(selector))
{
    if (m_selector.word_selector_range.start.syntax_error_node)
        set_is_syntax_error(*m_selector.word_selector_range.start.syntax_error_node);
    else if (m_selector.word_selector_range.end.has_value() && m_selector.word_selector_range.end->syntax_error_node)
        set_is_syntax_error(*m_selector.word_selector_range.end->syntax_error_node);
}

HistoryEvent::~HistoryEvent()
{
}

void Execute::dump(int level) const
{
    Node::dump(level);
    if (m_capture_stdout)
        print_indented("(Capturing stdout)"sv, level + 1);
    m_command->dump(level + 1);
}

void Execute::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
{
    if (m_command->would_execute())
        return m_command->for_each_entry(shell, move(callback));

    auto unexpanded_commands = m_command->run(shell)->resolve_as_commands(shell);
    if (shell && shell->has_any_error())
        return;

    if (!shell)
        return;

    auto commands = shell->expand_aliases(move(unexpanded_commands));

    if (m_capture_stdout) {
        // Make sure that we're going to be running _something_.
        auto has_one_command = false;
        for (auto& command : commands) {
            if (command.argv.is_empty() && !command.pipeline && command.next_chain.is_empty())
                continue;
            has_one_command = true;
            break;
        }

        if (!has_one_command) {
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Cannot capture standard output when no command is being executed", m_position);
            return;
        }
        int pipefd[2];
        int rc = pipe(pipefd);
        if (rc < 0) {
            dbgln("Error: cannot pipe(): {}", strerror(errno));
            return;
        }
        auto& last_in_commands = commands.last();

        last_in_commands.redirections.prepend(FdRedirection::create(pipefd[1], STDOUT_FILENO, Rewiring::Close::Old));
        last_in_commands.should_wait = false;
        last_in_commands.should_notify_if_in_background = false;
        last_in_commands.is_pipe_source = false;

        Core::EventLoop loop;

        auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
        DuplexMemoryStream stream;

        enum {
            Continue,
            Break,
            NothingLeft,
        };
        auto check_and_call = [&] {
            auto ifs = shell->local_variable_or("IFS"sv, "\n"sv);

            if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
                auto line_end = offset.value();
                if (line_end == 0) {
                    auto rc = stream.discard_or_error(ifs.length());
                    VERIFY(rc);

                    if (shell->options.inline_exec_keep_empty_segments)
                        if (callback(make_ref_counted<StringValue>("")) == IterationDecision::Break) {
                            loop.quit(Break);
                            notifier->set_enabled(false);
                            return Break;
                        }
                } else {
                    auto entry_result = ByteBuffer::create_uninitialized(line_end + ifs.length());
                    if (entry_result.is_error()) {
                        loop.quit(Break);
                        notifier->set_enabled(false);
                        return Break;
                    }
                    auto entry = entry_result.release_value();
                    auto rc = stream.read_or_error(entry);
                    VERIFY(rc);

                    auto str = StringView(entry.data(), entry.size() - ifs.length());
                    if (callback(make_ref_counted<StringValue>(str)) == IterationDecision::Break) {
                        loop.quit(Break);
                        notifier->set_enabled(false);
                        return Break;
                    }
                }

                return Continue;
            }

            return NothingLeft;
        };

        notifier->on_ready_to_read = [&] {
            constexpr static auto buffer_size = 16;
            u8 buffer[buffer_size];
            size_t remaining_size = buffer_size;

            for (;;) {
                notifier->set_event_mask(Core::Notifier::None);
                bool should_enable_notifier = false;

                ScopeGuard notifier_enabler { [&] {
                    if (should_enable_notifier)
                        notifier->set_event_mask(Core::Notifier::Read);
                } };

                if (check_and_call() == Break) {
                    loop.quit(Break);
                    return;
                }

                auto read_size = read(pipefd[0], buffer, remaining_size);
                if (read_size < 0) {
                    int saved_errno = errno;
                    if (saved_errno == EINTR) {
                        should_enable_notifier = true;
                        continue;
                    }
                    if (saved_errno == 0)
                        continue;
                    dbgln("read() failed: {}", strerror(saved_errno));
                    break;
                }
                if (read_size == 0)
                    break;

                should_enable_notifier = true;
                stream.write({ buffer, (size_t)read_size });
            }

            loop.quit(NothingLeft);
        };

        auto jobs = shell->run_commands(commands);
        ScopeGuard kill_jobs_if_around { [&] {
            for (auto& job : jobs) {
                if (job.is_running_in_background() && !job.exited() && !job.signaled()) {
                    job.set_should_announce_signal(false); // We're explicitly killing it here.
                    shell->kill_job(&job, SIGTERM);
                }
            }
        } };

        auto exit_reason = loop.exec();

        notifier->on_ready_to_read = nullptr;

        if (close(pipefd[0]) < 0) {
            dbgln("close() failed: {}", strerror(errno));
        }

        if (exit_reason != Break && !stream.eof()) {
            auto action = Continue;
            do {
                action = check_and_call();
                if (action == Break)
                    return;
            } while (action == Continue);

            if (!stream.eof()) {
                auto entry_result = ByteBuffer::create_uninitialized(stream.size());
                if (entry_result.is_error()) {
                    shell->raise_error(Shell::ShellError::OutOfMemory, {}, position());
                    return;
                }
                auto entry = entry_result.release_value();
                auto rc = stream.read_or_error(entry);
                VERIFY(rc);
                callback(make_ref_counted<StringValue>(String::copy(entry)));
            }
        }

        return;
    }

    auto jobs = shell->run_commands(commands);

    if (!jobs.is_empty())
        callback(make_ref_counted<JobValue>(&jobs.last()));
}

RefPtr<Value> Execute::run(RefPtr<Shell> shell)
{
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (m_command->would_execute())
        return m_command->run(shell);

    NonnullRefPtrVector<Value> values;
    for_each_entry(shell, [&](auto value) {
        values.append(*value);
        return IterationDecision::Continue;
    });

    if (values.size() == 1 && values.first().is_job())
        return values.first();

    return make_ref_counted<ListValue>(move(values));
}

void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    if (m_capture_stdout)
        editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
    metadata.is_first_in_list = true;
    m_command->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Execute::hit_test_position(size_t offset) const
{
    auto result = m_command->hit_test_position(offset);
    if (!result.closest_node_with_semantic_meaning)
        result.closest_node_with_semantic_meaning = this;
    if (!result.closest_command_node)
        result.closest_command_node = m_command;
    return result;
}

Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node || !matching_node->is_bareword())
        return {};

    auto corrected_offset = offset - matching_node->position().start_offset;
    auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());

    if (corrected_offset > node->text().length())
        return {};

    return shell.complete_program_name(node->text(), corrected_offset);
}

Execute::Execute(Position position, NonnullRefPtr<Node> command, bool capture_stdout)
    : Node(move(position))
    , m_command(move(command))
    , m_capture_stdout(capture_stdout)
{
    if (m_command->is_syntax_error())
        set_is_syntax_error(m_command->syntax_error_node());
}

Execute::~Execute()
{
}

void IfCond::dump(int level) const
{
    Node::dump(level);
    print_indented("Condition"sv, ++level);
    m_condition->dump(level + 1);
    print_indented("True Branch"sv, level);
    if (m_true_branch)
        m_true_branch->dump(level + 1);
    else
        print_indented("(empty)"sv, level + 1);
    print_indented("False Branch"sv, level);
    if (m_false_branch)
        m_false_branch->dump(level + 1);
    else
        print_indented("(empty)"sv, level + 1);
}

RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
{
    auto cond = m_condition->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    // The condition could be a builtin, in which case it has already run and exited.
    if (cond->is_job()) {
        auto cond_job_value = static_cast<JobValue const*>(cond.ptr());
        auto cond_job = cond_job_value->job();

        shell->block_on_job(cond_job);
    }
    if (shell->last_return_code == 0) {
        if (m_true_branch)
            return m_true_branch->run(shell);
    } else {
        if (m_false_branch)
            return m_false_branch->run(shell);
    }

    return make_ref_counted<ListValue>({});
}

void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    metadata.is_first_in_list = true;

    editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
    if (m_else_position.has_value())
        editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

    m_condition->highlight_in_editor(editor, shell, metadata);
    if (m_true_branch)
        m_true_branch->highlight_in_editor(editor, shell, metadata);
    if (m_false_branch)
        m_false_branch->highlight_in_editor(editor, shell, metadata);
}

HitTestResult IfCond::hit_test_position(size_t offset) const
{
    if (auto result = m_condition->hit_test_position(offset); result.matching_node)
        return result;

    if (m_true_branch) {
        if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
            return result;
    }

    if (m_false_branch) {
        if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
            return result;
    }

    return {};
}

IfCond::IfCond(Position position, Optional<Position> else_position, NonnullRefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
    : Node(move(position))
    , m_condition(move(condition))
    , m_true_branch(move(true_branch))
    , m_false_branch(move(false_branch))
    , m_else_position(move(else_position))
{
    if (m_condition->is_syntax_error())
        set_is_syntax_error(m_condition->syntax_error_node());
    else if (m_true_branch && m_true_branch->is_syntax_error())
        set_is_syntax_error(m_true_branch->syntax_error_node());
    else if (m_false_branch && m_false_branch->is_syntax_error())
        set_is_syntax_error(m_false_branch->syntax_error_node());

    m_condition = make_ref_counted<AST::Execute>(m_condition->position(), m_condition);

    if (m_true_branch) {
        auto true_branch = m_true_branch.release_nonnull();
        if (true_branch->is_execute())
            m_true_branch = static_ptr_cast<AST::Execute>(true_branch)->command();
        else
            m_true_branch = move(true_branch);
    }

    if (m_false_branch) {
        auto false_branch = m_false_branch.release_nonnull();
        if (false_branch->is_execute())
            m_false_branch = static_ptr_cast<AST::Execute>(false_branch)->command();
        else
            m_false_branch = move(false_branch);
    }
}

IfCond::~IfCond()
{
}

void ImmediateExpression::dump(int level) const
{
    Node::dump(level);
    print_indented("(function)"sv, level + 1);
    print_indented(m_function.name, level + 2);
    print_indented("(arguments)"sv, level + 1);
    for (auto& argument : arguments())
        argument.dump(level + 2);
}

RefPtr<Value> ImmediateExpression::run(RefPtr<Shell> shell)
{
    auto node = shell->run_immediate_function(m_function.name, *this, arguments());
    if (node)
        return node->run(shell);

    return make_ref_counted<ListValue>({});
}

void ImmediateExpression::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    // '${' - FIXME: This could also be '$\\\n{'
    editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });

    // Function name
    Line::Style function_style { Line::Style::Foreground(Line::Style::XtermColor::Red) };
    if (shell.has_immediate_function(function_name()))
        function_style = { Line::Style::Foreground(Line::Style::XtermColor::Green) };
    editor.stylize({ m_function.position.start_offset, m_function.position.end_offset }, move(function_style));

    // Arguments
    for (auto& argument : m_arguments) {
        metadata.is_first_in_list = false;
        argument.highlight_in_editor(editor, shell, metadata);
    }

    // Closing brace
    if (m_closing_brace_position.has_value())
        editor.stylize({ m_closing_brace_position->start_offset, m_closing_brace_position->end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
}

Vector<Line::CompletionSuggestion> ImmediateExpression::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node || matching_node != this)
        return {};

    auto corrected_offset = offset - m_function.position.start_offset;

    if (corrected_offset > m_function.name.length())
        return {};

    return shell.complete_immediate_function_name(m_function.name, corrected_offset);
}

HitTestResult ImmediateExpression::hit_test_position(size_t offset) const
{
    if (m_function.position.contains(offset))
        return { this, this, this };

    for (auto& argument : m_arguments) {
        if (auto result = argument.hit_test_position(offset); result.matching_node)
            return result;
    }

    return {};
}

ImmediateExpression::ImmediateExpression(Position position, NameWithPosition function, NonnullRefPtrVector<AST::Node> arguments, Optional<Position> closing_brace_position)
    : Node(move(position))
    , m_arguments(move(arguments))
    , m_function(move(function))
    , m_closing_brace_position(move(closing_brace_position))
{
    if (is_syntax_error())
        return;

    for (auto& argument : m_arguments) {
        if (argument.is_syntax_error()) {
            set_is_syntax_error(argument.syntax_error_node());
            return;
        }
    }
}

ImmediateExpression::~ImmediateExpression()
{
}

void Join::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> Join::run(RefPtr<Shell> shell)
{
    auto left = m_left->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (left.last().should_wait && !left.last().next_chain.is_empty()) {
        // Join (C0s*; C1) X -> (C0s*; Join C1 X)
        auto& lhs_node = left.last().next_chain.last().node;
        lhs_node = make_ref_counted<Join>(m_position, lhs_node, m_right);
        return make_ref_counted<CommandSequenceValue>(move(left));
    }

    auto right = m_right->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    return make_ref_counted<CommandSequenceValue>(join_commands(move(left), move(right)));
}

void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_left->highlight_in_editor(editor, shell, metadata);
    if (m_left->is_list() || m_left->is_command())
        metadata.is_first_in_list = false;
    m_right->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Join::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (result.matching_node)
        return result;

    return m_right->hit_test_position(offset);
}

RefPtr<Node> Join::leftmost_trivial_literal() const
{
    if (auto value = m_left->leftmost_trivial_literal())
        return value;
    return m_right->leftmost_trivial_literal();
}

Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

Join::~Join()
{
}

void MatchExpr::dump(int level) const
{
    Node::dump(level);
    print_indented(String::formatted("(expression: {})", m_expr_name.characters()), level + 1);
    m_matched_expr->dump(level + 2);
    print_indented(String::formatted("(named: {})", m_expr_name.characters()), level + 1);
    print_indented("(entries)"sv, level + 1);
    for (auto& entry : m_entries) {
        StringBuilder builder;
        builder.append("(match"sv);
        if (entry.match_names.has_value()) {
            builder.append(" to names ("sv);
            bool first = true;
            for (auto& name : entry.match_names.value()) {
                if (!first)
                    builder.append(' ');
                first = false;
                builder.append(name);
            }
            builder.append("))"sv);

        } else {
            builder.append(')');
        }
        print_indented(builder.string_view(), level + 2);
        entry.options.visit(
            [&](NonnullRefPtrVector<Node> const& options) {
                for (auto& option : options)
                    option.dump(level + 3);
            },
            [&](Vector<Regex<ECMA262>> const& options) {
                for (auto& option : options)
                    print_indented(String::formatted("(regex: {})", option.pattern_value), level + 3);
            });
        print_indented("(execute)"sv, level + 2);
        if (entry.body)
            entry.body->dump(level + 3);
        else
            print_indented("(nothing)"sv, level + 3);
    }
}

RefPtr<Value> MatchExpr::run(RefPtr<Shell> shell)
{
    auto value = m_matched_expr->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto list = value->resolve_as_list(shell);

    auto list_matches = [&](auto&& pattern, auto& spans) {
        if constexpr (IsSame<RemoveCVReference<decltype(pattern)>, Regex<ECMA262>>) {
            if (list.size() != 1)
                return false;
            auto& subject = list.first();
            auto match = pattern.match(subject);
            if (!match.success)
                return false;

            spans.ensure_capacity(match.n_capture_groups);
            for (size_t i = 0; i < match.n_capture_groups; ++i) {
                auto& capture = match.capture_group_matches[0][i];
                spans.append(capture.view.to_string());
            }
            return true;
        } else {
            if (pattern.size() != list.size())
                return false;

            for (size_t i = 0; i < pattern.size(); ++i) {
                Vector<AK::MaskSpan> mask_spans;
                if (!list[i].matches(pattern[i], mask_spans))
                    return false;
                for (auto& span : mask_spans)
                    spans.append(list[i].substring(span.start, span.length));
            }

            return true;
        }
    };

    auto resolve_pattern = [&](auto& option) -> decltype(auto) {
        if constexpr (IsSame<RemoveCVReference<decltype(option)>, Regex<ECMA262>>) {
            return option;
        } else {
            Vector<String> pattern;
            if (option.is_glob()) {
                pattern.append(static_cast<const Glob*>(&option)->text());
            } else if (option.is_bareword()) {
                pattern.append(static_cast<const BarewordLiteral*>(&option)->text());
            } else {
                auto list = option.run(shell);
                if (shell && shell->has_any_error())
                    return pattern;

                option.for_each_entry(shell, [&](auto&& value) {
                    pattern.extend(value->resolve_as_list(nullptr)); // Note: 'nullptr' incurs special behavior,
                                                                     //       asking the node for a 'raw' value.
                    return IterationDecision::Continue;
                });
            }

            return pattern;
        }
    };

    auto frame = shell->push_frame(String::formatted("match ({})", this));
    if (!m_expr_name.is_empty())
        shell->set_local_variable(m_expr_name, value, true);

    for (auto& entry : m_entries) {
        auto result = entry.options.visit([&](auto& options) -> Variant<IterationDecision, RefPtr<Value>> {
            for (auto& option : options) {
                Vector<String> spans;
                if (list_matches(resolve_pattern(option), spans)) {
                    if (entry.body) {
                        if (entry.match_names.has_value()) {
                            size_t i = 0;
                            for (auto& name : entry.match_names.value()) {
                                if (spans.size() > i)
                                    shell->set_local_variable(name, make_ref_counted<AST::StringValue>(spans[i]), true);
                                ++i;
                            }
                        }
                        return entry.body->run(shell);
                    }
                    return RefPtr<Value>(make_ref_counted<AST::ListValue>({}));
                }
            }
            return IterationDecision::Continue;
        });
        if (result.has<IterationDecision>() && result.get<IterationDecision>() == IterationDecision::Break)
            break;

        if (result.has<RefPtr<Value>>())
            return move(result).get<RefPtr<Value>>();
    }

    shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
    return make_ref_counted<AST::ListValue>({});
}

void MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
    if (m_as_position.has_value())
        editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

    metadata.is_first_in_list = false;
    m_matched_expr->highlight_in_editor(editor, shell, metadata);

    for (auto& entry : m_entries) {
        metadata.is_first_in_list = false;
        entry.options.visit(
            [&](NonnullRefPtrVector<Node>& node_options) {
                for (auto& option : node_options)
                    option.highlight_in_editor(editor, shell, metadata);
            },
            [](auto&) {});

        metadata.is_first_in_list = true;
        if (entry.body)
            entry.body->highlight_in_editor(editor, shell, metadata);

        for (auto& position : entry.pipe_positions)
            editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

        if (entry.match_as_position.has_value())
            editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
    }
}

HitTestResult MatchExpr::hit_test_position(size_t offset) const
{
    auto result = m_matched_expr->hit_test_position(offset);
    if (result.matching_node)
        return result;

    for (auto& entry : m_entries) {
        if (!entry.body)
            continue;
        auto result = entry.body->hit_test_position(offset);
        if (result.matching_node)
            return result;
    }

    return {};
}

MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
    : Node(move(position))
    , m_matched_expr(move(expr))
    , m_expr_name(move(name))
    , m_as_position(move(as_position))
    , m_entries(move(entries))
{
    if (m_matched_expr->is_syntax_error()) {
        set_is_syntax_error(m_matched_expr->syntax_error_node());
    } else {
        for (auto& entry : m_entries) {
            if (!entry.body)
                continue;
            if (entry.body->is_syntax_error()) {
                set_is_syntax_error(entry.body->syntax_error_node());
                break;
            }
        }
    }
}

MatchExpr::~MatchExpr()
{
}

void Or::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> Or::run(RefPtr<Shell> shell)
{
    auto commands = m_left->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
    return make_ref_counted<CommandSequenceValue>(move(commands));
}

void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_left->highlight_in_editor(editor, shell, metadata);
    m_right->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Or::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (result.matching_node) {
        if (!result.closest_command_node)
            result.closest_command_node = m_right;
        return result;
    }

    result = m_right->hit_test_position(offset);
    if (!result.closest_command_node)
        result.closest_command_node = m_right;
    return result;
}

Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
    , m_or_position(or_position)
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

Or::~Or()
{
}

void Pipe::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
{
    auto left = m_left->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto right = m_right->to_lazy_evaluated_commands(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto last_in_left = left.take_last();
    auto first_in_right = right.take_first();

    auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
    auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);

    auto insert_at_start_or_after_last_pipe = [&](auto& pipe, auto& command) {
        size_t insert_index = 0;
        auto& redirections = command.redirections;
        for (ssize_t i = redirections.size() - 1; i >= 0; --i) {
            auto& redirection = redirections[i];
            if (!redirection.is_fd_redirection())
                continue;
            auto& fd_redirection = static_cast<FdRedirection&>(redirection);
            if (fd_redirection.old_fd == -1) {
                insert_index = i;
                break;
            }
        }

        redirections.insert(insert_index, pipe);
    };

    insert_at_start_or_after_last_pipe(pipe_read_end, first_in_right);
    insert_at_start_or_after_last_pipe(pipe_write_end, last_in_left);

    last_in_left.should_wait = false;
    last_in_left.is_pipe_source = true;

    if (first_in_right.pipeline) {
        last_in_left.pipeline = first_in_right.pipeline;
    } else {
        auto pipeline = make_ref_counted<Pipeline>();
        last_in_left.pipeline = pipeline;
        first_in_right.pipeline = pipeline;
    }

    Vector<Command> commands;
    commands.extend(left);
    commands.append(last_in_left);
    commands.append(first_in_right);
    commands.extend(right);

    return make_ref_counted<CommandSequenceValue>(move(commands));
}

void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_left->highlight_in_editor(editor, shell, metadata);
    m_right->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Pipe::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (result.matching_node) {
        if (!result.closest_command_node)
            result.closest_command_node = m_right;
        return result;
    }

    result = m_right->hit_test_position(offset);
    if (!result.closest_command_node)
        result.closest_command_node = m_right;
    return result;
}

Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

Pipe::~Pipe()
{
}

PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
    : Node(move(position))
    , m_fd(fd)
    , m_path(move(path))
{
}

void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
    metadata.is_first_in_list = false;
    m_path->highlight_in_editor(editor, shell, metadata);
    if (m_path->is_bareword()) {
        auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
        VERIFY(path_text.size() == 1);
        // Apply a URL to the path.
        auto& position = m_path->position();
        auto& path = path_text[0];
        if (!path.starts_with('/'))
            path = String::formatted("{}/{}", shell.cwd, path);
        auto url = URL::create_with_file_protocol(path);
        url.set_host(shell.hostname);
        editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
    }
}

HitTestResult PathRedirectionNode::hit_test_position(size_t offset) const
{
    auto result = m_path->hit_test_position(offset);
    if (!result.closest_node_with_semantic_meaning)
        result.closest_node_with_semantic_meaning = this;
    return result;
}

Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node || !matching_node->is_bareword())
        return {};

    auto corrected_offset = offset - matching_node->position().start_offset;
    auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());

    if (corrected_offset > node->text().length())
        return {};

    return shell.complete_path(""sv, node->text(), corrected_offset, Shell::ExecutableOnly::No, nullptr, nullptr);
}

PathRedirectionNode::~PathRedirectionNode()
{
}

void Range::dump(int level) const
{
    Node::dump(level);
    print_indented("(From)"sv, level + 1);
    m_start->dump(level + 2);
    print_indented("(To)"sv, level + 1);
    m_end->dump(level + 2);
}

RefPtr<Value> Range::run(RefPtr<Shell> shell)
{
    auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> NonnullRefPtrVector<Value> {
        NonnullRefPtrVector<Value> values;

        if (start->is_string() && end->is_string()) {
            auto start_str = start->resolve_as_list(shell)[0];
            auto end_str = end->resolve_as_list(shell)[0];

            Utf8View start_view { start_str }, end_view { end_str };
            if (start_view.validate() && end_view.validate()) {
                if (start_view.length() == 1 && end_view.length() == 1) {
                    // Interpolate between two code points.
                    auto start_code_point = *start_view.begin();
                    auto end_code_point = *end_view.begin();
                    auto step = start_code_point > end_code_point ? -1 : 1;
                    StringBuilder builder;
                    for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
                        builder.clear();
                        builder.append_code_point(code_point);
                        values.append(make_ref_counted<StringValue>(builder.to_string()));
                    }
                    // Append the ending code point too, most shells treat this as inclusive.
                    builder.clear();
                    builder.append_code_point(end_code_point);
                    values.append(make_ref_counted<StringValue>(builder.to_string()));
                } else {
                    // Could be two numbers?
                    auto start_int = start_str.to_int();
                    auto end_int = end_str.to_int();
                    if (start_int.has_value() && end_int.has_value()) {
                        auto start = start_int.value();
                        auto end = end_int.value();
                        auto step = start > end ? -1 : 1;
                        for (int value = start; value != end; value += step)
                            values.append(make_ref_counted<StringValue>(String::number(value)));
                        // Append the range end too, most shells treat this as inclusive.
                        values.append(make_ref_counted<StringValue>(String::number(end)));
                    } else {
                        goto yield_start_end;
                    }
                }
            } else {
            yield_start_end:;
                shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, String::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
                // We can't really interpolate between the two, so just yield both.
                values.append(make_ref_counted<StringValue>(move(start_str)));
                values.append(make_ref_counted<StringValue>(move(end_str)));
            }

            return values;
        }

        warnln("Shell: Cannot apply the requested interpolation");
        return values;
    };

    auto start_value = m_start->run(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto end_value = m_end->run(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    if (!start_value || !end_value)
        return make_ref_counted<ListValue>({});

    return make_ref_counted<ListValue>(interpolate(*start_value, *end_value, shell));
}

void Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_start->highlight_in_editor(editor, shell, metadata);

    // Highlight the '..'
    editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });

    metadata.is_first_in_list = false;
    m_end->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Range::hit_test_position(size_t offset) const
{
    auto result = m_start->hit_test_position(offset);
    if (result.matching_node) {
        if (!result.closest_command_node)
            result.closest_command_node = m_start;
        return result;
    }

    result = m_end->hit_test_position(offset);
    if (!result.closest_command_node)
        result.closest_command_node = m_end;
    return result;
}

Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
    : Node(move(position))
    , m_start(move(start))
    , m_end(move(end))
{
    if (m_start->is_syntax_error())
        set_is_syntax_error(m_start->syntax_error_node());
    else if (m_end->is_syntax_error())
        set_is_syntax_error(m_end->syntax_error_node());
}

Range::~Range()
{
}

void ReadRedirection::dump(int level) const
{
    Node::dump(level);
    m_path->dump(level + 1);
    print_indented(String::formatted("To {}", m_fd), level + 1);
}

RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
{
    Command command;
    auto path_segments = m_path->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    StringBuilder builder;
    builder.join(' ', path_segments);

    command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
    return make_ref_counted<CommandValue>(move(command));
}

ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
    : PathRedirectionNode(move(position), fd, move(path))
{
}

ReadRedirection::~ReadRedirection()
{
}

void ReadWriteRedirection::dump(int level) const
{
    Node::dump(level);
    m_path->dump(level + 1);
    print_indented(String::formatted("To/From {}", m_fd), level + 1);
}

RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
{
    Command command;
    auto path_segments = m_path->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    StringBuilder builder;
    builder.join(' ', path_segments);

    command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
    return make_ref_counted<CommandValue>(move(command));
}

ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
    : PathRedirectionNode(move(position), fd, move(path))
{
}

ReadWriteRedirection::~ReadWriteRedirection()
{
}

void Sequence::dump(int level) const
{
    Node::dump(level);
    for (auto& entry : m_entries)
        entry.dump(level + 1);
}

RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
{
    Vector<Command> all_commands;
    Command* last_command_in_sequence = nullptr;
    for (auto& entry : m_entries) {
        if (shell && shell->has_any_error())
            break;
        if (!last_command_in_sequence) {
            auto commands = entry.to_lazy_evaluated_commands(shell);
            all_commands.extend(move(commands));
            last_command_in_sequence = &all_commands.last();
            continue;
        }

        if (last_command_in_sequence->should_wait) {
            last_command_in_sequence->next_chain.append(NodeWithAction { entry, NodeWithAction::Sequence });
        } else {
            all_commands.extend(entry.to_lazy_evaluated_commands(shell));
            last_command_in_sequence = &all_commands.last();
        }
    }

    return make_ref_counted<CommandSequenceValue>(move(all_commands));
}

void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    for (auto& entry : m_entries)
        entry.highlight_in_editor(editor, shell, metadata);
}

HitTestResult Sequence::hit_test_position(size_t offset) const
{
    for (auto& entry : m_entries) {
        auto result = entry.hit_test_position(offset);
        if (result.matching_node) {
            if (!result.closest_command_node)
                result.closest_command_node = entry;
            return result;
        }
    }

    return {};
}

RefPtr<Node> Sequence::leftmost_trivial_literal() const
{
    for (auto& entry : m_entries) {
        if (auto node = entry.leftmost_trivial_literal())
            return node;
    }
    return nullptr;
}

Sequence::Sequence(Position position, NonnullRefPtrVector<Node> entries, Vector<Position> separator_positions)
    : Node(move(position))
    , m_entries(move(entries))
    , m_separator_positions(separator_positions)
{
    for (auto& entry : m_entries) {
        if (entry.is_syntax_error()) {
            set_is_syntax_error(entry.syntax_error_node());
            break;
        }
    }
}

Sequence::~Sequence()
{
}

void Subshell::dump(int level) const
{
    Node::dump(level);
    if (m_block)
        m_block->dump(level + 1);
}

RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
{
    if (!m_block)
        return make_ref_counted<ListValue>({});

    return make_ref_counted<AST::CommandSequenceValue>(m_block->to_lazy_evaluated_commands(shell));
}

void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    metadata.is_first_in_list = true;
    if (m_block)
        m_block->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Subshell::hit_test_position(size_t offset) const
{
    if (m_block)
        return m_block->hit_test_position(offset);

    return {};
}

Subshell::Subshell(Position position, RefPtr<Node> block)
    : Node(move(position))
    , m_block(block)
{
    if (m_block && m_block->is_syntax_error())
        set_is_syntax_error(m_block->syntax_error_node());
}

Subshell::~Subshell()
{
}

void Slice::dump(int level) const
{
    Node::dump(level);
    m_selector->dump(level + 1);
}

RefPtr<Value> Slice::run(RefPtr<Shell> shell)
{
    return m_selector->run(shell);
}

void Slice::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_selector->highlight_in_editor(editor, shell, metadata);
}

HitTestResult Slice::hit_test_position(size_t offset) const
{
    return m_selector->hit_test_position(offset);
}

Vector<Line::CompletionSuggestion> Slice::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    // TODO: Maybe intercept this, and suggest values in range?
    return m_selector->complete_for_editor(shell, offset, hit_test_result);
}

Slice::Slice(Position position, NonnullRefPtr<AST::Node> selector)
    : Node(move(position))
    , m_selector(move(selector))
{
    if (m_selector->is_syntax_error())
        set_is_syntax_error(m_selector->syntax_error_node());
}

Slice::~Slice()
{
}

void SimpleVariable::dump(int level) const
{
    Node::dump(level);
    print_indented("(Name)"sv, level + 1);
    print_indented(m_name, level + 2);
    print_indented("(Slice)"sv, level + 1);
    if (m_slice)
        m_slice->dump(level + 2);
    else
        print_indented("(None)"sv, level + 2);
}

RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
{
    NonnullRefPtr<Value> value = make_ref_counted<SimpleVariableValue>(m_name);
    if (m_slice)
        value = value->with_slices(*m_slice);
    return value;
}

void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    Line::Style style { Line::Style::Foreground(214, 112, 214) };
    if (metadata.is_first_in_list)
        style.unify_with({ Line::Style::Bold });
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
    if (m_slice)
        m_slice->highlight_in_editor(editor, shell, metadata);
}

HitTestResult SimpleVariable::hit_test_position(size_t offset) const
{
    if (!position().contains(offset))
        return {};

    if (m_slice && m_slice->position().contains(offset))
        return m_slice->hit_test_position(offset);

    return { this, this, nullptr };
}

Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node)
        return {};

    if (matching_node != this)
        return {};

    auto corrected_offset = offset - matching_node->position().start_offset - 1;

    if (corrected_offset > m_name.length() + 1)
        return {};

    return shell.complete_variable(m_name, corrected_offset);
}

SimpleVariable::SimpleVariable(Position position, String name)
    : VariableNode(move(position))
    , m_name(move(name))
{
}

SimpleVariable::~SimpleVariable()
{
}

void SpecialVariable::dump(int level) const
{
    Node::dump(level);
    print_indented("(Name)"sv, level + 1);
    print_indented(String { &m_name, 1 }, level + 1);
    print_indented("(Slice)"sv, level + 1);
    if (m_slice)
        m_slice->dump(level + 2);
    else
        print_indented("(None)"sv, level + 2);
}

RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
{
    NonnullRefPtr<Value> value = make_ref_counted<SpecialVariableValue>(m_name);
    if (m_slice)
        value = value->with_slices(*m_slice);
    return value;
}

void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
    if (m_slice)
        m_slice->highlight_in_editor(editor, shell, metadata);
}

Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, HitTestResult const&)
{
    return {};
}

HitTestResult SpecialVariable::hit_test_position(size_t offset) const
{
    if (m_slice && m_slice->position().contains(offset))
        return m_slice->hit_test_position(offset);

    return { this, this, nullptr };
}

SpecialVariable::SpecialVariable(Position position, char name)
    : VariableNode(move(position))
    , m_name(name)
{
}

SpecialVariable::~SpecialVariable()
{
}

void Juxtaposition::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
{
    auto left_value = m_left->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto right_value = m_right->run(shell)->resolve_without_cast(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto left = left_value->resolve_as_list(shell);
    auto right = right_value->resolve_as_list(shell);

    if (left_value->is_string() && right_value->is_string()) {

        VERIFY(left.size() == 1);
        VERIFY(right.size() == 1);

        StringBuilder builder;
        builder.append(left[0]);
        builder.append(right[0]);

        return make_ref_counted<StringValue>(builder.to_string());
    }

    // Otherwise, treat them as lists and create a list product.
    if (left.is_empty() || right.is_empty())
        return make_ref_counted<ListValue>({});

    Vector<String> result;
    result.ensure_capacity(left.size() * right.size());

    StringBuilder builder;
    for (auto& left_element : left) {
        for (auto& right_element : right) {
            builder.append(left_element);
            builder.append(right_element);
            result.append(builder.to_string());
            builder.clear();
        }
    }

    return make_ref_counted<ListValue>(move(result));
}

void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_left->highlight_in_editor(editor, shell, metadata);

    // '~/foo/bar' is special, we have to actually resolve the tilde
    // since that resolution is a pure operation, we can just go ahead
    // and do it to get the value :)
    if (m_right->is_bareword() && m_left->is_tilde()) {
        auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
        auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];

        StringBuilder path_builder;
        path_builder.append(tilde_value);
        path_builder.append('/');
        path_builder.append(bareword_value);
        auto path = path_builder.to_string();

        if (Core::File::exists(path)) {
            auto realpath = shell.resolve_path(path);
            auto url = URL::create_with_file_protocol(realpath);
            url.set_host(shell.hostname);
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
        }

    } else {
        m_right->highlight_in_editor(editor, shell, metadata);
    }
}

Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (m_left->would_execute() || m_right->would_execute()) {
        return {};
    }

    // '~/foo/bar' is special, we have to actually resolve the tilde
    // then complete the bareword with that path prefix.
    auto left_values = m_left->run(shell)->resolve_as_list(shell);

    if (left_values.is_empty())
        return m_right->complete_for_editor(shell, offset, hit_test_result);

    auto& left_value = left_values.first();

    auto right_values = m_right->run(shell)->resolve_as_list(shell);
    StringView right_value {};

    auto corrected_offset = offset - matching_node->position().start_offset;

    if (!right_values.is_empty())
        right_value = right_values.first();

    if (m_left->is_tilde() && !right_value.is_empty()) {
        right_value = right_value.substring_view(1);
        corrected_offset--;
    }

    if (corrected_offset > right_value.length())
        return {};

    return shell.complete_path(left_value, right_value, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node);
}

HitTestResult Juxtaposition::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (!result.closest_node_with_semantic_meaning)
        result.closest_node_with_semantic_meaning = this;
    if (result.matching_node)
        return result;

    result = m_right->hit_test_position(offset);
    if (!result.closest_node_with_semantic_meaning)
        result.closest_node_with_semantic_meaning = this;
    return result;
}

Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

Juxtaposition::~Juxtaposition()
{
}

void StringLiteral::dump(int level) const
{
    Node::dump(level);
    print_indented(m_text, level + 1);
}

RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
{
    return make_ref_counted<StringValue>(m_text);
}

void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
{
    if (m_text.is_empty())
        return;

    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
    if (metadata.is_first_in_list)
        style.unify_with({ Line::Style::Bold });
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
}

StringLiteral::StringLiteral(Position position, String text, EnclosureType enclosure_type)
    : Node(move(position))
    , m_text(move(text))
    , m_enclosure_type(enclosure_type)
{
}

StringLiteral::~StringLiteral()
{
}

void StringPartCompose::dump(int level) const
{
    Node::dump(level);
    m_left->dump(level + 1);
    m_right->dump(level + 1);
}

RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
{
    auto left = m_left->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    auto right = m_right->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    StringBuilder builder;
    builder.join(' ', left);
    builder.join(' ', right);

    return make_ref_counted<StringValue>(builder.to_string());
}

void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    m_left->highlight_in_editor(editor, shell, metadata);
    m_right->highlight_in_editor(editor, shell, metadata);
}

HitTestResult StringPartCompose::hit_test_position(size_t offset) const
{
    auto result = m_left->hit_test_position(offset);
    if (result.matching_node)
        return result;
    return m_right->hit_test_position(offset);
}

StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
    : Node(move(position))
    , m_left(move(left))
    , m_right(move(right))
{
    if (m_left->is_syntax_error())
        set_is_syntax_error(m_left->syntax_error_node());
    else if (m_right->is_syntax_error())
        set_is_syntax_error(m_right->syntax_error_node());
}

StringPartCompose::~StringPartCompose()
{
}

void SyntaxError::dump(int level) const
{
    Node::dump(level);
    print_indented("(Error text)"sv, level + 1);
    print_indented(m_syntax_error_text, level + 2);
    print_indented("(Can be recovered from)"sv, level + 1);
    print_indented(String::formatted("{}", m_is_continuable), level + 2);
}

RefPtr<Value> SyntaxError::run(RefPtr<Shell> shell)
{
    shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text, position());
    return make_ref_counted<StringValue>("");
}

void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
{
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
}

SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
    : Node(move(position))
    , m_syntax_error_text(move(error))
    , m_is_continuable(is_continuable)
{
}

SyntaxError const& SyntaxError::syntax_error_node() const
{
    return *this;
}

SyntaxError::~SyntaxError()
{
}

void SyntheticNode::dump(int level) const
{
    Node::dump(level);
}

RefPtr<Value> SyntheticNode::run(RefPtr<Shell>)
{
    return m_value;
}

void SyntheticNode::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
{
}

SyntheticNode::SyntheticNode(Position position, NonnullRefPtr<Value> value)
    : Node(move(position))
    , m_value(move(value))
{
}

void Tilde::dump(int level) const
{
    Node::dump(level);
    print_indented(m_username, level + 1);
}

RefPtr<Value> Tilde::run(RefPtr<Shell>)
{
    return make_ref_counted<TildeValue>(m_username);
}

void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
{
}

HitTestResult Tilde::hit_test_position(size_t offset) const
{
    if (!position().contains(offset))
        return {};

    return { this, this, nullptr };
}

Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
{
    auto matching_node = hit_test_result.matching_node;
    if (!matching_node)
        return {};

    if (matching_node != this)
        return {};

    auto corrected_offset = offset - matching_node->position().start_offset - 1;

    if (corrected_offset > m_username.length() + 1)
        return {};

    return shell.complete_user(m_username, corrected_offset);
}

String Tilde::text() const
{
    StringBuilder builder;
    builder.append('~');
    builder.append(m_username);
    return builder.to_string();
}

Tilde::Tilde(Position position, String username)
    : Node(move(position))
    , m_username(move(username))
{
}

Tilde::~Tilde()
{
}

void WriteAppendRedirection::dump(int level) const
{
    Node::dump(level);
    m_path->dump(level + 1);
    print_indented(String::formatted("From {}", m_fd), level + 1);
}

RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
{
    Command command;
    auto path_segments = m_path->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    StringBuilder builder;
    builder.join(' ', path_segments);

    command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
    return make_ref_counted<CommandValue>(move(command));
}

WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
    : PathRedirectionNode(move(position), fd, move(path))
{
}

WriteAppendRedirection::~WriteAppendRedirection()
{
}

void WriteRedirection::dump(int level) const
{
    Node::dump(level);
    m_path->dump(level + 1);
    print_indented(String::formatted("From {}", m_fd), level + 1);
}

RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
{
    Command command;
    auto path_segments = m_path->run(shell)->resolve_as_list(shell);
    if (shell && shell->has_any_error())
        return make_ref_counted<ListValue>({});

    StringBuilder builder;
    builder.join(' ', path_segments);

    command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
    return make_ref_counted<CommandValue>(move(command));
}

WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
    : PathRedirectionNode(move(position), fd, move(path))
{
}

WriteRedirection::~WriteRedirection()
{
}

void VariableDeclarations::dump(int level) const
{
    Node::dump(level);
    for (auto& var : m_variables) {
        print_indented("Set"sv, level + 1);
        var.name->dump(level + 2);
        var.value->dump(level + 2);
    }
}

RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
{
    for (auto& var : m_variables) {
        auto name_value = var.name->run(shell)->resolve_as_list(shell);
        if (shell && shell->has_any_error())
            break;

        VERIFY(name_value.size() == 1);
        auto name = name_value[0];
        auto value = var.value->run(shell);
        if (shell && shell->has_any_error())
            break;
        value = value->resolve_without_cast(shell);

        shell->set_local_variable(name, value.release_nonnull());
    }

    return make_ref_counted<ListValue>({});
}

void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
{
    metadata.is_first_in_list = false;
    for (auto& var : m_variables) {
        var.name->highlight_in_editor(editor, shell, metadata);
        // Highlight the '='.
        editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
        var.value->highlight_in_editor(editor, shell, metadata);
    }
}

HitTestResult VariableDeclarations::hit_test_position(size_t offset) const
{
    for (auto decl : m_variables) {
        auto result = decl.value->hit_test_position(offset);
        if (result.matching_node)
            return result;
    }

    return { nullptr, nullptr, nullptr };
}

VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
    : Node(move(position))
    , m_variables(move(variables))
{
    for (auto& decl : m_variables) {
        if (decl.name->is_syntax_error()) {
            set_is_syntax_error(decl.name->syntax_error_node());
            break;
        }
        if (decl.value->is_syntax_error()) {
            set_is_syntax_error(decl.value->syntax_error_node());
            break;
        }
    }
}

VariableDeclarations::~VariableDeclarations()
{
}

Value::~Value()
{
}

String Value::resolve_as_string(RefPtr<Shell> shell)
{
    if (shell)
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Conversion to string not allowed");
    return {};
}

Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
{
    Command command;
    command.argv = resolve_as_list(shell);
    return { command };
}

ListValue::ListValue(Vector<String> values)
{
    if (values.is_empty())
        return;
    m_contained_values.ensure_capacity(values.size());
    for (auto& str : values)
        m_contained_values.append(adopt_ref(*new StringValue(move(str))));
}

NonnullRefPtr<Value> Value::with_slices(NonnullRefPtr<Slice> slice) const&
{
    auto value = clone();
    value->m_slices.append(move(slice));
    return value;
}

NonnullRefPtr<Value> Value::with_slices(NonnullRefPtrVector<Slice> slices) const&
{
    auto value = clone();
    value->m_slices.extend(move(slices));
    return value;
}

ListValue::~ListValue()
{
}

Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
{
    Vector<String> values;
    for (auto& value : m_contained_values)
        values.extend(value.resolve_as_list(shell));

    return resolve_slices(shell, move(values), m_slices);
}

NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
{
    NonnullRefPtrVector<Value> values;
    for (auto& value : m_contained_values)
        values.append(value.resolve_without_cast(shell));

    NonnullRefPtr<Value> value = make_ref_counted<ListValue>(move(values));
    if (!m_slices.is_empty())
        value = value->with_slices(m_slices);
    return value;
}

CommandValue::~CommandValue()
{
}

CommandSequenceValue::~CommandSequenceValue()
{
}

Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell> shell)
{
    shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Unexpected cast of a command sequence to a list");
    return {};
}

Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
{
    return m_contained_values;
}

Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
{
    return m_command.argv;
}

Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
{
    return { m_command };
}

JobValue::~JobValue()
{
}

StringValue::~StringValue()
{
}

String StringValue::resolve_as_string(RefPtr<Shell> shell)
{
    if (m_split.is_null())
        return m_string;
    return Value::resolve_as_string(shell);
}

Vector<String> StringValue::resolve_as_list(RefPtr<Shell> shell)
{
    if (is_list()) {
        auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
        Vector<String> result;
        result.ensure_capacity(parts.size());
        for (auto& part : parts)
            result.append(part);
        return resolve_slices(shell, move(result), m_slices);
    }

    return { resolve_slices(shell, String { m_string }, m_slices) };
}

NonnullRefPtr<Value> StringValue::resolve_without_cast(RefPtr<Shell> shell)
{
    if (is_list())
        return make_ref_counted<AST::ListValue>(resolve_as_list(shell)); // No need to reapply the slices.

    return *this;
}

GlobValue::~GlobValue()
{
}
Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
{
    if (!shell)
        return { resolve_slices(shell, String { m_glob }, m_slices) };

    auto results = shell->expand_globs(m_glob, shell->cwd);
    if (results.is_empty())
        shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
    return resolve_slices(shell, move(results), m_slices);
}

SimpleVariableValue::~SimpleVariableValue()
{
}

String SimpleVariableValue::resolve_as_string(RefPtr<Shell> shell)
{
    if (!shell)
        return resolve_slices(shell, String {}, m_slices);

    if (auto value = resolve_without_cast(shell); value != this)
        return value->resolve_as_string(shell);

    char* env_value = getenv(m_name.characters());
    return resolve_slices(shell, env_value, m_slices);
}

Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
{
    if (!shell)
        return resolve_slices(shell, Vector<String> {}, m_slices);

    if (auto value = resolve_without_cast(shell); value != this)
        return value->resolve_as_list(shell);

    char* env_value = getenv(m_name.characters());
    if (env_value == nullptr)
        return { resolve_slices(shell, "", m_slices) };

    return { resolve_slices(shell, String { env_value }, m_slices) };
}

NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
{
    VERIFY(shell);

    if (auto value = shell->lookup_local_variable(m_name)) {
        auto result = value.release_nonnull();
        // If a slice is applied, add it.
        if (!m_slices.is_empty())
            result = result->with_slices(m_slices);

        return result;
    }

    return *this;
}

SpecialVariableValue::~SpecialVariableValue()
{
}

String SpecialVariableValue::resolve_as_string(RefPtr<Shell> shell)
{
    if (!shell)
        return {};

    auto result = resolve_as_list(shell);
    if (result.size() == 1)
        return result[0];

    if (result.is_empty())
        return {};

    return Value::resolve_as_string(shell);
}

Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
{
    if (!shell)
        return {};

    switch (m_name) {
    case '?':
        return { resolve_slices(shell, String::number(shell->last_return_code.value_or(0)), m_slices) };
    case '$':
        return { resolve_slices(shell, String::number(getpid()), m_slices) };
    case '*':
        if (auto argv = shell->lookup_local_variable("ARGV"sv))
            return resolve_slices(shell, argv->resolve_as_list(shell), m_slices);
        return resolve_slices(shell, Vector<String> {}, m_slices);
    case '#':
        if (auto argv = shell->lookup_local_variable("ARGV"sv)) {
            if (argv->is_list()) {
                auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
                return { resolve_slices(shell, String::number(list_argv->values().size()), m_slices) };
            }
            return { resolve_slices(shell, "1", m_slices) };
        }
        return { resolve_slices(shell, "0", m_slices) };
    default:
        return { resolve_slices(shell, "", m_slices) };
    }
}

NonnullRefPtr<Value> SpecialVariableValue::resolve_without_cast(RefPtr<Shell> shell)
{
    if (!shell)
        return *this;

    return make_ref_counted<ListValue>(resolve_as_list(shell));
}

TildeValue::~TildeValue()
{
}

String TildeValue::resolve_as_string(RefPtr<Shell> shell)
{
    return resolve_as_list(shell).first();
}

Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
{
    StringBuilder builder;
    builder.append('~');
    builder.append(m_username);

    if (!shell)
        return { resolve_slices(shell, builder.to_string(), m_slices) };

    return { resolve_slices(shell, shell->expand_tilde(builder.to_string()), m_slices) };
}

ErrorOr<NonnullRefPtr<Rewiring>> CloseRedirection::apply() const
{
    return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
}

CloseRedirection::~CloseRedirection()
{
}

ErrorOr<NonnullRefPtr<Rewiring>> PathRedirection::apply() const
{
    auto check_fd_and_return = [my_fd = this->fd](int fd, String const& path) -> ErrorOr<NonnullRefPtr<Rewiring>> {
        if (fd < 0) {
            auto error = Error::from_errno(errno);
            dbgln("open() failed for '{}' with {}", path, error);
            return error;
        }
        return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, my_fd, Rewiring::Close::Old));
    };
    switch (direction) {
    case AST::PathRedirection::WriteAppend:
        return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);

    case AST::PathRedirection::Write:
        return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);

    case AST::PathRedirection::Read:
        return check_fd_and_return(open(path.characters(), O_RDONLY), path);

    case AST::PathRedirection::ReadWrite:
        return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
    }

    VERIFY_NOT_REACHED();
}

PathRedirection::~PathRedirection()
{
}

FdRedirection::~FdRedirection()
{
}

Redirection::~Redirection()
{
}

}