File: Driver.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (3656 lines) | stat: -rw-r--r-- 150,425 bytes parent folder | download
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
//===--------------- Driver.swift - Swift Driver --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftOptions

import class Dispatch.DispatchQueue
import class TSCBasic.DiagnosticsEngine
import class TSCBasic.UnknownLocation
import enum TSCBasic.ProcessEnv
import func TSCBasic.withTemporaryDirectory
import protocol TSCBasic.DiagnosticData
import protocol TSCBasic.FileSystem
import protocol TSCBasic.OutputByteStream
import struct TSCBasic.AbsolutePath
import struct TSCBasic.ByteString
import struct TSCBasic.Diagnostic
import struct TSCBasic.FileInfo
import struct TSCBasic.RelativePath
import var TSCBasic.localFileSystem
import var TSCBasic.stderrStream
import var TSCBasic.stdoutStream

extension Driver {
  /// Stub Error for terminating the process.
  public enum ErrorDiagnostics: Swift.Error {
    case emitted
  }
}

extension Driver.ErrorDiagnostics: CustomStringConvertible {
  public var description: String {
    switch self {
    case .emitted:
      return "errors were encountered"
    }
  }
}


/// The Swift driver.
public struct Driver {
  public enum Error: Swift.Error, Equatable, DiagnosticData {
    case unknownOrMissingSubcommand(String)
    case invalidDriverName(String)
    case invalidInput(String)
    case noInputFiles
    case invalidArgumentValue(String, String)
    case relativeFrontendPath(String)
    case subcommandPassedToDriver
    case integratedReplRemoved
    case cannotSpecify_OForMultipleOutputs
    case conflictingOptions(Option, Option)
    case unableToLoadOutputFileMap(String, String)
    case unableToDecodeFrontendTargetInfo(String?, [String], String)
    case failedToRetrieveFrontendTargetInfo
    case failedToRunFrontendToRetrieveTargetInfo(Int, String?)
    case unableToReadFrontendTargetInfo
    case missingProfilingData(String)
    case conditionalCompilationFlagHasRedundantPrefix(String)
    case conditionalCompilationFlagIsNotValidIdentifier(String)
    case baselineGenerationRequiresTopLevelModule(String)
    case optionRequiresAnother(String, String)
    // Explicit Module Build Failures
    case malformedModuleDependency(String, String)
    case missingPCMArguments(String)
    case missingModuleDependency(String)
    case missingContextHashOnSwiftDependency(String)
    case dependencyScanningFailure(Int, String)
    case missingExternalDependency(String)

    public var description: String {
      switch self {
      case .unknownOrMissingSubcommand(let subcommand):
        return "unknown or missing subcommand '\(subcommand)'"
      case .invalidDriverName(let driverName):
        return "invalid driver name: \(driverName)"
      case .invalidInput(let input):
        return "invalid input: \(input)"
      case .noInputFiles:
        return "no input files"
      case .invalidArgumentValue(let option, let value):
        return "invalid value '\(value)' in '\(option)'"
      case .relativeFrontendPath(let path):
        // TODO: where is this error thrown
        return "relative frontend path: \(path)"
      case .subcommandPassedToDriver:
        return "subcommand passed to driver"
      case .integratedReplRemoved:
        return "Compiler-internal integrated REPL has been removed; use the LLDB-enhanced REPL instead."
      case .cannotSpecify_OForMultipleOutputs:
        return "cannot specify -o when generating multiple output files"
      case .conflictingOptions(let one, let two):
        return "conflicting options '\(one.spelling)' and '\(two.spelling)'"
      case let .unableToDecodeFrontendTargetInfo(outputString, arguments, errorDesc):
        let output = outputString.map { ": \"\($0)\""} ?? ""
        return """
          could not decode frontend target info; compiler driver and frontend executables may be incompatible
          details: frontend: \(arguments.first ?? "")
                   arguments: \(arguments.dropFirst())
                   error: \(errorDesc)
          output\n\(output)
          """
      case .failedToRetrieveFrontendTargetInfo:
        return "failed to retrieve frontend target info"
      case .unableToReadFrontendTargetInfo:
        return "could not read frontend target info"
      case let .failedToRunFrontendToRetrieveTargetInfo(returnCode, stderr):
        return "frontend job retrieving target info failed with code \(returnCode)"
          + (stderr.map {": \($0)"} ?? "")
      case .missingProfilingData(let arg):
        return "no profdata file exists at '\(arg)'"
      case .conditionalCompilationFlagHasRedundantPrefix(let name):
        return "invalid argument '-D\(name)'; did you provide a redundant '-D' in your build settings?"
      case .conditionalCompilationFlagIsNotValidIdentifier(let name):
        return "conditional compilation flags must be valid Swift identifiers (rather than '\(name)')"
      // Explicit Module Build Failures
      case .malformedModuleDependency(let moduleName, let errorDescription):
        return "Malformed Module Dependency: \(moduleName), \(errorDescription)"
      case .missingPCMArguments(let moduleName):
        return "Missing extraPcmArgs to build Clang module: \(moduleName)"
      case .missingModuleDependency(let moduleName):
        return "Missing Module Dependency Info: \(moduleName)"
      case .missingContextHashOnSwiftDependency(let moduleName):
        return "Missing Context Hash for Swift dependency: \(moduleName)"
      case .dependencyScanningFailure(let code, let error):
        return "Module Dependency Scanner returned with non-zero exit status: \(code), \(error)"
      case .unableToLoadOutputFileMap(let path, let error):
        return "unable to load output file map '\(path)': \(error)"
      case .missingExternalDependency(let moduleName):
        return "Missing External dependency info for module: \(moduleName)"
      case .baselineGenerationRequiresTopLevelModule(let arg):
        return "generating a baseline with '\(arg)' is only supported with '-emit-module' or '-emit-module-path'"
      case .optionRequiresAnother(let first, let second):
        return "'\(first)' cannot be specified if '\(second)' is not present"
      }
    }
  }

  /// Specific implementation of a diagnostics output type that can be used when initializing a new `Driver`.
  public enum DiagnosticsOutput {
    case engine(DiagnosticsEngine)
    case handler(DiagnosticsEngine.DiagnosticsHandler)
  }

  /// The set of environment variables that are visible to the driver and
  /// processes it launches. This is a hook for testing; in actual use
  /// it should be identical to the real environment.
  public let env: [String: String]

  /// Whether we are using the driver as the integrated driver via libSwiftDriver
  public let integratedDriver: Bool

  /// The file system which we should interact with.
  @_spi(Testing) public let fileSystem: FileSystem

  /// Diagnostic engine for emitting warnings, errors, etc.
  public let diagnosticEngine: DiagnosticsEngine

  /// The executor the driver uses to run jobs.
  let executor: DriverExecutor

  /// The toolchain to use for resolution.
  @_spi(Testing) public let toolchain: Toolchain

  /// Information about the target, as reported by the Swift frontend.
  @_spi(Testing) public let frontendTargetInfo: FrontendTargetInfo

  /// The target triple.
  @_spi(Testing) public var targetTriple: Triple { frontendTargetInfo.target.triple }

  /// The host environment triple.
  @_spi(Testing) public let hostTriple: Triple

  /// The variant target triple.
  var targetVariantTriple: Triple? {
    frontendTargetInfo.targetVariant?.triple
  }

  /// `true` if the driver should use the static resource directory.
  let useStaticResourceDir: Bool

  /// The kind of driver.
  let driverKind: DriverKind

  /// The option table we're using.
  let optionTable: OptionTable

  /// The set of parsed options.
  var parsedOptions: ParsedOptions

  /// Whether to print out extra info regarding jobs
  let showJobLifecycle: Bool

  /// Extra command-line arguments to pass to the Swift compiler.
  let swiftCompilerPrefixArgs: [String]

  /// The working directory for the driver, if there is one.
  let workingDirectory: AbsolutePath?

  /// The set of input files
  @_spi(Testing) public let inputFiles: [TypedVirtualPath]

  /// The last time each input file was modified, recorded at the start of the build.
  @_spi(Testing) public let recordedInputModificationDates: [TypedVirtualPath: TimePoint]

  /// The mapping from input files to output files for each kind.
  let outputFileMap: OutputFileMap?

  /// The number of files required before making a file list.
  let fileListThreshold: Int

  /// Should use file lists for inputs (number of inputs exceeds `fileListThreshold`).
  let shouldUseInputFileList: Bool

  /// VirtualPath for shared all sources file list. `nil` if unused. This is used as a cache for
  /// the file list computed during CompileJob creation and only holds valid to be query by tests
  /// after planning to build.
  @_spi(Testing) public var allSourcesFileList: VirtualPath? = nil

  /// The mode in which the compiler will execute.
  @_spi(Testing) public let compilerMode: CompilerMode

  /// A distinct job will build the module files.
  @_spi(Testing) public let emitModuleSeparately: Bool

  /// The type of the primary output generated by the compiler.
  @_spi(Testing) public let compilerOutputType: FileType?

  /// The type of the link-time-optimization we expect to perform.
  @_spi(Testing) public let lto: LTOKind?

  /// The type of the primary output generated by the linker.
  @_spi(Testing) public let linkerOutputType: LinkOutputType?

  /// When > 0, the number of threads to use in a multithreaded build.
  @_spi(Testing) public let numThreads: Int

  /// The specified maximum number of parallel jobs to execute.
  @_spi(Testing) public let numParallelJobs: Int?

  /// The set of sanitizers that were requested
  let enabledSanitizers: Set<Sanitizer>

  /// The debug information to produce.
  @_spi(Testing) public let debugInfo: DebugInfo

  /// The information about the module to produce.
  @_spi(Testing) public let moduleOutputInfo: ModuleOutputInfo

  /// Name of the package containing a target module or file.
  @_spi(Testing) public let packageName: String?

  /// Info needed to write and maybe read the build record.
  /// Only present when the driver will be writing the record.
  /// Only used for reading when compiling incrementally.
  @_spi(Testing) public let buildRecordInfo: BuildRecordInfo?

  /// Whether to consider incremental compilation.
  let shouldAttemptIncrementalCompilation: Bool

  /// CAS/Caching related options.
  let enableCaching: Bool
  let useClangIncludeTree: Bool

  /// CAS instance used for compilation.
  @_spi(Testing) public var cas: SwiftScanCAS? = nil

  /// Is swift caching enabled.
  lazy var isCachingEnabled: Bool = {
    return enableCaching && isFeatureSupported(.compilation_caching)
  }()

  /// Scanner prefix mapping.
  let scannerPrefixMap: [AbsolutePath: AbsolutePath]
  let scannerPrefixMapSDK: AbsolutePath?
  let scannerPrefixMapToolchain: AbsolutePath?
  lazy var prefixMapping: [(AbsolutePath, AbsolutePath)] = {
    var mapping: [(AbsolutePath, AbsolutePath)] = scannerPrefixMap.map {
      return ($0.key, $0.value)
    }
    do {
      guard isFrontendArgSupported(.scannerPrefixMap) else {
        return []
      }
      if let sdkMapping = scannerPrefixMapSDK,
         let sdkPath = absoluteSDKPath {
        mapping.append((sdkPath, sdkMapping))
      }
      if let toolchainMapping = scannerPrefixMapToolchain {
        let toolchainPath = try toolchain.executableDir.parentDirectory // usr
                                                       .parentDirectory // toolchain
        mapping.append((toolchainPath, toolchainMapping))
      }
      // The mapping needs to be sorted so the mapping is determinisitic.
      // The sorting order is reversed so /tmp/tmp is preferred over /tmp in remapping.
      return mapping.sorted { $0.0 > $1.0 }
    } catch {
      return mapping.sorted { $0.0 > $1.0 }
    }
  }()

  /// Code & data for incremental compilation. Nil if not running in incremental mode.
  /// Set during planning because needs the jobs to look at outputs.
  @_spi(Testing) public private(set) var incrementalCompilationState: IncrementalCompilationState? = nil

  /// Nil if not running in explicit module build mode.
  /// Set during planning.
  var interModuleDependencyGraph: InterModuleDependencyGraph? = nil

  /// The path of the SDK.
  public var absoluteSDKPath: AbsolutePath? {
    guard let path = frontendTargetInfo.sdkPath?.path else {
      return nil
    }

    switch VirtualPath.lookup(path) {
    case .absolute(let path):
      return path
    case .relative(let path):
      let cwd = workingDirectory ?? fileSystem.currentWorkingDirectory
      return cwd.map { AbsolutePath($0, path) }
    case .standardInput, .standardOutput, .temporary, .temporaryWithKnownContents, .fileList:
      fatalError("Frontend target information will never include a path of this type.")
    }
  }

  /// The path to the imported Objective-C header.
  let importedObjCHeader: VirtualPath.Handle?

  /// The path to the pch for the imported Objective-C header.
  lazy var bridgingPrecompiledHeader: VirtualPath.Handle? = {
    let contextHash = try? explicitDependencyBuildPlanner?.getMainModuleContextHash()
    return Self.computeBridgingPrecompiledHeader(&parsedOptions,
                                                 compilerMode: compilerMode,
                                                 importedObjCHeader: importedObjCHeader,
                                                 outputFileMap: outputFileMap,
                                                 contextHash: contextHash)
  }()

  /// Path to the dependencies file.
  let dependenciesFilePath: VirtualPath.Handle?

  /// Path to the references dependencies file.
  let referenceDependenciesPath: VirtualPath.Handle?

  /// Path to the serialized diagnostics file.
  let serializedDiagnosticsFilePath: VirtualPath.Handle?

  /// Path to the serialized diagnostics file of the emit-module task.
  let emitModuleSerializedDiagnosticsFilePath: VirtualPath.Handle?

  /// Path to the discovered dependencies file of the emit-module task.
  let emitModuleDependenciesFilePath: VirtualPath.Handle?

  /// Path to emitted compile-time-known values.
  let constValuesFilePath: VirtualPath.Handle?

  /// Path to the Objective-C generated header.
  let objcGeneratedHeaderPath: VirtualPath.Handle?

  /// Path to the loaded module trace file.
  let loadedModuleTracePath: VirtualPath.Handle?

  /// Path to the TBD file (text-based dylib).
  let tbdPath: VirtualPath.Handle?

  /// Path to the module documentation file.
  let moduleDocOutputPath: VirtualPath.Handle?

  /// Path to the Swift interface file.
  let swiftInterfacePath: VirtualPath.Handle?

  /// Path to the Swift private interface file.
  let swiftPrivateInterfacePath: VirtualPath.Handle?

  /// Path to the Swift package interface file.
  let swiftPackageInterfacePath: VirtualPath.Handle?

  /// File type for the optimization record.
  let optimizationRecordFileType: FileType?

  /// Path to the optimization record.
  let optimizationRecordPath: VirtualPath.Handle?

  /// Path to the Swift module source information file.
  let moduleSourceInfoPath: VirtualPath.Handle?

  /// Path to the module's digester baseline file.
  let digesterBaselinePath: VirtualPath.Handle?

  /// Path to the emitted API descriptor file.
  let apiDescriptorFilePath: VirtualPath.Handle?

  /// The mode the API digester should run in.
  let digesterMode: DigesterMode

  // FIXME: We should soon be able to remove this from being in the Driver's state.
  // Its only remaining use outside of actual dependency build planning is in
  // command-line input option generation for the explicit main module compile job.
  /// Planner for constructing module build jobs using Explicit Module Builds.
  /// Constructed during the planning phase only when all module dependencies will be prebuilt and treated
  /// as explicit inputs by the various compilation jobs.
  @_spi(Testing) public var explicitDependencyBuildPlanner: ExplicitDependencyBuildPlanner? = nil

  /// An oracle for querying inter-module dependencies
  /// Can either be an argument to the driver in many-module contexts where dependency information
  /// is shared across many targets; otherwise, a new instance is created by the driver itself.
  @_spi(Testing) public let interModuleDependencyOracle: InterModuleDependencyOracle

  /// A dictionary of external targets that are a part of the same build, mapping to filesystem paths
  /// of their module files
  @_spi(Testing) public var externalTargetModuleDetailsMap: ExternalTargetModuleDetailsMap? = nil

  /// A collection of all the flags the selected toolchain's `swift-frontend` supports
  public let supportedFrontendFlags: Set<String>

  /// A list of unknown driver flags that are recognizable to `swift-frontend`
  public let savedUnknownDriverFlagsForSwiftFrontend: [String]

  /// A collection of all the features the selected toolchain's `swift-frontend` supports
  public let supportedFrontendFeatures: Set<String>

  /// A global queue for emitting non-interrupted messages into stderr
  public static let stdErrQueue = DispatchQueue(label: "org.swift.driver.emit-to-stderr")

  @_spi(Testing)
  public enum KnownCompilerFeature: String {
    case emit_abi_descriptor = "emit-abi-descriptor"
    case compilation_caching = "compilation-caching"
  }

  lazy var sdkPath: VirtualPath? = {
    guard let rawSdkPath = frontendTargetInfo.sdkPath?.path else {
      return nil
    }
    return VirtualPath.lookup(rawSdkPath)
  } ()

  lazy var iosMacFrameworksSearchPath: VirtualPath = {
    sdkPath!
      .appending(component: "System")
      .appending(component: "iOSSupport")
      .appending(component: "System")
      .appending(component: "Library")
      .appending(component: "Frameworks")
  } ()

  lazy var abiDescriptorPath: TypedVirtualPath? = {
    guard isFeatureSupported(.emit_abi_descriptor) else {
      return nil
    }
    // Emit the descriptor only on platforms where Library Evolution is supported,
    // or opted-into explicitly.
    guard targetTriple.isDarwin || parsedOptions.hasArgument(.enableLibraryEvolution) else {
      return nil
    }
    guard let moduleOutput = moduleOutputInfo.output else {
      return nil
    }
    guard let path = try? VirtualPath.lookup(moduleOutput.outputPath).replacingExtension(with: .jsonABIBaseline) else {
      return nil
    }
    return TypedVirtualPath(file: path.intern(), type: .jsonABIBaseline)
  }()

  public static func isOptionFound(_ opt: String, allOpts: Set<String>) -> Bool {
    var current = opt
    while(true) {
      if allOpts.contains(current) {
        return true
      }
      if current.starts(with: "-") {
        current = String(current.dropFirst())
      } else {
        return false
      }
    }
  }

  public func isFrontendArgSupported(_ opt: Option) -> Bool {
    return Driver.isOptionFound(opt.spelling, allOpts: supportedFrontendFlags)
  }

  @_spi(Testing)
  public func isFeatureSupported(_ feature: KnownCompilerFeature) -> Bool {
    return supportedFrontendFeatures.contains(feature.rawValue)
  }

  public func getSwiftScanLibPath() throws -> AbsolutePath? {
    return try toolchain.lookupSwiftScanLib()
  }

  @_spi(Testing)
  public static func findBlocklists(RelativeTo execDir: AbsolutePath) throws ->  [AbsolutePath] {
    // Expect to find all blocklists in such dir:
    // .../XcodeDefault.xctoolchain/usr/local/lib/swift/blocklists
    var results: [AbsolutePath] = []
    let blockListDir = execDir.parentDirectory
      .appending(components: "local", "lib", "swift", "blocklists")
    if (localFileSystem.exists(blockListDir)) {
      try localFileSystem.getDirectoryContents(blockListDir).forEach {
        let currentFile = AbsolutePath(blockListDir, try VirtualPath(path: $0).relativePath!)
        if currentFile.extension == "yml" || currentFile.extension == "yaml" {
          results.append(currentFile)
        }
      }
    }
    return results
  }

  @_spi(Testing)
  public static func findCompilerClientsConfigVersion(RelativeTo execDir: AbsolutePath) throws -> String? {
    // Expect to find all blocklists in such dir:
    // .../XcodeDefault.xctoolchain/usr/local/lib/swift/compilerClientsConfig_version.txt
    let versionFilePath = execDir.parentDirectory
      .appending(components: "local", "lib", "swift", "compilerClientsConfig_version.txt")
    if (localFileSystem.exists(versionFilePath)) {
      return try localFileSystem.readFileContents(versionFilePath).cString
    }
    return nil
  }

  /// Handler for emitting diagnostics to stderr.
  public static let stderrDiagnosticsHandler: DiagnosticsEngine.DiagnosticsHandler = { diagnostic in
    stdErrQueue.sync {
      let stream = stderrStream
      if !(diagnostic.location is UnknownLocation) {
          stream.send("\(diagnostic.location.description): ")
      }

      switch diagnostic.message.behavior {
      case .error:
        stream.send("error: ")
      case .warning:
        stream.send("warning: ")
      case .note:
        stream.send("note: ")
      case .remark:
        stream.send("remark: ")
      case .ignored:
          break
      }

      stream.send("\(diagnostic.localizedDescription)\n")
      stream.flush()
    }
  }

  @available(*, deprecated, renamed: "init(args:env:diagnosticsOutput:fileSystem:executor:integratedDriver:compilerExecutableDir:externalTargetModuleDetailsMap:interModuleDependencyOracle:)")
  public init(
    args: [String],
    env: [String: String] = ProcessEnv.vars,
    diagnosticsEngine: DiagnosticsEngine,
    fileSystem: FileSystem = localFileSystem,
    executor: DriverExecutor,
    integratedDriver: Bool = true,
    compilerExecutableDir: AbsolutePath? = nil,
    externalTargetModuleDetailsMap: ExternalTargetModuleDetailsMap? = nil,
    interModuleDependencyOracle: InterModuleDependencyOracle? = nil
  ) throws {
    try self.init(
      args: args,
      env: env,
      diagnosticsOutput: .engine(diagnosticsEngine),
      fileSystem: fileSystem,
      executor: executor,
      integratedDriver: integratedDriver,
      compilerExecutableDir: compilerExecutableDir,
      externalTargetModuleDetailsMap: externalTargetModuleDetailsMap,
      interModuleDependencyOracle: interModuleDependencyOracle
    )
  }

  /// Create the driver with the given arguments.
  ///
  /// - Parameter args: The command-line arguments, including the "swift" or "swiftc"
  ///   at the beginning.
  /// - Parameter env: The environment variables to use. This is a hook for testing;
  ///   in production, you should use the default argument, which copies the current environment.
  /// - Parameter diagnosticsOutput: The diagnostics output implementation used by the driver to emit errors
  ///   and warnings.
  /// - Parameter fileSystem: The filesystem used by the driver to find resources/SDKs,
  ///   expand response files, etc. By default this is the local filesystem.
  /// - Parameter executor: Used by the driver to execute jobs. The default argument
  ///   is present to streamline testing, it shouldn't be used in production.
  /// - Parameter integratedDriver: Used to distinguish whether the driver is being used as
  ///   an executable or as a library.
  /// - Parameter compilerExecutableDir: Directory that contains the compiler executable to be used.
  ///   Used when in `integratedDriver` mode as a substitute for the driver knowing its executable path.
  /// - Parameter externalTargetModuleDetailsMap: A dictionary of external targets that are a part of
  ///   the same build, mapping to a details value which includes a filesystem path of their
  ///   `.swiftmodule` and a flag indicating whether the external target is a framework.
  /// - Parameter interModuleDependencyOracle: An oracle for querying inter-module dependencies,
  ///   shared across different module builds by a build system.
  public init(
    args: [String],
    env: [String: String] = ProcessEnv.vars,
    diagnosticsOutput: DiagnosticsOutput = .engine(DiagnosticsEngine(handlers: [Driver.stderrDiagnosticsHandler])),
    fileSystem: FileSystem = localFileSystem,
    executor: DriverExecutor,
    integratedDriver: Bool = true,
    compilerExecutableDir: AbsolutePath? = nil,
    externalTargetModuleDetailsMap: ExternalTargetModuleDetailsMap? = nil,
    interModuleDependencyOracle: InterModuleDependencyOracle? = nil
  ) throws {
    self.env = env
    self.fileSystem = fileSystem
    self.integratedDriver = integratedDriver

    let diagnosticsEngine: DiagnosticsEngine
    switch diagnosticsOutput {
    case .engine(let engine):
      diagnosticsEngine = engine
    case .handler(let handler):
      diagnosticsEngine = DiagnosticsEngine(handlers: [handler])
    }
    self.diagnosticEngine = diagnosticsEngine

    self.executor = executor
    self.externalTargetModuleDetailsMap = externalTargetModuleDetailsMap

    if case .subcommand = try Self.invocationRunMode(forArgs: args).mode {
      throw Error.subcommandPassedToDriver
    }
    var args = args
    if let additional = env["ADDITIONAL_SWIFT_DRIVER_FLAGS"] {
      args.append(contentsOf: additional.components(separatedBy: " "))
    }

    args = try Self.expandResponseFiles(args, fileSystem: fileSystem, diagnosticsEngine: self.diagnosticEngine)

    self.driverKind = try Self.determineDriverKind(args: &args)
    self.optionTable = OptionTable()
    self.parsedOptions = try optionTable.parse(Array(args), for: self.driverKind, delayThrows: true)
    self.showJobLifecycle = parsedOptions.contains(.driverShowJobLifecycle)

    // Determine the compilation mode.
    self.compilerMode = try Self.computeCompilerMode(&parsedOptions, driverKind: driverKind, diagnosticsEngine: diagnosticEngine)

    self.shouldAttemptIncrementalCompilation = Self.shouldAttemptIncrementalCompilation(&parsedOptions,
                                                                                        diagnosticEngine: diagnosticsEngine,
                                                                                        compilerMode: compilerMode)

    // Compute the working directory.
    workingDirectory = try parsedOptions.getLastArgument(.workingDirectory).map { workingDirectoryArg in
      let cwd = fileSystem.currentWorkingDirectory
      return try cwd.map{ try AbsolutePath(validating: workingDirectoryArg.asSingle, relativeTo: $0) } ?? AbsolutePath(validating: workingDirectoryArg.asSingle)
    }

    // Apply the working directory to the parsed options.
    if let workingDirectory = self.workingDirectory {
      try Self.applyWorkingDirectory(workingDirectory, to: &self.parsedOptions)
    }

    let staticExecutable = parsedOptions.hasFlag(positive: .staticExecutable,
                                                 negative: .noStaticExecutable,
                                                 default: false)
    let staticStdlib = parsedOptions.hasFlag(positive: .staticStdlib,
                                             negative: .noStaticStdlib,
                                             default: false)
    self.useStaticResourceDir = staticExecutable || staticStdlib

    // Build the toolchain and determine target information.
    (self.toolchain, self.frontendTargetInfo, self.swiftCompilerPrefixArgs) =
        try Self.computeToolchain(
          &self.parsedOptions, diagnosticsEngine: diagnosticEngine,
          compilerMode: self.compilerMode, env: env,
          executor: self.executor, fileSystem: fileSystem,
          useStaticResourceDir: self.useStaticResourceDir,
          workingDirectory: self.workingDirectory,
          compilerExecutableDir: compilerExecutableDir)

    // Compute the host machine's triple
    self.hostTriple =
      try Self.computeHostTriple(&self.parsedOptions, diagnosticsEngine: diagnosticEngine,
                                 toolchain: self.toolchain, executor: self.executor,
                                 fileSystem: fileSystem,
                                 workingDirectory: self.workingDirectory,
                                 swiftCompilerPrefixArgs: self.swiftCompilerPrefixArgs)

    // Classify and collect all of the input files.
    let inputFiles = try Self.collectInputFiles(&self.parsedOptions, diagnosticsEngine: diagnosticsEngine, fileSystem: self.fileSystem)
    self.inputFiles = inputFiles
    self.recordedInputModificationDates = .init(uniqueKeysWithValues:
      Set(inputFiles).compactMap {
        guard let modTime = try? fileSystem
          .lastModificationTime(for: $0.file) else { return nil }
        return ($0, modTime)
    })

    do {
      let outputFileMap: OutputFileMap?
      // Initialize an empty output file map, which will be populated when we start creating jobs.
      if let outputFileMapArg = parsedOptions.getLastArgument(.outputFileMap)?.asSingle {
        do {
          let path = try VirtualPath(path: outputFileMapArg)
          outputFileMap = try .load(fileSystem: fileSystem, file: path, diagnosticEngine: diagnosticEngine)
        } catch let error {
          throw Error.unableToLoadOutputFileMap(outputFileMapArg, error.localizedDescription)
        }
      } else {
        outputFileMap = nil
      }

      if let workingDirectory = self.workingDirectory {
        self.outputFileMap = outputFileMap?.resolveRelativePaths(relativeTo: workingDirectory)
      } else {
        self.outputFileMap = outputFileMap
      }
    }

    // Create an instance of an inter-module dependency oracle, if the driver's
    // client did not provide one. The clients are expected to provide an oracle
    // when they wish to share module dependency information across targets.
    if let dependencyOracle = interModuleDependencyOracle {
      self.interModuleDependencyOracle = dependencyOracle
    } else {
      self.interModuleDependencyOracle = InterModuleDependencyOracle()
    }

    self.fileListThreshold = try Self.computeFileListThreshold(&self.parsedOptions, diagnosticsEngine: diagnosticsEngine)
    self.shouldUseInputFileList = inputFiles.count > fileListThreshold

    self.lto = Self.ltoKind(&parsedOptions, diagnosticsEngine: diagnosticsEngine)
    // Figure out the primary outputs from the driver.
    (self.compilerOutputType, self.linkerOutputType) = 
      Self.determinePrimaryOutputs(&parsedOptions, targetTriple: self.frontendTargetInfo.target.triple, 
                                   driverKind: driverKind, diagnosticsEngine: diagnosticEngine)

    // Multithreading.
    self.numThreads = Self.determineNumThreads(&parsedOptions, compilerMode: compilerMode, diagnosticsEngine: diagnosticEngine)
    self.numParallelJobs = Self.determineNumParallelJobs(&parsedOptions, diagnosticsEngine: diagnosticEngine, env: env)

    var mode = DigesterMode.api
    if let modeArg = parsedOptions.getLastArgument(.digesterMode)?.asSingle {
      if let digesterMode = DigesterMode(rawValue: modeArg) {
        mode = digesterMode
      } else {
        diagnosticsEngine.emit(.error(Error.invalidArgumentValue(Option.digesterMode.spelling, modeArg)),
                               location: nil)
      }
    }
    self.digesterMode = mode

    Self.validateWarningControlArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateProfilingArgs(&parsedOptions,
                               fileSystem: fileSystem,
                               workingDirectory: workingDirectory,
                               diagnosticEngine: diagnosticEngine)
    Self.validateEmitDependencyGraphArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateValidateClangModulesOnceOptions(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateParseableOutputArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateCompilationConditionArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateFrameworkSearchPathArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
    Self.validateCoverageArgs(&parsedOptions, diagnosticsEngine: diagnosticEngine)
    Self.validateLinkArgs(&parsedOptions, diagnosticsEngine: diagnosticEngine)
    try toolchain.validateArgs(&parsedOptions,
                               targetTriple: self.frontendTargetInfo.target.triple,
                               targetVariantTriple: self.frontendTargetInfo.targetVariant?.triple,
                               compilerOutputType: self.compilerOutputType,
                               diagnosticsEngine: diagnosticEngine)

    // Compute debug information output.
    let defaultDwarfVersion = self.toolchain.getDefaultDwarfVersion(targetTriple: self.frontendTargetInfo.target.triple)
    self.debugInfo = Self.computeDebugInfo(&parsedOptions,
                                           defaultDwarfVersion: defaultDwarfVersion,
                                           diagnosticsEngine: diagnosticEngine)

    // Error if package-name is passed but the input is empty; if
    // package-name is not passed but `package` decls exist, error
    // will occur during the frontend type check.
    self.packageName = parsedOptions.getLastArgument(.packageName)?.asSingle
    if let packageName = packageName, packageName.isEmpty {
      diagnosticsEngine.emit(.error_empty_package_name)
    }

    // Determine the module we're building and whether/how the module file itself will be emitted.
    self.moduleOutputInfo = try Self.computeModuleInfo(
      &parsedOptions, compilerOutputType: compilerOutputType, compilerMode: compilerMode, linkerOutputType: linkerOutputType,
      debugInfoLevel: debugInfo.level, diagnosticsEngine: diagnosticEngine,
      workingDirectory: self.workingDirectory)

    // Should we schedule a separate emit-module job?
    self.emitModuleSeparately = Self.computeEmitModuleSeparately(parsedOptions: &parsedOptions,
                                                                 compilerMode: compilerMode,
                                                                 compilerOutputType: compilerOutputType,
                                                                 moduleOutputInfo: moduleOutputInfo,
                                                                 inputFiles: inputFiles)

    self.buildRecordInfo = BuildRecordInfo(
      actualSwiftVersion: self.frontendTargetInfo.compilerVersion,
      compilerOutputType: compilerOutputType,
      workingDirectory: self.workingDirectory ?? fileSystem.currentWorkingDirectory,
      diagnosticEngine: diagnosticEngine,
      fileSystem: fileSystem,
      moduleOutputInfo: moduleOutputInfo,
      outputFileMap: outputFileMap,
      incremental: self.shouldAttemptIncrementalCompilation,
      parsedOptions: parsedOptions,
      recordedInputModificationDates: recordedInputModificationDates)

    self.importedObjCHeader = try Self.computeImportedObjCHeader(&parsedOptions, compilerMode: compilerMode, diagnosticEngine: diagnosticEngine)

    self.supportedFrontendFlags =
      try Self.computeSupportedCompilerArgs(of: self.toolchain,
                                            parsedOptions: &self.parsedOptions,
                                            diagnosticsEngine: diagnosticEngine,
                                            fileSystem: fileSystem,
                                            executor: executor)
    let supportedFrontendFlagsLocal = self.supportedFrontendFlags
    self.savedUnknownDriverFlagsForSwiftFrontend = try self.parsedOptions.saveUnknownFlags {
      Driver.isOptionFound($0, allOpts: supportedFrontendFlagsLocal)
    }
    self.savedUnknownDriverFlagsForSwiftFrontend.forEach {
      diagnosticsEngine.emit(.warning("save unknown driver flag \($0) as additional swift-frontend flag"),
                             location: nil)
    }
    self.supportedFrontendFeatures = try Self.computeSupportedCompilerFeatures(of: self.toolchain, env: env)

    // Caching options.
    let cachingEnabled = parsedOptions.hasArgument(.cacheCompileJob) || env.keys.contains("SWIFT_ENABLE_CACHING")
    if cachingEnabled {
      if !parsedOptions.hasArgument(.driverExplicitModuleBuild) {
        diagnosticsEngine.emit(.warning("-cache-compile-job cannot be used without explicit module build, turn off caching"),
                               location: nil)
        self.enableCaching = false
      } else if importedObjCHeader != nil, !parsedOptions.hasFlag(positive: .enableBridgingPch, negative: .disableBridgingPch, default: true) {
        diagnosticsEngine.emit(.warning("-cache-compile-job cannot be used with -disable-bridging-pch, turn off caching"),
                               location: nil)
        self.enableCaching = false
      } else {
        self.enableCaching = true
      }
    } else {
      self.enableCaching = false
    }
    self.useClangIncludeTree = !parsedOptions.hasArgument(.noClangIncludeTree) && !env.keys.contains("SWIFT_CACHING_USE_CLANG_CAS_FS")
    self.scannerPrefixMap = try Self.computeScanningPrefixMapper(&parsedOptions)
    if let sdkMapping =  parsedOptions.getLastArgument(.scannerPrefixMapSdk)?.asSingle {
      self.scannerPrefixMapSDK = try AbsolutePath(validating: sdkMapping)
    } else {
      self.scannerPrefixMapSDK = nil
    }
    if let toolchainMapping = parsedOptions.getLastArgument(.scannerPrefixMapToolchain)?.asSingle {
      self.scannerPrefixMapToolchain = try AbsolutePath(validating: toolchainMapping)
    } else {
      self.scannerPrefixMapToolchain = nil
    }

    self.enabledSanitizers = try Self.parseSanitizerArgValues(
      &parsedOptions,
      diagnosticEngine: diagnosticEngine,
      toolchain: toolchain,
      targetInfo: frontendTargetInfo)

    Self.validateSanitizerAddressUseOdrIndicatorFlag(&parsedOptions, diagnosticEngine: diagnosticsEngine, addressSanitizerEnabled: enabledSanitizers.contains(.address))

    Self.validateSanitizeStableABI(&parsedOptions, diagnosticEngine: diagnosticsEngine, addressSanitizerEnabled: enabledSanitizers.contains(.address))

    Self.validateSanitizerRecoverArgValues(&parsedOptions, diagnosticEngine: diagnosticsEngine, enabledSanitizers: enabledSanitizers)

    Self.validateSanitizerCoverageArgs(&parsedOptions,
                                       anySanitizersEnabled: !enabledSanitizers.isEmpty,
                                       diagnosticsEngine: diagnosticsEngine)

    // Supplemental outputs.
    self.dependenciesFilePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .dependencies, isOutputOptions: [.emitDependencies],
        outputPath: .emitDependenciesPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.referenceDependenciesPath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .swiftDeps, isOutputOptions: shouldAttemptIncrementalCompilation ? [.incremental] : [],
        outputPath: .emitReferenceDependenciesPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.serializedDiagnosticsFilePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .diagnostics, isOutputOptions: [.serializeDiagnostics],
        outputPath: .serializeDiagnosticsPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.emitModuleSerializedDiagnosticsFilePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .emitModuleDiagnostics, isOutputOptions: [.serializeDiagnostics],
        outputPath: .emitModuleSerializeDiagnosticsPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.emitModuleDependenciesFilePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .emitModuleDependencies, isOutputOptions: [.emitDependencies],
        outputPath: .emitModuleDependenciesPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.constValuesFilePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .swiftConstValues, isOutputOptions: [.emitConstValues],
        outputPath: .emitConstValuesPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    // FIXME: -fixits-output-path
    self.objcGeneratedHeaderPath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .objcHeader, isOutputOptions: [.emitObjcHeader],
        outputPath: .emitObjcHeaderPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)

    if let loadedModuleTraceEnvVar = env["SWIFT_LOADED_MODULE_TRACE_FILE"] {
      self.loadedModuleTracePath = try VirtualPath.intern(path: loadedModuleTraceEnvVar)
    } else {
      self.loadedModuleTracePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .moduleTrace, isOutputOptions: [.emitLoadedModuleTrace],
        outputPath: .emitLoadedModuleTracePath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    }

    self.tbdPath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .tbd, isOutputOptions: [.emitTbd],
        outputPath: .emitTbdPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    self.moduleDocOutputPath = try Self.computeModuleDocOutputPath(
        &parsedOptions, moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)

    let projectDirectory = Self.computeProjectDirectoryPath(
      moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
      fileSystem: self.fileSystem)
    self.moduleSourceInfoPath = try Self.computeModuleSourceInfoOutputPath(
        &parsedOptions,
        moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name,
        projectDirectory: projectDirectory)
    self.digesterBaselinePath = try Self.computeDigesterBaselineOutputPath(
      &parsedOptions,
      moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
      mode: self.digesterMode,
      compilerOutputType: compilerOutputType,
      compilerMode: compilerMode,
      outputFileMap: self.outputFileMap,
      moduleName: moduleOutputInfo.name,
      projectDirectory: projectDirectory)
    self.swiftInterfacePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .swiftInterface, isOutputOptions: [.emitModuleInterface],
        outputPath: .emitModuleInterfacePath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    let givenPrivateInterfacePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .privateSwiftInterface, isOutputOptions: [],
        outputPath: .emitPrivateModuleInterfacePath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)
    let givenPackageInterfacePath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: .packageSwiftInterface, isOutputOptions: [],
        outputPath: .emitPackageModuleInterfacePath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)

    // Always emitting private swift interfaces if public interfaces are emitted.'
    // With the introduction of features like @_spi_available, we may print public
    // and private interfaces differently even from the same codebase. For this reason,
    // we should always print private interfaces so that we don’t mix the public interfaces
    // with private Clang modules.
    if let swiftInterfacePath = self.swiftInterfacePath,
        givenPrivateInterfacePath == nil {
      self.swiftPrivateInterfacePath = try VirtualPath.lookup(swiftInterfacePath)
        .replacingExtension(with: .privateSwiftInterface).intern()
    } else {
      self.swiftPrivateInterfacePath = givenPrivateInterfacePath
    }

    if let packageNameInput = parsedOptions.getLastArgument(Option.packageName),
        !packageNameInput.asSingle.isEmpty {
      // Generate a package interface if built with `-package-name` required for decls
      // with the `package` access level. The .package.swiftinterface contains package
      // decls as well as SPI and public decls (superset of a private interface).
      if let publicInterfacePath = self.swiftInterfacePath,
         givenPackageInterfacePath == nil {
        self.swiftPackageInterfacePath = try VirtualPath.lookup(publicInterfacePath)
          .replacingExtension(with: .packageSwiftInterface).intern()
      } else {
        self.swiftPackageInterfacePath = givenPackageInterfacePath
      }
    } else {
      self.swiftPackageInterfacePath = nil
    }

    var optimizationRecordFileType = FileType.yamlOptimizationRecord
    if let argument = parsedOptions.getLastArgument(.saveOptimizationRecordEQ)?.asSingle {
      switch argument {
      case "yaml":
        optimizationRecordFileType = .yamlOptimizationRecord
      case "bitstream":
        optimizationRecordFileType = .bitstreamOptimizationRecord
      default:
        // Don't report an error here, it will be emitted by the frontend.
        break
      }
    }
    self.optimizationRecordFileType = optimizationRecordFileType
    self.optimizationRecordPath = try Self.computeSupplementaryOutputPath(
        &parsedOptions, type: optimizationRecordFileType,
        isOutputOptions: [.saveOptimizationRecord, .saveOptimizationRecordEQ],
        outputPath: .saveOptimizationRecordPath,
        compilerOutputType: compilerOutputType,
        compilerMode: compilerMode,
        emitModuleSeparately: emitModuleSeparately,
        outputFileMap: self.outputFileMap,
        moduleName: moduleOutputInfo.name)

    var apiDescriptorDirectory: VirtualPath? = nil
    if let apiDescriptorDirectoryEnvVar = env["TAPI_SDKDB_OUTPUT_PATH"] {
        apiDescriptorDirectory = try VirtualPath(path: apiDescriptorDirectoryEnvVar)
    } else if let ldTraceFileEnvVar = env["LD_TRACE_FILE"] {
        apiDescriptorDirectory = try VirtualPath(path: ldTraceFileEnvVar).parentDirectory.appending(component: "SDKDB")
    }
    if let apiDescriptorDirectory = apiDescriptorDirectory {
        self.apiDescriptorFilePath = apiDescriptorDirectory
          .appending(component: "\(moduleOutputInfo.name).\(frontendTargetInfo.target.moduleTriple.triple).swift.sdkdb")
          .intern()
    } else {
        self.apiDescriptorFilePath = try Self.computeSupplementaryOutputPath(
            &parsedOptions, type: .jsonAPIDescriptor, isOutputOptions: [],
            outputPath: .emitApiDescriptorPath,
            compilerOutputType: compilerOutputType,
            compilerMode: compilerMode,
            emitModuleSeparately: emitModuleSeparately,
            outputFileMap: self.outputFileMap,
            moduleName: moduleOutputInfo.name)
    }

    Self.validateDigesterArgs(&parsedOptions,
                              moduleOutputInfo: moduleOutputInfo,
                              digesterMode: self.digesterMode,
                              swiftInterfacePath: self.swiftInterfacePath,
                              diagnosticEngine: diagnosticsEngine)

    try verifyOutputOptions()
  }

  public mutating func planBuild() throws -> [Job] {
    let (jobs, incrementalCompilationState) = try planPossiblyIncrementalBuild()
    self.incrementalCompilationState = incrementalCompilationState
    return jobs
  }
}

extension Driver {

  public enum InvocationRunMode: Equatable {
    case normal(isRepl: Bool)
    case subcommand(String)
  }

  /// Determines whether the given arguments constitute a normal invocation,
  /// or whether they invoke a subcommand.
  ///
  /// - Returns: the invocation mode along with the arguments modified for that mode.
  public static func invocationRunMode(
    forArgs args: [String]
  ) throws -> (mode: InvocationRunMode, args: [String]) {

    assert(!args.isEmpty)

    let execName = try VirtualPath(path: args[0]).basenameWithoutExt

    // If we are not run as 'swift' or 'swiftc' or there are no program arguments, always invoke as normal.
    guard ["swift", "swiftc", executableName("swift"), executableName("swiftc")].contains(execName), args.count > 1 else {
      return (.normal(isRepl: false), args)
    }

    // Otherwise, we have a program argument.
    let firstArg = args[1]
    var updatedArgs = args

    // Check for flags associated with frontend tools.
    if firstArg == "-frontend" {
      updatedArgs.replaceSubrange(0...1, with: [executableName("swift-frontend")])
      return (.subcommand(executableName("swift-frontend")), updatedArgs)
    }

    if firstArg == "-modulewrap" {
      updatedArgs[0] = executableName("swift-frontend")
      return (.subcommand(executableName("swift-frontend")), updatedArgs)
    }

    // Only 'swift' supports subcommands.
    guard ["swift", executableName("swift")].contains(execName) else {
      return (.normal(isRepl: false), args)
    }

    // If it looks like an option or a path, then invoke in interactive mode with the arguments as given.
    if firstArg.hasPrefix("-") || firstArg.hasPrefix("/") || firstArg.contains(".") {
        return (.normal(isRepl: false), args)
    }

    // Otherwise, we should have some sort of subcommand.
    // If it is the "built-in" 'repl', then use the normal driver.
    if firstArg == "repl" {
        updatedArgs.remove(at: 1)
        updatedArgs.append("-repl")
        return (.normal(isRepl: true), updatedArgs)
    }

    let subcommand = executableName("swift-\(firstArg)")

    updatedArgs.replaceSubrange(0...1, with: [subcommand])

    return (.subcommand(subcommand), updatedArgs)
  }
}

extension Driver {
  private static func ltoKind(_ parsedOptions: inout ParsedOptions,
                              diagnosticsEngine: DiagnosticsEngine) -> LTOKind? {
    guard let arg = parsedOptions.getLastArgument(.lto)?.asSingle else { return nil }
    guard let kind = LTOKind(rawValue: arg) else {
      diagnosticsEngine.emit(.error_invalid_arg_value_with_allowed(
        arg: .lto, value: arg, options: LTOKind.allCases.map { $0.rawValue }))
      return nil
    }
    return kind
  }
}

extension Driver {
  // Detect mis-use of multi-threading and output file options
  private func verifyOutputOptions() throws {
    if compilerOutputType != .swiftModule,
       parsedOptions.hasArgument(.o),
       linkerOutputType == nil {
      let shouldComplain: Bool
      if numThreads > 0 {
        // Multi-threading compilation has multiple outputs unless there's only
        // one input.
        shouldComplain = self.inputFiles.count > 1
      } else {
        // Single-threaded compilation is a problem if we're compiling more than
        // one file.
        shouldComplain = self.inputFiles.filter { $0.type.isPartOfSwiftCompilation }.count > 1 && .singleCompile != compilerMode
      }
      if shouldComplain {
        diagnosticEngine.emit(.error(Error.cannotSpecify_OForMultipleOutputs),
                              location: nil)
      }
    }
  }
}

// MARK: - Response files.
extension Driver {
  /// Tracks visited response files by unique file ID to prevent recursion,
  /// even if they are referenced with different path strings.
  private struct VisitedResponseFile: Hashable, Equatable {
    var device: UInt64
    var inode: UInt64

    init(fileInfo: FileInfo) {
      self.device = fileInfo.device
      self.inode = fileInfo.inode
    }
  }

  /// Tokenize a single line in a response file.
  ///
  /// This method supports response files with:
  /// 1. Double slash comments at the beginning of a line.
  /// 2. Backslash escaping.
  /// 3. Shell Quoting
  ///
  /// - Returns: An array of 0 or more command line arguments
  ///
  /// - Complexity: O(*n*), where *n* is the length of the line.
  private static func tokenizeResponseFileLine<S: StringProtocol>(_ line: S) -> [String] {
    // Support double dash comments only if they start at the beginning of a line.
    if line.hasPrefix("//") { return [] }

    var tokens: [String] = []
    var token: String = ""
    // Conservatively assume ~1 token per line.
    token.reserveCapacity(line.count)
    // Indicates if we just parsed an escaping backslash.
    var isEscaping = false
    // Indicates if we are currently parsing quoted text.
    var quoted = false

    for char in line {
      // Backslash escapes to the next character.
      if char == #"\"#, !isEscaping {
        isEscaping = true
        continue
      } else if isEscaping {
        // Disable escaping and keep parsing.
        isEscaping = false
      } else if char.isShellQuote {
        // If an unescaped shell quote appears, begin or end quoting.
        quoted.toggle()
        continue
      } else if char.isWhitespace && !quoted {
        // This is unquoted, unescaped whitespace, start a new token.
        if !token.isEmpty {
          tokens.append(token)
          token = ""
        }
        continue
      }

      token.append(char)
    }
    // Add the final token
    if !token.isEmpty {
      tokens.append(token)
    }

    return tokens
  }

  // https://docs.microsoft.com/en-us/previous-versions//17w5ykft(v=vs.85)?redirectedfrom=MSDN
  private static func tokenizeWindowsResponseFile(_ content: String) -> [String] {
    let whitespace: [Character] = [" ", "\t", "\r", "\n", "\0" ]

    var content = content
    var tokens: [String] = []
    var token: String = ""
    var quoted: Bool = false

    while !content.isEmpty {
      // Eat whitespace at the beginning
      if token.isEmpty {
        if let end = content.firstIndex(where: { !whitespace.contains($0) }) {
          let count = content.distance(from: content.startIndex, to: end)
          content.removeFirst(count)
        }

        // Stop if this was trailing whitespace.
        if content.isEmpty { break }
      }

      // Treat whitespace, double quotes, and backslashes as special characters.
      if let next = content.firstIndex(where: { (quoted ? ["\\", "\""] : [" ", "\t", "\r", "\n", "\0", "\\", "\""]).contains($0) }) {
        let count = content.distance(from: content.startIndex, to: next)
        token.append(contentsOf: content[..<next])
        content.removeFirst(count)

        switch content.first {
        case " ", "\t", "\r", "\n", "\0":
          tokens.append(token)
          token = ""
          content.removeFirst(1)

        case "\\":
          // Backslashes are interpreted in a special manner due to use as both
          // a path separator and an escape character.  Consume runs of
          // backslashes and following double quote if escaped.
          //
          //  - If an even number of backslashes is followed by a double quote,
          //  one backslash is emitted for each pair, and the last double quote
          //  remains unconsumed.  The quote will be processed as the start or
          //  end of a quoted string by the tokenizer.
          //
          //  - If an odd number of backslashes is followed by a double quote,
          //  one backslash is emitted for each pair, and a double quote is
          //  emitted for the trailing backslash and quote pair.  The double
          //  quote is consumed.
          //
          //  - Otherwise, backslashes are treated literally.
          if let next = content.firstIndex(where: { $0 != "\\" }) {
            let count = content.distance(from: content.startIndex, to: next)
            if content[next] == "\"" {
              token.append(String(repeating: "\\", count: count / 2))
              content.removeFirst(count)

              if count % 2 != 0 {
                token.append("\"")
                content.removeFirst(1)
              }
            } else {
              token.append(String(repeating: "\\", count: count))
              content.removeFirst(count)
            }
          } else {
            token.append(String(repeating: "\\", count: content.count))
            content.removeFirst(content.count)
          }

        case "\"":
          content.removeFirst(1)

          if quoted, content.first == "\"" {
            // Consecutive double quotes inside a quoted string implies one quote
            token.append("\"")
            content.removeFirst(1)
          }

          quoted.toggle()

        default:
          fatalError("unexpected character '\(content.first!)'")
        }
      } else {
        // Consume to end of content.
        token.append(content)
        content.removeFirst(content.count)
        break
      }
    }

    if !token.isEmpty { tokens.append(token) }
    return tokens.filter { !$0.isEmpty }
  }

  /// Tokenize each line of the response file, omitting empty lines.
  ///
  /// - Parameter content: response file's content to be tokenized.
  private static func tokenizeResponseFile(_ content: String) -> [String] {
    #if !canImport(Darwin) && !os(Linux) && !os(Android) && !os(OpenBSD) && !os(Windows)
      #warning("Response file tokenization unimplemented for platform; behavior may be incorrect")
    #endif
#if os(Windows)
    return content.split { $0 == "\n" || $0 == "\r\n" }
                  .flatMap { tokenizeWindowsResponseFile(String($0)) }
#else
    return content.split { $0 == "\n" || $0 == "\r\n" }
                  .flatMap { tokenizeResponseFileLine($0) }
#endif
  }

  /// Resolves the absolute path for a response file.
  ///
  /// A response file may be specified using either an absolute or relative
  /// path. Relative paths resolved relative to the given base directory, which
  /// defaults to the process's current working directory, or are forbidden if
  /// the base path is nil.
  ///
  /// - Parameter path: An absolute or relative path to a response file.
  /// - Parameter basePath: An absolute path used to resolve relative paths; if
  ///   nil, relative paths will not be allowed.
  /// - Returns: The absolute path to the response file if it was a valid file,
  ///   or nil if it was not a file or was a relative path when `basePath` was
  ///   nil.
  private static func resolveResponseFile(
    _ path: String,
    relativeTo basePath: AbsolutePath?,
    fileSystem: FileSystem
  ) -> AbsolutePath? {
    let responseFile: AbsolutePath
    if let basePath = basePath {
      guard let absolutePath = try? AbsolutePath(validating: path, relativeTo: basePath) else {
          return nil
      }
      responseFile = absolutePath
    } else {
      guard let absolutePath = try? AbsolutePath(validating: path) else {
        return nil
      }
      responseFile = absolutePath
    }
    return fileSystem.isFile(responseFile) ? responseFile : nil
  }

  /// Tracks the given response file and returns a token if it has not already
  /// been visited.
  ///
  /// - Returns: A value that uniquely identifies the response file that was
  ///   added to `visitedResponseFiles` and should be removed when the caller
  ///   is done visiting the file, or nil if visiting the file would result in
  ///   recursion.
  private static func shouldVisitResponseFile(
    _ path: AbsolutePath,
    fileSystem: FileSystem,
    visitedResponseFiles: inout Set<VisitedResponseFile>
  ) throws -> VisitedResponseFile? {
    let visitationToken = try VisitedResponseFile(fileInfo: fileSystem.getFileInfo(path))
    return visitedResponseFiles.insert(visitationToken).inserted ? visitationToken : nil
  }

  /// Recursively expands the response files.
  /// - Parameter basePath: The absolute path used to resolve response files
  ///   with relative path names. If nil, relative paths will be ignored.
  /// - Parameter visitedResponseFiles: Set containing visited response files
  ///   to detect recursive parsing.
  private static func expandResponseFiles(
    _ args: [String],
    fileSystem: FileSystem,
    diagnosticsEngine: DiagnosticsEngine,
    relativeTo basePath: AbsolutePath?,
    visitedResponseFiles: inout Set<VisitedResponseFile>
  ) throws -> [String] {
    var result: [String] = []

    // Go through each arg and add arguments from response files.
    for arg in args {
      if arg.first == "@", let responseFile = resolveResponseFile(String(arg.dropFirst()), relativeTo: basePath, fileSystem: fileSystem) {
        // Guard against infinite parsing loop.
        guard let visitationToken = try shouldVisitResponseFile(responseFile, fileSystem: fileSystem, visitedResponseFiles: &visitedResponseFiles) else {
          diagnosticsEngine.emit(.warn_recursive_response_file(responseFile))
          continue
        }
        defer {
          visitedResponseFiles.remove(visitationToken)
        }

        let contents = try fileSystem.readFileContents(responseFile).cString
        let lines = tokenizeResponseFile(contents)
        result.append(contentsOf: try expandResponseFiles(lines, fileSystem: fileSystem, diagnosticsEngine: diagnosticsEngine, relativeTo: basePath, visitedResponseFiles: &visitedResponseFiles))
      } else {
        result.append(arg)
      }
    }

    return result
  }

  /// Expand response files in the input arguments and return a new argument list.
  public static func expandResponseFiles(
    _ args: [String],
    fileSystem: FileSystem,
    diagnosticsEngine: DiagnosticsEngine
  ) throws -> [String] {
    var visitedResponseFiles = Set<VisitedResponseFile>()
    return try expandResponseFiles(args, fileSystem: fileSystem, diagnosticsEngine: diagnosticsEngine, relativeTo: fileSystem.currentWorkingDirectory, visitedResponseFiles: &visitedResponseFiles)
  }
}

extension Diagnostic.Message {
  static func warn_unused_option(_ option: ParsedOption) -> Diagnostic.Message {
    .warning("Unused option: \(option)")
  }
}

extension Driver {
  /// Determine the driver kind based on the command-line arguments, consuming the arguments
  /// conveying this information.
  @_spi(Testing) public static func determineDriverKind(
    args: inout [String]
  ) throws -> DriverKind {
    // Get the basename of the driver executable.
    let execRelPath = args.removeFirst()
    var driverName = try VirtualPath(path: execRelPath).basenameWithoutExt

    // Determine if the driver kind is being overridden.
    let driverModeOption = "--driver-mode="
    if let firstArg = args.first, firstArg.hasPrefix(driverModeOption) {
      args.removeFirst()
      driverName = String(firstArg.dropFirst(driverModeOption.count))
    }

    switch driverName {
    case "swift":
      return .interactive
    case "swiftc":
      return .batch
    default:
      throw Error.invalidDriverName(driverName)
    }
  }

  /// Run the driver.
  public mutating func run(
    jobs: [Job]
  ) throws {
    if parsedOptions.hasArgument(.v) {
      try printVersion(outputStream: &stderrStream)
    }

    let forceResponseFiles = parsedOptions.contains(.driverForceResponseFiles)

    // If we're only supposed to print the jobs, do so now.
    if parsedOptions.contains(.driverPrintJobs) {
      for job in jobs {
        print(try executor.description(of: job, forceResponseFiles: forceResponseFiles))
      }
      return
    }

    // If we're only supposed to explain a dependency on a given module, do so now.
    if let explainModuleName = parsedOptions.getLastArgument(.explainModuleDependency) {
      guard let dependencyPlanner = explicitDependencyBuildPlanner else {
        fatalError("Cannot explain dependency without Explicit Build Planner")
      }
      guard let dependencyPaths = try dependencyPlanner.explainDependency(explainModuleName.asSingle) else {
        diagnosticEngine.emit(.remark("No such module dependency found: '\(explainModuleName.asSingle)'"))
        return
      }
      diagnosticEngine.emit(.remark("Module '\(moduleOutputInfo.name)' depends on '\(explainModuleName.asSingle)'"))
      for path in dependencyPaths {
        var pathString:String = ""
        for (index, moduleId) in path.enumerated() {
          switch moduleId {
          case .swift(let moduleName):
            pathString = pathString + "[" + moduleName + "]"
          case .swiftPrebuiltExternal(let moduleName):
            pathString = pathString + "[" + moduleName + "]"
          case .clang(let moduleName):
            pathString = pathString + "[" + moduleName + "](ObjC)"
          case .swiftPlaceholder(_):
            fatalError("Unexpected unresolved Placeholder module")
          }
          if index < path.count - 1 {
            pathString = pathString + " -> "
          }
        }
        diagnosticEngine.emit(.note(pathString))
      }
    }

    if parsedOptions.contains(.driverPrintOutputFileMap) {
      if let outputFileMap = self.outputFileMap {
        stderrStream.send(outputFileMap.description)
        stderrStream.flush()
      } else {
        diagnosticEngine.emit(.error_no_output_file_map_specified)
      }
      return
    }

    if parsedOptions.contains(.driverPrintBindings) {
      for job in jobs {
        printBindings(job)
      }
      return
    }

    if parsedOptions.contains(.driverPrintActions) {
      // Print actions using the same style as the old C++ driver
      // This is mostly for testing purposes. We should print semantically
      // equivalent actions as the old driver.
      printActions(jobs)
      return
    }

    if parsedOptions.contains(.driverPrintGraphviz) {
      var serializer = DOTJobGraphSerializer(jobs: jobs)
      serializer.writeDOT(to: &stdoutStream)
      stdoutStream.flush()
      return
    }

    let toolExecutionDelegate = createToolExecutionDelegate()

    defer {
      // Attempt to cleanup temporary files before exiting, unless -save-temps was passed or a job crashed.
      if !parsedOptions.hasArgument(.saveTemps) && !toolExecutionDelegate.anyJobHadAbnormalExit {
          try? executor.resolver.removeTemporaryDirectory()
      }
    }

    // Jobs which are run as child processes of the driver.
    var childJobs: [Job]
    // A job which runs in-place, replacing the driver.
    var inPlaceJob: Job?

    if jobs.contains(where: { $0.requiresInPlaceExecution }) {
      childJobs = jobs.filter { !$0.requiresInPlaceExecution }
      let inPlaceJobs = jobs.filter(\.requiresInPlaceExecution)
      assert(inPlaceJobs.count == 1,
             "Cannot execute multiple jobs in-place")
      inPlaceJob = inPlaceJobs.first
    } else if jobs.count == 1 && !parsedOptions.hasArgument(.parseableOutput) &&
                buildRecordInfo == nil {
      // Only one job and no cleanup required, e.g. not writing build record
      inPlaceJob = jobs[0]
      childJobs = []
    } else {
      childJobs = jobs
      inPlaceJob = nil
    }
    inPlaceJob?.requiresInPlaceExecution = true

    if !childJobs.isEmpty {
      do {
        defer {
          writeIncrementalBuildInformation(jobs)
        }
        try performTheBuild(allJobs: childJobs,
                            jobExecutionDelegate: toolExecutionDelegate,
                            forceResponseFiles: forceResponseFiles)
      }
    }

    // If we have a job to run in-place, do so at the end.
    if let inPlaceJob = inPlaceJob {
      // Print the driver source version first before we print the compiler
      // versions.
      if inPlaceJob.kind == .versionRequest && !Driver.driverSourceVersion.isEmpty {
        stderrStream.send("swift-driver version: \(Driver.driverSourceVersion) ")
        if let blocklistVersion = try Driver.findCompilerClientsConfigVersion(RelativeTo: try toolchain.executableDir) {
          stderrStream.send("\(blocklistVersion) ")
        }
        stderrStream.flush()
      }
      // In verbose mode, print out the job
      if parsedOptions.contains(.v) {
        let arguments: [String] = try executor.resolver.resolveArgumentList(for: inPlaceJob,
                                                                            useResponseFiles: forceResponseFiles ? .forced : .heuristic)
        stdoutStream.send("\(arguments.map { $0.spm_shellEscaped() }.joined(separator: " "))\n")
        stdoutStream.flush()
      }
      try executor.execute(job: inPlaceJob,
                           forceResponseFiles: forceResponseFiles,
                           recordedInputModificationDates: recordedInputModificationDates)
    }

    // If requested, warn for options that weren't used by the driver after the build is finished.
    if parsedOptions.hasArgument(.driverWarnUnusedOptions) {
      for option in parsedOptions.unconsumedOptions {
        diagnosticEngine.emit(.warn_unused_option(option))
      }
    }
  }

  mutating func createToolExecutionDelegate() -> ToolExecutionDelegate {
    var mode: ToolExecutionDelegate.Mode = .regular

    // FIXME: Old driver does _something_ if both -parseable-output and -v are passed.
    // Not sure if we want to support that.
    if parsedOptions.contains(.parseableOutput) {
      mode = .parsableOutput
    } else if parsedOptions.contains(.v) {
      mode = .verbose
    } else if integratedDriver {
      mode = .silent
    }

    return ToolExecutionDelegate(
      mode: mode,
      buildRecordInfo: buildRecordInfo,
      showJobLifecycle: showJobLifecycle,
      argsResolver: executor.resolver,
      diagnosticEngine: diagnosticEngine)
  }

  private mutating func performTheBuild(
    allJobs: [Job],
    jobExecutionDelegate: JobExecutionDelegate,
    forceResponseFiles: Bool
  ) throws {
    let continueBuildingAfterErrors = computeContinueBuildingAfterErrors()
    try executor.execute(
      workload: .init(allJobs,
                      incrementalCompilationState,
                      interModuleDependencyGraph,
                      continueBuildingAfterErrors: continueBuildingAfterErrors),
      delegate: jobExecutionDelegate,
      numParallelJobs: numParallelJobs ?? 1,
      forceResponseFiles: forceResponseFiles,
      recordedInputModificationDates: recordedInputModificationDates)
  }

  public func writeIncrementalBuildInformation(_ jobs: [Job]) {
    // In case the write fails, don't crash the build.
    // A mitigation to rdar://76359678.
    // If the write fails, import incrementality is lost, but it is not a fatal error.
    guard
      let buildRecordInfo = self.buildRecordInfo,
      let absPath = buildRecordInfo.buildRecordPath.absolutePath
    else {
      return
    }

    let buildRecord = buildRecordInfo.buildRecord(
      jobs, self.incrementalCompilationState?.blockingConcurrentMutationToProtectedState{
        $0.skippedCompilationInputs
      })

    if
      let incrementalCompilationState = self.incrementalCompilationState,
      incrementalCompilationState.info.isCrossModuleIncrementalBuildEnabled
    {
      do {
        try incrementalCompilationState.writeDependencyGraph(to: buildRecordInfo.dependencyGraphPath, buildRecord)
      } catch {
        diagnosticEngine.emit(
          .warning("next compile won't be incremental; could not write dependency graph: \(error.localizedDescription)"))
        /// Ensure that a bogus dependency graph is not used next time.
        buildRecordInfo.removeBuildRecord()
        buildRecordInfo.removeInterModuleDependencyGraph()
        return
      }
      do {
        try incrementalCompilationState.writeInterModuleDependencyGraph(buildRecordInfo)
      } catch {
        diagnosticEngine.emit(
          .warning("next compile must run a full dependency scan; could not write inter-module dependency graph: \(error.localizedDescription)"))
        buildRecordInfo.removeBuildRecord()
        buildRecordInfo.removeInterModuleDependencyGraph()
        return
      }
    } else {
      // FIXME: This is all legacy code. Once the cross module incremental build
      // becomes the default:
      //
      // 1) Delete this branch
      // 2) Delete the parts of the incremental build that talk about anything
      //    derived from `buildRecordPath`
      // 3) Delete the Yams dependency.

      // Before writing to the dependencies file path, preserve any previous file
      // that may have been there. No error handling -- this is just a nicety, it
      // doesn't matter if it fails.
      // Added for the sake of compatibility with the legacy driver.
      try? fileSystem.move(
        from: absPath, to: absPath.appending(component: absPath.basename + "~"))

      guard let contents = buildRecord.encode(diagnosticEngine: diagnosticEngine) else {
        diagnosticEngine.emit(.warning_could_not_write_build_record(absPath))
        return
      }

      do {
        try fileSystem.writeFileContents(absPath,
                                         bytes: ByteString(encodingAsUTF8: contents))
      } catch {
        diagnosticEngine.emit(.warning_could_not_write_build_record(absPath))
      }
    }
  }

  private func printBindings(_ job: Job) {
    stdoutStream.send(#"# ""#).send(targetTriple.triple)
    stdoutStream.send(#"" - ""#).send(job.tool.basename)
    stdoutStream.send(#"", inputs: ["#)
    stdoutStream.send(job.displayInputs.map { "\"" + $0.file.name + "\"" }.joined(separator: ", "))

    stdoutStream.send("], output: {")

    stdoutStream.send(job.outputs.map { $0.type.name + ": \"" + $0.file.name + "\"" }.joined(separator: ", "))

    stdoutStream.send("}\n")
    stdoutStream.flush()
  }

  /// This handles -driver-print-actions flag. The C++ driver has a concept of actions
  /// which it builds up a list of actions before then creating them into jobs.
  /// The swift-driver doesn't have actions, so the logic here takes the jobs and tries
  /// to mimic the actions that would be created by the C++ driver and
  /// prints them in *hopefully* the same order.
  private mutating func printActions(_ jobs: [Job]) {
    defer {
      stdoutStream.flush()
    }

    // Put bridging header as first input if we have it
    let allInputs: [TypedVirtualPath]
    if let objcHeader = importedObjCHeader, bridgingPrecompiledHeader != nil {
      allInputs = [TypedVirtualPath(file: objcHeader, type: .objcHeader)] + inputFiles
    } else {
      allInputs = inputFiles
    }

    var jobIdMap = Dictionary<Job, UInt>()
    // The C++ driver treats each input as an action, we should print them as
    // an action too for testing purposes.
    var inputIdMap = Dictionary<TypedVirtualPath, UInt>()
    var nextId: UInt = 0
    var allInputsIterator = allInputs.makeIterator()
    for job in jobs {
      // After "module input" jobs, print any left over inputs
      switch job.kind {
      case .generatePCH, .compile, .backend:
        break
      default:
        while let input = allInputsIterator.next() {
          Self.printInputIfNew(input, inputIdMap: &inputIdMap, nextId: &nextId)
        }
      }
      // All input action IDs for this action.
      var inputIds = [UInt]()

      var jobInputs = job.primaryInputs.isEmpty ? job.inputs : job.primaryInputs
      if let pchPath = bridgingPrecompiledHeader, job.kind == .compile {
        jobInputs.append(TypedVirtualPath(file: pchPath, type: .pch))
      }
      // Collect input job IDs.
      for input in jobInputs {
        if let id = inputIdMap[input] {
          inputIds.append(id)
          continue
        }
        var foundInput = false
        for (prevJob, id) in jobIdMap {
          if prevJob.outputs.contains(input) {
            foundInput = true
            inputIds.append(id)
            break
          }
        }
        if !foundInput {
          while let nextInputAction = allInputsIterator.next() {
            Self.printInputIfNew(nextInputAction, inputIdMap: &inputIdMap, nextId: &nextId)
            if let id = inputIdMap[input] {
              inputIds.append(id)
              break
            }
          }
        }
      }

      // Print current Job
      stdoutStream.send("\(nextId): ").send(job.kind.rawValue).send(", {")
      switch job.kind {
      // Don't sort for compile jobs. Puts pch last
      case .compile:
        stdoutStream.send(inputIds.map(\.description).joined(separator: ", "))
      default:
        stdoutStream.send(inputIds.sorted().map(\.description).joined(separator: ", "))
      }
      var typeName = job.outputs.first?.type.name
      if typeName == nil {
        typeName = "none"
      }
      stdoutStream.send("}, \(typeName!)\n")
      jobIdMap[job] = nextId
      nextId += 1
    }
  }

  private static func printInputIfNew(_ input: TypedVirtualPath, inputIdMap: inout [TypedVirtualPath: UInt], nextId: inout UInt) {
    if inputIdMap[input] == nil {
      stdoutStream.send("\(nextId): input, ")
      stdoutStream.send("\"\(input.file)\", \(input.type)\n")
      inputIdMap[input] = nextId
      nextId += 1
    }
  }

  private func printVersion<S: OutputByteStream>(outputStream: inout S) throws {
    outputStream.send("\(frontendTargetInfo.compilerVersion)\n")
    outputStream.send("Target: \(frontendTargetInfo.target.triple.triple)\n")
    outputStream.flush()
  }
}

extension Diagnostic.Message {
  static func warn_recursive_response_file(_ path: AbsolutePath) -> Diagnostic.Message {
    .warning("response file '\(path)' is recursively expanded")
  }

  static var error_no_swift_frontend: Diagnostic.Message {
    .error("-driver-use-frontend-path requires a Swift compiler executable argument")
  }

  static var warning_cannot_multithread_batch_mode: Diagnostic.Message {
    .warning("ignoring -num-threads argument; cannot multithread batch mode")
  }

  static var error_no_output_file_map_specified: Diagnostic.Message {
    .error("no output file map specified")
  }
}

extension Driver {
  /// Parse an option's value into an `Int`.
  ///
  /// If the parsed options don't contain an option with this value, returns
  /// `nil`.
  /// If the parsed option does contain an option with this value, but the
  /// value is not parsable as an `Int`, emits an error and returns `nil`.
  /// Otherwise, returns the parsed value.
  private static func parseIntOption(
    _ parsedOptions: inout ParsedOptions,
    option: Option,
    diagnosticsEngine: DiagnosticsEngine
  ) -> Int? {
    guard let argument = parsedOptions.getLastArgument(option) else {
      return nil
    }

    guard let value = Int(argument.asSingle) else {
      diagnosticsEngine.emit(.error_invalid_arg_value(arg: option, value: argument.asSingle))
      return nil
    }

    return value
  }
}

extension Driver {
  private static func computeFileListThreshold(
    _ parsedOptions: inout ParsedOptions,
    diagnosticsEngine: DiagnosticsEngine
  ) throws -> Int {
    let hasUseFileLists = parsedOptions.hasArgument(.driverUseFilelists)

    if hasUseFileLists {
      diagnosticsEngine.emit(.warn_use_filelists_deprecated)
    }

    if let threshold = parsedOptions.getLastArgument(.driverFilelistThreshold)?.asSingle {
      if let thresholdInt = Int(threshold) {
        return thresholdInt
      } else {
        throw Error.invalidArgumentValue(Option.driverFilelistThreshold.spelling, threshold)
      }
    } else if hasUseFileLists {
      return 0
    }

    return 128
  }
}

private extension Diagnostic.Message {
  static var warn_use_filelists_deprecated: Diagnostic.Message {
    .warning("the option '-driver-use-filelists' is deprecated; use '-driver-filelist-threshold=0' instead")
  }
}

extension Driver {
  /// Compute the compiler mode based on the options.
  private static func computeCompilerMode(
    _ parsedOptions: inout ParsedOptions,
    driverKind: DriverKind,
    diagnosticsEngine: DiagnosticsEngine
  ) throws -> CompilerMode {
    // Some output flags affect the compiler mode.
    if let outputOption = parsedOptions.getLast(in: .modes) {
      switch outputOption.option {
      case .emitImportedModules:
        return .singleCompile
      case .repl, .lldbRepl:
        return .repl

      case .deprecatedIntegratedRepl:
        throw Error.integratedReplRemoved

      case .emitPcm:
        return .compilePCM

      case .dumpPcm:
        return .dumpPCM

      default:
        // Output flag doesn't determine the compiler mode.
        break
      }
    }

    if driverKind == .interactive {
      if parsedOptions.hasAnyInput {
        return .immediate
      } else {
        if parsedOptions.contains(Option.repl) {
          return .repl
        } else {
          return .intro
        }
      }
    }

    let useWMO = parsedOptions.hasFlag(positive: .wholeModuleOptimization, negative: .noWholeModuleOptimization, default: false)
    let hasIndexFile = parsedOptions.hasArgument(.indexFile)
    let wantBatchMode = parsedOptions.hasFlag(positive: .enableBatchMode, negative: .disableBatchMode, default: false)

    // AST dump doesn't work with `-wmo`/`-index-file`. Since it's not common to want to dump
    // the AST, we assume that's the priority and ignore those flags, but we warn the
    // user about this decision.
    if useWMO && parsedOptions.hasArgument(.dumpAst) {
      diagnosticsEngine.emit(.warning_option_overrides_another(overridingOption: .dumpAst,
                                                               overridenOption: .wmo))
      parsedOptions.eraseArgument(.wmo)
      return .standardCompile
    }

    if hasIndexFile && parsedOptions.hasArgument(.dumpAst) {
      diagnosticsEngine.emit(.warning_option_overrides_another(overridingOption: .dumpAst,
                                                               overridenOption: .indexFile))
      parsedOptions.eraseArgument(.indexFile)
      parsedOptions.eraseArgument(.indexFilePath)
      parsedOptions.eraseArgument(.indexStorePath)
      parsedOptions.eraseArgument(.indexIgnoreSystemModules)
      return .standardCompile
    }

    if useWMO || hasIndexFile {
      if wantBatchMode {
        let disablingOption: Option = useWMO ? .wholeModuleOptimization : .indexFile
        diagnosticsEngine.emit(.warn_ignoring_batch_mode(disablingOption))
      }

      return .singleCompile
    }

    // For batch mode, collect information
    if wantBatchMode {
      let batchSeed = parseIntOption(&parsedOptions, option: .driverBatchSeed, diagnosticsEngine: diagnosticsEngine)
      let batchCount = parseIntOption(&parsedOptions, option: .driverBatchCount, diagnosticsEngine: diagnosticsEngine)
      let batchSizeLimit = parseIntOption(&parsedOptions, option: .driverBatchSizeLimit, diagnosticsEngine: diagnosticsEngine)
      return .batchCompile(BatchModeInfo(seed: batchSeed, count: batchCount, sizeLimit: batchSizeLimit))
    }

    return .standardCompile
  }
}

extension Diagnostic.Message {
  static func warn_ignoring_batch_mode(_ option: Option) -> Diagnostic.Message {
    .warning("ignoring '-enable-batch-mode' because '\(option.spelling)' was also specified")
  }
}

/// Input and output file handling.
extension Driver {
  /// Apply the given working directory to all paths in the parsed options.
  private static func applyWorkingDirectory(_ workingDirectory: AbsolutePath,
                                            to parsedOptions: inout ParsedOptions) throws {
    try parsedOptions.forEachModifying { parsedOption in
      // Only translate options whose arguments are paths.
      if !parsedOption.option.attributes.contains(.argumentIsPath) { return }

      let translatedArgument: ParsedOption.Argument
      switch parsedOption.argument {
      case .none:
        return

      case .single(let arg):
        if arg == "-" {
          translatedArgument = parsedOption.argument
        } else {
          translatedArgument = .single(try AbsolutePath(validating: arg, relativeTo: workingDirectory).pathString)
        }

      case .multiple(let args):
        translatedArgument = .multiple(try args.map { arg in
          try AbsolutePath(validating: arg, relativeTo: workingDirectory).pathString
        })
      }

      parsedOption = .init(
        option: parsedOption.option,
        argument: translatedArgument,
        index: parsedOption.index
      )
    }
  }

  /// Collect all of the input files from the parsed options, translating them into input files.
  private static func collectInputFiles(
    _ parsedOptions: inout ParsedOptions,
    diagnosticsEngine: DiagnosticsEngine,
    fileSystem: FileSystem
  ) throws -> [TypedVirtualPath] {
    var swiftFiles = [String: String]() // [Basename: Path]
    var paths: [TypedVirtualPath] = try parsedOptions.allInputs.map { input in
      // Standard input is assumed to be Swift code.
      if input == "-" {
        return TypedVirtualPath(file: .standardInput, type: .swift)
      }

      // Resolve the input file.
      let inputHandle = try VirtualPath.intern(path: input)
      let inputFile = VirtualPath.lookup(inputHandle)
      let fileExtension = inputFile.extension ?? ""

      // Determine the type of the input file based on its extension.
      // If we don't recognize the extension, treat it as an object file.
      // FIXME: The object-file default is carried over from the existing
      // driver, but seems odd.
      let fileType = FileType(rawValue: fileExtension) ?? FileType.object

      if fileType == .swift {
        let basename = inputFile.basename
        if let originalPath = swiftFiles[basename] {
          diagnosticsEngine.emit(.error_two_files_same_name(basename: basename, firstPath: originalPath, secondPath: input))
          diagnosticsEngine.emit(.note_explain_two_files_same_name)
          throw ErrorDiagnostics.emitted
        } else {
          swiftFiles[basename] = input
        }
      }

      return TypedVirtualPath(file: inputHandle, type: fileType)
    }

    if parsedOptions.hasArgument(.e) {
      if let mainPath = swiftFiles["main.swift"] {
        diagnosticsEngine.emit(.error_two_files_same_name(basename: "main.swift", firstPath: mainPath, secondPath: "-e"))
        diagnosticsEngine.emit(.note_explain_two_files_same_name)
        throw ErrorDiagnostics.emitted
      }

      try withTemporaryDirectory(dir: fileSystem.tempDirectory, removeTreeOnDeinit: false) { absPath in
        let filePath = VirtualPath.absolute(absPath.appending(component: "main.swift"))

        try fileSystem.writeFileContents(filePath) { file in
          file.send(###"#sourceLocation(file: "-e", line: 1)\###n"###)
          for option in parsedOptions.arguments(for: .e) {
            file.send("\(option.argument.asSingle)\n")
          }
        }

        paths.append(TypedVirtualPath(file: filePath.intern(), type: .swift))
      }
    }

    return paths
  }

  /// Determine the primary compiler and linker output kinds.
  private static func determinePrimaryOutputs(
    _ parsedOptions: inout ParsedOptions,
    targetTriple: Triple,
    driverKind: DriverKind,
    diagnosticsEngine: DiagnosticsEngine
  ) -> (FileType?, LinkOutputType?) {
    // By default, the driver does not link its output. However, this will be updated below.
    var compilerOutputType: FileType? = (driverKind == .interactive ? nil : .object)
    var linkerOutputType: LinkOutputType? = nil
    let objectLikeFileType: FileType = parsedOptions.getLastArgument(.lto) != nil ? .llvmBitcode : .object

    if let outputOption = parsedOptions.getLast(in: .modes) {
      switch outputOption.option {
      case .emitExecutable:
        if parsedOptions.contains(.static) && !targetTriple.supportsStaticExecutables {
          diagnosticsEngine.emit(.error_static_emit_executable_disallowed)
        }
        linkerOutputType = .executable
        compilerOutputType = objectLikeFileType

      case .emitLibrary:
        linkerOutputType = parsedOptions.hasArgument(.static) ? .staticLibrary : .dynamicLibrary
        compilerOutputType = objectLikeFileType

      case .emitObject, .c:
        compilerOutputType = objectLikeFileType

      case .emitAssembly, .S:
        compilerOutputType = .assembly

      case .emitSil:
        compilerOutputType = .sil

      case .emitSilgen:
        compilerOutputType = .raw_sil

      case .emitSib:
        compilerOutputType = .sib

      case .emitSibgen:
        compilerOutputType = .raw_sib

      case .emitIrgen, .emitIr:
        compilerOutputType = .llvmIR

      case .emitBc:
        compilerOutputType = .llvmBitcode

      case .dumpAst:
        compilerOutputType = .ast

      case .emitPcm:
        compilerOutputType = .pcm

      case .dumpPcm:
        compilerOutputType = nil

      case .emitImportedModules:
        compilerOutputType = .importedModules

      case .indexFile:
        compilerOutputType = .indexData

      case .parse, .resolveImports, .typecheck,
           .dumpParse, .printAst, .dumpTypeRefinementContexts, .dumpScopeMaps,
           .dumpInterfaceHash, .dumpTypeInfo, .verifyDebugInfo:
        compilerOutputType = nil

      case .i:
        diagnosticsEngine.emit(.error_i_mode)

      case .repl, .deprecatedIntegratedRepl, .lldbRepl:
        compilerOutputType = nil

      case .interpret:
        compilerOutputType = nil

      case .scanDependencies:
        compilerOutputType = .jsonDependencies

      default:
        fatalError("unhandled output mode option \(outputOption)")
      }
    } else if parsedOptions.hasArgument(.emitModule, .emitModulePath) {
      compilerOutputType = .swiftModule
    } else if driverKind != .interactive {
      compilerOutputType = objectLikeFileType
      linkerOutputType = .executable
    }

    // warn if -embed-bitcode is set and the output type is not an object
    if parsedOptions.hasArgument(.embedBitcode) && compilerOutputType != .object {
      diagnosticsEngine.emit(.warn_ignore_embed_bitcode)
      parsedOptions.eraseArgument(.embedBitcode)
    }
    if parsedOptions.hasArgument(.embedBitcodeMarker) && compilerOutputType != .object {
      diagnosticsEngine.emit(.warn_ignore_embed_bitcode_marker)
      parsedOptions.eraseArgument(.embedBitcodeMarker)
    }

    return (compilerOutputType, linkerOutputType)
  }
}

extension Diagnostic.Message {
  static var error_i_mode: Diagnostic.Message {
    .error(
      """
      the flag '-i' is no longer required and has been removed; \
      use '\(DriverKind.interactive.usage) input-filename'
      """
    )
  }

  static var warn_ignore_embed_bitcode: Diagnostic.Message {
    .warning("ignoring -embed-bitcode since no object file is being generated")
  }

  static var warn_ignore_embed_bitcode_marker: Diagnostic.Message {
    .warning("ignoring -embed-bitcode-marker since no object file is being generated")
  }

  static func error_two_files_same_name(basename: String, firstPath: String, secondPath: String) -> Diagnostic.Message {
    .error("filename \"\(basename)\" used twice: '\(firstPath)' and '\(secondPath)'")
  }

  static var note_explain_two_files_same_name: Diagnostic.Message {
    .note("filenames are used to distinguish private declarations with the same name")
  }
}

// Multithreading
extension Driver {
  /// Determine the number of threads to use for a multithreaded build,
  /// or zero to indicate a single-threaded build.
  static func determineNumThreads(
    _ parsedOptions: inout ParsedOptions,
    compilerMode: CompilerMode, diagnosticsEngine: DiagnosticsEngine
  ) -> Int {
    guard let numThreadsArg = parsedOptions.getLastArgument(.numThreads) else {
      return 0
    }

    // Make sure we have a non-negative integer value.
    guard let numThreads = Int(numThreadsArg.asSingle), numThreads >= 0 else {
      diagnosticsEngine.emit(.error_invalid_arg_value(arg: .numThreads, value: numThreadsArg.asSingle))
      return 0
    }

    if case .batchCompile = compilerMode {
      diagnosticsEngine.emit(.warning_cannot_multithread_batch_mode)
      return 0
    }

    return numThreads
  }

  /// Determine the number of parallel jobs to execute.
  static func determineNumParallelJobs(
    _ parsedOptions: inout ParsedOptions,
    diagnosticsEngine: DiagnosticsEngine,
    env: [String: String]
  ) -> Int? {
    guard let numJobs = parseIntOption(&parsedOptions, option: .j, diagnosticsEngine: diagnosticsEngine) else {
      return nil
    }

    guard numJobs >= 1 else {
      diagnosticsEngine.emit(.error_invalid_arg_value(arg: .j, value: String(numJobs)))
      return nil
    }

    if let determinismRequested = env["SWIFTC_MAXIMUM_DETERMINISM"], !determinismRequested.isEmpty {
      diagnosticsEngine.emit(.remark_max_determinism_overriding(.j))
      return 1
    }

    return numJobs
  }

  private mutating func computeContinueBuildingAfterErrors() -> Bool {
    // Note: Batch mode handling of serialized diagnostics requires that all
    // batches get to run, in order to make sure that all diagnostics emitted
    // during the compilation end up in at least one serialized diagnostic file.
    // Therefore, treat batch mode as implying -continue-building-after-errors.
    // (This behavior could be limited to only when serialized diagnostics are
    // being emitted, but this seems more consistent and less surprising for
    // users.)
    // FIXME: We don't really need (or want) a full ContinueBuildingAfterErrors.
    // If we fail to precompile a bridging header, for example, there's no need
    // to go on to compilation of source files, and if compilation of source files
    // fails, we shouldn't try to link. Instead, we'd want to let all jobs finish
    // but not schedule any new ones.
    return compilerMode.isBatchCompile || parsedOptions.contains(.continueBuildingAfterErrors)
  }
}


extension Diagnostic.Message {
  static func remark_max_determinism_overriding(_ option: Option) -> Diagnostic.Message {
    .remark("SWIFTC_MAXIMUM_DETERMINISM overriding \(option.spelling)")
  }
}

// Debug information
extension Driver {
  /// Compute the level of debug information we are supposed to produce.
  private static func computeDebugInfo(_ parsedOptions: inout ParsedOptions,
                                       defaultDwarfVersion : UInt8,
                                       diagnosticsEngine: DiagnosticsEngine) -> DebugInfo {
    var shouldVerify = parsedOptions.hasArgument(.verifyDebugInfo)

    for debugPrefixMap in parsedOptions.arguments(for: .debugPrefixMap) {
      let value = debugPrefixMap.argument.asSingle
      let parts = value.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
      if parts.count != 2 {
        diagnosticsEngine.emit(.error_opt_invalid_mapping(option: debugPrefixMap.option, value: value))
      }
    }

    for filePrefixMap in parsedOptions.arguments(for: .filePrefixMap) {
      let value = filePrefixMap.argument.asSingle
      let parts = value.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
      if parts.count != 2 {
        diagnosticsEngine.emit(.error_opt_invalid_mapping(option: filePrefixMap.option, value: value))
      }
    }

    // Determine the debug level.
    let level: DebugInfo.Level?
    if let levelOption = parsedOptions.getLast(in: .g), levelOption.option != .gnone {
      switch levelOption.option {
      case .g:
        level = .astTypes

      case .glineTablesOnly:
        level = .lineTables

      case .gdwarfTypes:
        level = .dwarfTypes

      default:
        fatalError("Unhandle option in the '-g' group")
      }
    } else {
      // -gnone, or no debug level specified
      level = nil
      if shouldVerify {
        shouldVerify = false
        diagnosticsEngine.emit(.verify_debug_info_requires_debug_option)
      }
    }

    // Determine the debug info format.
    let format: DebugInfo.Format
    if let formatArg = parsedOptions.getLastArgument(.debugInfoFormat) {
      if let parsedFormat = DebugInfo.Format(rawValue: formatArg.asSingle) {
        format = parsedFormat
      } else {
        diagnosticsEngine.emit(.error_invalid_arg_value(arg: .debugInfoFormat, value: formatArg.asSingle))
        format = .dwarf
      }

      if !parsedOptions.contains(in: .g) {
        diagnosticsEngine.emit(.error_option_missing_required_argument(option: .debugInfoFormat, requiredArg: "-g"))
      }
    } else {
      // Default to DWARF.
      format = .dwarf
    }

    if format == .codeView && (level == .lineTables || level == .dwarfTypes) {
      let levelOption = parsedOptions.getLast(in: .g)!.option
      let fullNotAllowedOption = Option.debugInfoFormat.spelling + format.rawValue
      diagnosticsEngine.emit(.error_argument_not_allowed_with(arg: fullNotAllowedOption, other: levelOption.spelling))
    }

    // Determine the DWARF version.
    var dwarfVersion: UInt8 = defaultDwarfVersion
    if let versionArg = parsedOptions.getLastArgument(.dwarfVersion) {
      if let parsedVersion = UInt8(versionArg.asSingle), parsedVersion >= 2 && parsedVersion <= 5 {
        dwarfVersion = parsedVersion
      } else {
        diagnosticsEngine.emit(.error_invalid_arg_value(arg: .dwarfVersion, value: versionArg.asSingle))
      }
    }

    return DebugInfo(format: format, dwarfVersion: dwarfVersion, level: level, shouldVerify: shouldVerify)
  }

  /// Parses the set of `-sanitize={sanitizer}` arguments and returns all the
  /// sanitizers that were requested.
  static func parseSanitizerArgValues(
    _ parsedOptions: inout ParsedOptions,
    diagnosticEngine: DiagnosticsEngine,
    toolchain: Toolchain,
    targetInfo: FrontendTargetInfo
  ) throws -> Set<Sanitizer> {

    var set = Set<Sanitizer>()

    let args = parsedOptions
      .filter { $0.option == .sanitizeEQ }
      .flatMap { $0.argument.asMultiple }

    // No sanitizer args found, we could return.
    if args.isEmpty {
      return set
    }

    let targetTriple = targetInfo.target.triple
    // Find the sanitizer kind.
    for arg in args {
      guard let sanitizer = Sanitizer(rawValue: arg) else {
        // Unrecognized sanitizer option
        diagnosticEngine.emit(
          .error_invalid_arg_value(arg: .sanitizeEQ, value: arg))
        continue
      }

      let stableAbi = sanitizer == .address && parsedOptions.contains(.sanitizeStableAbiEQ)
      // Support is determined by existence of the sanitizer library.
      // FIXME: Should we do this? This prevents cross-compiling with sanitizers
      //        enabled.
      var sanitizerSupported = try toolchain.runtimeLibraryExists(
        for: stableAbi ? .address_stable_abi : sanitizer,
        targetInfo: targetInfo,
        parsedOptions: &parsedOptions,
        isShared: sanitizer != .fuzzer && !stableAbi
      )

      if sanitizer == .thread {
        // TSAN is unavailable on Windows
        if targetTriple.isWindows {
          diagnosticEngine.emit(
            .error_sanitizer_unavailable_on_target(
              sanitizer: "thread",
              target: targetTriple
            )
          )
          continue
        }

        // TSan is explicitly not supported for 32 bits.
        if !targetTriple.arch!.is64Bit {
          sanitizerSupported = false
        }
      }

      if !sanitizerSupported {
        diagnosticEngine.emit(
          .error_unsupported_opt_for_target(
            arg: "-sanitize=\(sanitizer.rawValue)",
            target: targetTriple
          )
        )
      } else {
        set.insert(sanitizer)
      }
    }

    // Check that we're one of the known supported targets for sanitizers.
    if !(targetTriple.isWindows || targetTriple.isDarwin || targetTriple.os == .linux) {
      diagnosticEngine.emit(
        .error_unsupported_opt_for_target(
          arg: "-sanitize=",
          target: targetTriple
        )
      )
    }

    // Address and thread sanitizers can not be enabled concurrently.
    if set.contains(.thread) && set.contains(.address) {
      diagnosticEngine.emit(
        .error_argument_not_allowed_with(
          arg: "-sanitize=thread",
          other: "-sanitize=address"
        )
      )
    }

    // Scudo can only be run with ubsan.
    if set.contains(.scudo) {
      let allowedSanitizers: Set<Sanitizer> = [.scudo, .undefinedBehavior]
      for forbiddenSanitizer in set.subtracting(allowedSanitizers) {
        diagnosticEngine.emit(
          .error_argument_not_allowed_with(
            arg: "-sanitize=scudo",
            other: "-sanitize=\(forbiddenSanitizer.rawValue)"
          )
        )
      }
    }

    return set
  }

}

extension Diagnostic.Message {
  static var verify_debug_info_requires_debug_option: Diagnostic.Message {
    .warning("ignoring '-verify-debug-info'; no debug info is being generated")
  }

  static func warning_option_requires_sanitizer(currentOption: Option, currentOptionValue: String, sanitizerRequired: Sanitizer) -> Diagnostic.Message {
      .warning("option '\(currentOption.spelling)\(currentOptionValue)' has no effect when '\(sanitizerRequired)' sanitizer is disabled. Use \(Option.sanitizeEQ.spelling)\(sanitizerRequired) to enable the sanitizer")
  }
}

// Module computation.
extension Driver {
  /// Compute the base name of the given path without an extension.
  private static func baseNameWithoutExtension(_ path: String) -> String {
    var hasExtension = false
    return baseNameWithoutExtension(path, hasExtension: &hasExtension)
  }

  /// Compute the base name of the given path without an extension.
  private static func baseNameWithoutExtension(_ path: String, hasExtension: inout Bool) -> String {
    if let absolute = try? AbsolutePath(validating: path) {
      hasExtension = absolute.extension != nil
      return absolute.basenameWithoutExt
    }

    if let relative = try? RelativePath(validating: path) {
      hasExtension = relative.extension != nil
      return relative.basenameWithoutExt
    }

    hasExtension = false
    return ""
  }

  /// Determine how the module will be emitted and the name of the module.
  private static func computeModuleInfo(
    _ parsedOptions: inout ParsedOptions,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    linkerOutputType: LinkOutputType?,
    debugInfoLevel: DebugInfo.Level?,
    diagnosticsEngine: DiagnosticsEngine,
    workingDirectory: AbsolutePath?
  ) throws -> ModuleOutputInfo {
    // Figure out what kind of module we will output.
    enum ModuleOutputKind {
      case topLevel
      case auxiliary
    }

    var moduleOutputKind: ModuleOutputKind?
    if parsedOptions.hasArgument(.emitModule, .emitModulePath) {
      // The user has requested a module, so generate one and treat it as
      // top-level output.
      moduleOutputKind = .topLevel
    } else if (debugInfoLevel?.requiresModule ?? false) && linkerOutputType != nil {
      // An option has been passed which requires a module, but the user hasn't
      // requested one. Generate a module, but treat it as an intermediate output.
      moduleOutputKind = .auxiliary
    } else if parsedOptions.hasArgument(.emitObjcHeader, .emitObjcHeaderPath,
                                        .emitModuleInterface, .emitModuleInterfacePath,
                                        .emitPrivateModuleInterfacePath, .emitPackageModuleInterfacePath) {
      // An option has been passed which requires whole-module knowledge, but we
      // don't have that. Generate a module, but treat it as an intermediate
      // output.
      moduleOutputKind = .auxiliary
    } else {
      // No options require a module, so don't generate one.
      moduleOutputKind = nil
    }

    // The REPL and immediate mode do not support module output
    if moduleOutputKind != nil && (compilerMode == .repl || compilerMode == .immediate || compilerMode == .intro) {
      diagnosticsEngine.emit(.error_mode_cannot_emit_module)
      moduleOutputKind = nil
    }

    // Determine the name of the module.
    var moduleName: String
    var moduleNameIsFallback = false
    if let arg = parsedOptions.getLastArgument(.moduleName) {
      moduleName = arg.asSingle
    } else if compilerMode == .repl || compilerMode == .intro {
      // TODO: Remove the `.intro` check once the REPL no longer launches
      // by default.
      // REPL mode should always use the REPL module.
      moduleName = "REPL"
    } else if let outputArg = parsedOptions.getLastArgument(.o) {
      var hasExtension = false
      var rawModuleName = baseNameWithoutExtension(outputArg.asSingle, hasExtension: &hasExtension)
      if (linkerOutputType == .dynamicLibrary || linkerOutputType == .staticLibrary) &&
        hasExtension && rawModuleName.starts(with: "lib") {
        // Chop off a "lib" prefix if we're building a library.
        rawModuleName = String(rawModuleName.dropFirst(3))
      }

      moduleName = rawModuleName
    } else if parsedOptions.allInputs.count == 1 {
      moduleName = baseNameWithoutExtension(parsedOptions.allInputs.first!)
    } else {
      // This value will fail the isSwiftIdentifier test below.
      moduleName = ""
    }

    func fallbackOrDiagnose(_ error: Diagnostic.Message) {
      moduleNameIsFallback = true
      if compilerOutputType == nil || !parsedOptions.hasArgument(.moduleName) {
        moduleName = "main"
      } else {
        diagnosticsEngine.emit(error)
        moduleName = "__bad__"
      }
    }

    if !moduleName.sd_isSwiftIdentifier {
      fallbackOrDiagnose(.error_bad_module_name(moduleName: moduleName, explicitModuleName: parsedOptions.contains(.moduleName)))
    } else if moduleName == "Swift" && !parsedOptions.contains(.parseStdlib) {
      fallbackOrDiagnose(.error_stdlib_module_name(moduleName: moduleName, explicitModuleName: parsedOptions.contains(.moduleName)))
    }

    // Retrieve and validate module aliases if passed in
    let moduleAliases = moduleAliasesFromInput(parsedOptions.arguments(for: [.moduleAlias]), with: moduleName, onError: diagnosticsEngine)

    // If we're not emitting a module, we're done.
    if moduleOutputKind == nil {
      return ModuleOutputInfo(output: nil, name: moduleName, nameIsFallback: moduleNameIsFallback, aliases: moduleAliases)
    }

    // Determine the module file to output.
    var moduleOutputPath: VirtualPath

    // FIXME: Look in the output file map. It looks like it is weirdly
    // anchored to the first input?
    if let modulePathArg = parsedOptions.getLastArgument(.emitModulePath) {
      // The module path was specified.
      moduleOutputPath = try VirtualPath(path: modulePathArg.asSingle)
    } else if moduleOutputKind == .topLevel {
      // FIXME: Logic to infer from primary outputs, etc.
      let moduleFilename = moduleName.appendingFileTypeExtension(.swiftModule)
      if let outputArg = parsedOptions.getLastArgument(.o)?.asSingle, compilerOutputType == .swiftModule {
        // If the module is the primary output, match -o exactly if present.
        moduleOutputPath = try .init(path: outputArg)
      } else if let outputArg = parsedOptions.getLastArgument(.o)?.asSingle, let lastSeparatorIndex = outputArg.lastIndex(of: "/") {
        // Put the module next to the top-level output.
        moduleOutputPath = try .init(path: outputArg[outputArg.startIndex...lastSeparatorIndex] + moduleFilename)
      } else {
        moduleOutputPath = try .init(path: moduleFilename)
      }
    } else {
      moduleOutputPath = try VirtualPath.createUniqueTemporaryFile(RelativePath(validating: moduleName.appendingFileTypeExtension(.swiftModule)))
    }

    // Use working directory if specified
    if let moduleRelative = moduleOutputPath.relativePath {
      moduleOutputPath = try Driver.useWorkingDirectory(moduleRelative, workingDirectory)
    }

    switch moduleOutputKind! {
    case .topLevel:
      return ModuleOutputInfo(output: .topLevel(moduleOutputPath.intern()), name: moduleName, nameIsFallback: moduleNameIsFallback, aliases: moduleAliases)
    case .auxiliary:
      return ModuleOutputInfo(output: .auxiliary(moduleOutputPath.intern()), name: moduleName, nameIsFallback: moduleNameIsFallback, aliases: moduleAliases)
    }
  }

  // Validate and return module aliases passed via -module-alias
  static func moduleAliasesFromInput(_ aliasArgs: [ParsedOption],
                                     with moduleName: String,
                                     onError diagnosticsEngine: DiagnosticsEngine) -> [String: String]? {
    var moduleAliases: [String: String]? = nil
    let validate = { (_ arg: String, allowModuleName: Bool) -> Bool in
      if !arg.sd_isSwiftIdentifier {
        diagnosticsEngine.emit(.error_bad_module_name(moduleName: arg, explicitModuleName: true))
        return false
      }
      if arg == "Swift" {
        diagnosticsEngine.emit(.error_stdlib_module_name(moduleName: arg, explicitModuleName: true))
        return false
      }
      if !allowModuleName, arg == moduleName {
        diagnosticsEngine.emit(.error_bad_module_alias(arg, moduleName: moduleName))
        return false
      }
      return true
    }

    var used = [""]
    for item in aliasArgs {
      let arg = item.argument.asSingle
      let pair = arg.components(separatedBy: "=")
      guard pair.count == 2 else {
        diagnosticsEngine.emit(.error_bad_module_alias(arg, moduleName: moduleName, formatted: false))
        continue
      }
      guard let lhs = pair.first, validate(lhs, false) else { continue }
      guard let rhs = pair.last, validate(rhs, true) else { continue }

      if moduleAliases == nil {
        moduleAliases = [String: String]()
      }
      if let _ = moduleAliases?[lhs] {
        diagnosticsEngine.emit(.error_bad_module_alias(lhs, moduleName: moduleName, isDuplicate: true))
        continue
      }
      if used.contains(rhs)  {
        diagnosticsEngine.emit(.error_bad_module_alias(rhs, moduleName: moduleName, isDuplicate: true))
        continue
      }
      moduleAliases?[lhs] = rhs
      used.append(lhs)
      used.append(rhs)
    }
    return moduleAliases
  }
}

// SDK computation.
extension Driver {
  /// Computes the path to the SDK.
  private static func computeSDKPath(
    _ parsedOptions: inout ParsedOptions,
    compilerMode: CompilerMode,
    toolchain: Toolchain,
    targetTriple: Triple?,
    fileSystem: FileSystem,
    diagnosticsEngine: DiagnosticsEngine,
    env: [String: String]
  ) -> VirtualPath? {
    var sdkPath: String?

    if let arg = parsedOptions.getLastArgument(.sdk) {
      sdkPath = arg.asSingle
    } else if let SDKROOT = env["SDKROOT"] {
      sdkPath = SDKROOT
    } else if compilerMode == .immediate || compilerMode == .repl {
      // In immediate modes, query the toolchain for a default SDK.
      sdkPath = try? toolchain.defaultSDKPath(targetTriple)?.pathString
    }

    // An empty string explicitly clears the SDK.
    if sdkPath == "" {
      sdkPath = nil
    }

    // Delete trailing /.
    sdkPath = sdkPath.map { $0.count > 1 && $0.last == "/" ? String($0.dropLast()) : $0 }

    // Validate the SDK if we found one.
    if let sdkPath = sdkPath {
      let path: AbsolutePath

      // FIXME: TSC should provide a better utility for this.
      if let absPath = try? AbsolutePath(validating: sdkPath) {
        path = absPath
      } else if let cwd = fileSystem.currentWorkingDirectory, let absPath = try? AbsolutePath(validating: sdkPath, relativeTo: cwd) {
        path = absPath
      } else {
        diagnosticsEngine.emit(.warning_no_such_sdk(sdkPath))
        return nil
      }

      if !fileSystem.exists(path) {
        diagnosticsEngine.emit(.warning_no_such_sdk(sdkPath))
      } else if !(targetTriple?.isWindows ?? (defaultToolchainType == WindowsToolchain.self)) {
        if isSDKTooOld(sdkPath: path, fileSystem: fileSystem,
                       diagnosticsEngine: diagnosticsEngine) {
          diagnosticsEngine.emit(.error_sdk_too_old(sdkPath))
          return nil
        }
      }

      return .absolute(path)
    }

    return nil
  }
}

// SDK checking: attempt to diagnose if the SDK we are pointed at is too old.
extension Driver {
  static func isSDKTooOld(sdkPath: AbsolutePath, fileSystem: FileSystem,
                          diagnosticsEngine: DiagnosticsEngine) -> Bool {
    let sdkInfoReadAttempt = DarwinToolchain.readSDKInfo(fileSystem, VirtualPath.absolute(sdkPath).intern())
    guard let sdkInfo = sdkInfoReadAttempt else {
      diagnosticsEngine.emit(.warning_no_sdksettings_json(sdkPath.pathString))
      return false
    }
    guard let sdkVersion = try? Version(string: sdkInfo.versionString, lenient: true) else {
      diagnosticsEngine.emit(.warning_fail_parse_sdk_ver(sdkInfo.versionString, sdkPath.pathString))
      return false
    }
    if sdkInfo.canonicalName.hasPrefix("macos") {
      return sdkVersion < Version(10, 15, 0)
    } else if sdkInfo.canonicalName.hasPrefix("iphone") ||
                sdkInfo.canonicalName.hasPrefix("appletv") {
      return sdkVersion < Version(13, 0, 0)
    } else if sdkInfo.canonicalName.hasPrefix("watch") {
      return sdkVersion < Version(6, 0, 0)
    } else {
      return false
    }
  }
}

// Imported Objective-C header.
extension Driver {
  /// Compute the path of the imported Objective-C header.
  static func computeImportedObjCHeader(
    _ parsedOptions: inout ParsedOptions,
    compilerMode: CompilerMode,
    diagnosticEngine: DiagnosticsEngine
  ) throws -> VirtualPath.Handle? {
    guard let objcHeaderPathArg = parsedOptions.getLastArgument(.importObjcHeader) else {
      return nil
    }

    // Check for conflicting options.
    if parsedOptions.hasArgument(.importUnderlyingModule) {
      diagnosticEngine.emit(.error_framework_bridging_header)
    }

    if parsedOptions.hasArgument(.emitModuleInterface, .emitModuleInterfacePath) {
      diagnosticEngine.emit(.error_bridging_header_module_interface)
    }

    return try VirtualPath.intern(path: objcHeaderPathArg.asSingle)
  }

  /// Compute the path of the generated bridging PCH for the Objective-C header.
  static func computeBridgingPrecompiledHeader(_ parsedOptions: inout ParsedOptions,
                                               compilerMode: CompilerMode,
                                               importedObjCHeader: VirtualPath.Handle?,
                                               outputFileMap: OutputFileMap?,
                                               contextHash: String?) -> VirtualPath.Handle? {
    guard compilerMode.supportsBridgingPCH,
      let input = importedObjCHeader,
      parsedOptions.hasFlag(positive: .enableBridgingPch, negative: .disableBridgingPch, default: true) else {
        return nil
    }

    if let outputPath = try? outputFileMap?.existingOutput(inputFile: input, outputType: .pch) {
      return outputPath
    }

    let pchFile : String
    let baseName = VirtualPath.lookup(input).basenameWithoutExt
    if let hash = contextHash {
      pchFile = baseName + "-" + hash + ".pch"
    } else {
      pchFile = baseName.appendingFileTypeExtension(.pch)
    }
    if let outputDirectory = parsedOptions.getLastArgument(.pchOutputDir)?.asSingle {
      return try? VirtualPath(path: outputDirectory).appending(component: pchFile).intern()
    } else {
      return try? VirtualPath.temporary(RelativePath(validating: pchFile)).intern()
    }
  }
}

extension Diagnostic.Message {
  static var error_framework_bridging_header: Diagnostic.Message {
    .error("using bridging headers with framework targets is unsupported")
  }

  static var error_bridging_header_module_interface: Diagnostic.Message {
    .error("using bridging headers with module interfaces is unsupported")
  }
  static func warning_cannot_assign_to_compilation_condition(name: String) -> Diagnostic.Message {
    .warning("conditional compilation flags do not have values in Swift; they are either present or absent (rather than '\(name)')")
  }
  static func warning_framework_search_path_includes_extension(path: String) -> Diagnostic.Message {
    .warning("framework search path ends in \".framework\"; add directory containing framework instead: \(path)")
  }
}

// MARK: Miscellaneous Argument Validation
extension Driver {
  static func validateWarningControlArgs(_ parsedOptions: inout ParsedOptions,
                                         diagnosticEngine: DiagnosticsEngine) {
    if parsedOptions.hasArgument(.suppressWarnings) &&
        parsedOptions.hasFlag(positive: .warningsAsErrors, negative: .noWarningsAsErrors, default: false) {
      diagnosticEngine.emit(.error(Error.conflictingOptions(.warningsAsErrors, .suppressWarnings)),
                            location: nil)
    }
  }

  static func validateDigesterArgs(_ parsedOptions: inout ParsedOptions,
                                   moduleOutputInfo: ModuleOutputInfo,
                                   digesterMode: DigesterMode,
                                   swiftInterfacePath: VirtualPath.Handle?,
                                   diagnosticEngine: DiagnosticsEngine) {
    if moduleOutputInfo.output?.isTopLevel != true {
      for arg in parsedOptions.arguments(for: .emitDigesterBaseline, .emitDigesterBaselinePath, .compareToBaselinePath) {
        diagnosticEngine.emit(.error(Error.baselineGenerationRequiresTopLevelModule(arg.option.spelling)),
                              location: nil)
      }
    }

    if parsedOptions.hasArgument(.serializeBreakingChangesPath) && !parsedOptions.hasArgument(.compareToBaselinePath) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother(Option.serializeBreakingChangesPath.spelling,
                                                               Option.compareToBaselinePath.spelling)),
                            location: nil)
    }
    if parsedOptions.hasArgument(.digesterBreakageAllowlistPath) && !parsedOptions.hasArgument(.compareToBaselinePath) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother(Option.digesterBreakageAllowlistPath.spelling,
                                                               Option.compareToBaselinePath.spelling)),
                            location: nil)
    }
    if digesterMode == .abi && !parsedOptions.hasArgument(.enableLibraryEvolution) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother("\(Option.digesterMode.spelling) abi",
                                                               Option.enableLibraryEvolution.spelling)),
                            location: nil)
    }
    if digesterMode == .abi && swiftInterfacePath == nil {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother("\(Option.digesterMode.spelling) abi",
                                                               Option.emitModuleInterface.spelling)),
                            location: nil)
    }
  }

  static func validateValidateClangModulesOnceOptions(_ parsedOptions: inout ParsedOptions,
                                                      diagnosticEngine: DiagnosticsEngine) {
    // '-validate-clang-modules-once' requires '-clang-build-session-file'
    if parsedOptions.hasArgument(.validateClangModulesOnce) &&
        !parsedOptions.hasArgument(.clangBuildSessionFile) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother(Option.validateClangModulesOnce.spelling,
                                                               Option.clangBuildSessionFile.spelling)),
                            location: nil)
    }
  }

  static func validateEmitDependencyGraphArgs(_ parsedOptions: inout ParsedOptions,
                                              diagnosticEngine: DiagnosticsEngine) {
    // '-print-explicit-dependency-graph' requires '-explicit-module-build'
    if parsedOptions.hasArgument(.printExplicitDependencyGraph) &&
        !parsedOptions.hasArgument(.driverExplicitModuleBuild) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother(Option.printExplicitDependencyGraph.spelling,
                                                               Option.driverExplicitModuleBuild.spelling)),
                            location: nil)
    }
    // '-explicit-dependency-graph-format=' requires '-print-explicit-dependency-graph'
    if parsedOptions.hasArgument(.explicitDependencyGraphFormat) &&
        !parsedOptions.hasArgument(.printExplicitDependencyGraph) {
      diagnosticEngine.emit(.error(Error.optionRequiresAnother(Option.explicitDependencyGraphFormat.spelling,
                                                               Option.printExplicitDependencyGraph.spelling)),
                            location: nil)
    }
    // '-explicit-dependency-graph-format=' only supports values 'json' and 'dot'
    if let formatArg = parsedOptions.getLastArgument(.explicitDependencyGraphFormat)?.asSingle {
      if formatArg != "json" && formatArg != "dot" {
        diagnosticEngine.emit(.error_unsupported_argument(argument: formatArg,
                                                          option: .explicitDependencyGraphFormat))
      }
    }
  }

  static func validateProfilingArgs(_ parsedOptions: inout ParsedOptions,
                                    fileSystem: FileSystem,
                                    workingDirectory: AbsolutePath?,
                                    diagnosticEngine: DiagnosticsEngine) {
    if parsedOptions.hasArgument(.profileGenerate) &&
        parsedOptions.hasArgument(.profileUse) {
      diagnosticEngine.emit(.error(Error.conflictingOptions(.profileGenerate, .profileUse)),
                            location: nil)
    }

    if let profileArgs = parsedOptions.getLastArgument(.profileUse)?.asMultiple,
       let workingDirectory = workingDirectory ?? fileSystem.currentWorkingDirectory {
      for profilingData in profileArgs {
        if let path = try? AbsolutePath(validating: profilingData,
                                          relativeTo: workingDirectory) {
          if !fileSystem.exists(path) {
            diagnosticEngine.emit(.error(Error.missingProfilingData(profilingData)),
                                  location: nil)
          }
        }
      }
    }
  }

  static func validateParseableOutputArgs(_ parsedOptions: inout ParsedOptions,
                                          diagnosticEngine: DiagnosticsEngine) {
    if parsedOptions.contains(.parseableOutput) &&
        parsedOptions.contains(.useFrontendParseableOutput) {
      diagnosticEngine.emit(.error(Error.conflictingOptions(.parseableOutput, .useFrontendParseableOutput)),
                            location: nil)
    }
  }

  static func validateCompilationConditionArgs(_ parsedOptions: inout ParsedOptions,
                                               diagnosticEngine: DiagnosticsEngine) {
    for arg in parsedOptions.arguments(for: .D).map(\.argument.asSingle) {
      if arg.contains("=") {
        diagnosticEngine.emit(.warning_cannot_assign_to_compilation_condition(name: arg))
      } else if arg.hasPrefix("-D") {
        diagnosticEngine.emit(.error(Error.conditionalCompilationFlagHasRedundantPrefix(arg)),
                              location: nil)
      } else if !arg.sd_isSwiftIdentifier {
        diagnosticEngine.emit(.error(Error.conditionalCompilationFlagIsNotValidIdentifier(arg)),
                              location: nil)
      }
    }
  }

  static func validateFrameworkSearchPathArgs(_ parsedOptions: inout ParsedOptions,
                                              diagnosticEngine: DiagnosticsEngine) {
    for arg in parsedOptions.arguments(for: .F, .Fsystem).map(\.argument.asSingle) {
      if arg.hasSuffix(".framework") || arg.hasSuffix(".framework/") {
        diagnosticEngine.emit(.warning_framework_search_path_includes_extension(path: arg))
      }
    }
  }

  private static func validateCoverageArgs(_ parsedOptions: inout ParsedOptions, diagnosticsEngine: DiagnosticsEngine) {
    for coveragePrefixMap in parsedOptions.arguments(for: .coveragePrefixMap) {
      let value = coveragePrefixMap.argument.asSingle
      let parts = value.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
      if parts.count != 2 {
        diagnosticsEngine.emit(.error_opt_invalid_mapping(option: coveragePrefixMap.option, value: value))
      }
    }
  }

  private static func validateLinkArgs(_ parsedOptions: inout ParsedOptions, diagnosticsEngine: DiagnosticsEngine) {
    if parsedOptions.hasArgument(.experimentalHermeticSealAtLink) {
      if parsedOptions.hasArgument(.enableLibraryEvolution) {
        diagnosticsEngine.emit(.error_hermetic_seal_cannot_have_library_evolution)
      }

      let lto = Self.ltoKind(&parsedOptions, diagnosticsEngine: diagnosticsEngine)
      if lto == nil {
        diagnosticsEngine.emit(.error_hermetic_seal_requires_lto)
      }
    }
  }

  private static func validateSanitizerAddressUseOdrIndicatorFlag(
    _ parsedOptions: inout ParsedOptions,
    diagnosticEngine: DiagnosticsEngine,
    addressSanitizerEnabled: Bool
  ) {
    if (parsedOptions.hasArgument(.sanitizeAddressUseOdrIndicator) && !addressSanitizerEnabled) {
      diagnosticEngine.emit(
        .warning_option_requires_sanitizer(currentOption: .sanitizeAddressUseOdrIndicator, currentOptionValue: "", sanitizerRequired: .address))
    }
  }

  private static func validateSanitizeStableABI(
          _ parsedOptions: inout ParsedOptions,
          diagnosticEngine: DiagnosticsEngine,
          addressSanitizerEnabled: Bool
          ) {
      if (parsedOptions.hasArgument(.sanitizeStableAbiEQ) && !addressSanitizerEnabled) {
          diagnosticEngine.emit(
                  .warning_option_requires_sanitizer(currentOption: .sanitizeStableAbiEQ, currentOptionValue: "", sanitizerRequired: .address))
      }
  }

  /// Validates the set of `-sanitize-recover={sanitizer}` arguments
  private static func validateSanitizerRecoverArgValues(
    _ parsedOptions: inout ParsedOptions,
    diagnosticEngine: DiagnosticsEngine,
    enabledSanitizers: Set<Sanitizer>
  ){
    let args = parsedOptions
      .filter { $0.option == .sanitizeRecoverEQ }
      .flatMap { $0.argument.asMultiple }

    // No sanitizer args found, we could return.
    if args.isEmpty {
      return
    }

    // Find the sanitizer kind.
    for arg in args {
      guard let sanitizer = Sanitizer(rawValue: arg) else {
        // Unrecognized sanitizer option
        diagnosticEngine.emit(
          .error_invalid_arg_value(arg: .sanitizeRecoverEQ, value: arg))
        continue
      }

      // only -sanitize-recover=address is supported
      if sanitizer != .address {
        diagnosticEngine.emit(
          .error_unsupported_argument(argument: arg, option: .sanitizeRecoverEQ))
        continue
      }

      if !enabledSanitizers.contains(sanitizer) {
        diagnosticEngine.emit(
          .warning_option_requires_sanitizer(currentOption: .sanitizeRecoverEQ, currentOptionValue: arg, sanitizerRequired: sanitizer))
      }
    }
  }

  private static func validateSanitizerCoverageArgs(_ parsedOptions: inout ParsedOptions,
                                                    anySanitizersEnabled: Bool,
                                                    diagnosticsEngine: DiagnosticsEngine) {
    var foundRequiredArg = false
    for arg in parsedOptions.arguments(for: .sanitizeCoverageEQ).flatMap(\.argument.asMultiple) {
      if ["func", "bb", "edge"].contains(arg) {
        foundRequiredArg = true
      } else if !["indirect-calls", "trace-bb", "trace-cmp", "8bit-counters", "trace-pc", "trace-pc-guard","pc-table","inline-8bit-counters"].contains(arg) {
        diagnosticsEngine.emit(.error_unsupported_argument(argument: arg, option: .sanitizeCoverageEQ))
      }

      if !foundRequiredArg {
        diagnosticsEngine.emit(.error_option_missing_required_argument(option: .sanitizeCoverageEQ,
                                                                       requiredArg: #""func", "bb", "edge""#))
      }
    }

    if parsedOptions.hasArgument(.sanitizeCoverageEQ) && !anySanitizersEnabled {
      diagnosticsEngine.emit(.error_option_requires_sanitizer(option: .sanitizeCoverageEQ))
    }
  }
}

extension Triple {
  @_spi(Testing) public func toolchainType(_ diagnosticsEngine: DiagnosticsEngine) throws -> Toolchain.Type {
    switch os {
    case .darwin, .macosx, .ios, .tvos, .watchos, .visionos:
      return DarwinToolchain.self
    case .linux:
      return GenericUnixToolchain.self
    case .freeBSD, .haiku, .openbsd:
      return GenericUnixToolchain.self
    case .wasi:
      return WebAssemblyToolchain.self
    case .win32:
      return WindowsToolchain.self
    case .noneOS:
        switch self.vendor {
        case .apple:
            return DarwinToolchain.self
        default:
            return GenericUnixToolchain.self
        }
    default:
      diagnosticsEngine.emit(.error_unknown_target(triple))
      throw Driver.ErrorDiagnostics.emitted
    }
  }
}

/// Toolchain computation.
extension Driver {
  #if canImport(Darwin)
  static let defaultToolchainType: Toolchain.Type = DarwinToolchain.self
  #elseif os(Windows)
  static let defaultToolchainType: Toolchain.Type = WindowsToolchain.self
  #else
  static let defaultToolchainType: Toolchain.Type = GenericUnixToolchain.self
  #endif

  static func computeHostTriple(
    _ parsedOptions: inout ParsedOptions,
    diagnosticsEngine: DiagnosticsEngine,
    toolchain: Toolchain,
    executor: DriverExecutor,
    fileSystem: FileSystem,
    workingDirectory: AbsolutePath?,
    swiftCompilerPrefixArgs: [String]) throws -> Triple {

    let frontendOverride = try FrontendOverride(&parsedOptions, diagnosticsEngine)
    frontendOverride.setUpForTargetInfo(toolchain)
    defer { frontendOverride.setUpForCompilation(toolchain) }
    return try Self.computeTargetInfo(target: nil, targetVariant: nil,
                                      swiftCompilerPrefixArgs: frontendOverride.prefixArgsForTargetInfo,
                                      toolchain: toolchain, fileSystem: fileSystem,
                                      workingDirectory: workingDirectory,
                                      diagnosticsEngine: diagnosticsEngine,
                                      executor: executor).target.triple
  }

  static func computeToolchain(
    _ parsedOptions: inout ParsedOptions,
    diagnosticsEngine: DiagnosticsEngine,
    compilerMode: CompilerMode,
    env: [String: String],
    executor: DriverExecutor,
    fileSystem: FileSystem,
    useStaticResourceDir: Bool,
    workingDirectory: AbsolutePath?,
    compilerExecutableDir: AbsolutePath?
  ) throws -> (Toolchain, FrontendTargetInfo, [String]) {
    let explicitTarget = (parsedOptions.getLastArgument(.target)?.asSingle)
      .map {
        Triple($0, normalizing: true)
      }
    let explicitTargetVariant = (parsedOptions.getLastArgument(.targetVariant)?.asSingle)
      .map {
        Triple($0, normalizing: true)
      }

    // Determine the resource directory.
    let resourceDirPath: VirtualPath?
    if let resourceDirArg = parsedOptions.getLastArgument(.resourceDir) {
      resourceDirPath = try VirtualPath(path: resourceDirArg.asSingle)
    } else {
      resourceDirPath = nil
    }

    let toolchainType = try explicitTarget?.toolchainType(diagnosticsEngine) ??
          defaultToolchainType
    // Find tools directory and pass it down to the toolchain
    var toolDir: AbsolutePath?
    if let td = parsedOptions.getLastArgument(.toolsDirectory) {
      toolDir = try AbsolutePath(validating: td.asSingle)
    }
    let toolchain = toolchainType.init(env: env, executor: executor,
                                       fileSystem: fileSystem,
                                       compilerExecutableDir: compilerExecutableDir,
                                       toolDirectory: toolDir)

    let frontendOverride = try FrontendOverride(&parsedOptions, diagnosticsEngine)
    frontendOverride.setUpForTargetInfo(toolchain)
    defer { frontendOverride.setUpForCompilation(toolchain) }
    // Find the SDK, if any.
    let sdkPath: VirtualPath? = Self.computeSDKPath(
      &parsedOptions, compilerMode: compilerMode, toolchain: toolchain,
      targetTriple: explicitTarget, fileSystem: fileSystem,
      diagnosticsEngine: diagnosticsEngine, env: env)


    // Query the frontend for target information.
    do {
      var info: FrontendTargetInfo =
        try Self.computeTargetInfo(target: explicitTarget, targetVariant: explicitTargetVariant,
                                   sdkPath: sdkPath, resourceDirPath: resourceDirPath,
                                   runtimeCompatibilityVersion:
                                     parsedOptions.getLastArgument(.runtimeCompatibilityVersion)?.asSingle,
                                   useStaticResourceDir: useStaticResourceDir,
                                   swiftCompilerPrefixArgs: frontendOverride.prefixArgsForTargetInfo,
                                   toolchain: toolchain, fileSystem: fileSystem,
                                   workingDirectory: workingDirectory,
                                   diagnosticsEngine: diagnosticsEngine,
                                   executor: executor)

      // Parse the runtime compatibility version. If present, it will override
      // what is reported by the frontend.
      if let versionString =
          parsedOptions.getLastArgument(.runtimeCompatibilityVersion)?.asSingle {
        if let version = SwiftVersion(string: versionString) {
          info.target.swiftRuntimeCompatibilityVersion = version
          info.targetVariant?.swiftRuntimeCompatibilityVersion = version
        } else if (versionString != "none") {
          // "none" was accepted by the old driver, diagnose other values.
          diagnosticsEngine.emit(
            .error_invalid_arg_value(
              arg: .runtimeCompatibilityVersion, value: versionString))
        }
      }

      // Check if the simulator environment was inferred for backwards compatibility.
      if let explicitTarget = explicitTarget,
         explicitTarget.environment != .simulator && info.target.triple.environment == .simulator {
        diagnosticsEngine.emit(.warning_inferring_simulator_target(originalTriple: explicitTarget,
                                                                   inferredTriple: info.target.triple))
      }
      return (toolchain, info, frontendOverride.prefixArgs)
    } catch let JobExecutionError.decodingError(decodingError,
                                                dataToDecode,
                                                processResult) {
      let stringToDecode = String(data: dataToDecode, encoding: .utf8)
      let errorDesc: String
      switch decodingError {
        case let .typeMismatch(type, context):
          errorDesc = "type mismatch: \(type), path: \(context.codingPath)"
        case let .valueNotFound(type, context):
          errorDesc = "value missing: \(type), path: \(context.codingPath)"
        case let .keyNotFound(key, context):
          errorDesc = "key missing: \(key), path: \(context.codingPath)"
       case let .dataCorrupted(context):
          errorDesc = "data corrupted at path: \(context.codingPath)"
        @unknown default:
          errorDesc = "unknown decoding error"
      }
      throw Error.unableToDecodeFrontendTargetInfo(
        stringToDecode,
        processResult.arguments,
        errorDesc)
    } catch let JobExecutionError.jobFailedWithNonzeroExitCode(returnCode, stdout) {
      throw Error.failedToRunFrontendToRetrieveTargetInfo(returnCode, stdout)
    } catch JobExecutionError.failedToReadJobOutput {
      throw Error.unableToReadFrontendTargetInfo
    } catch {
      throw Error.failedToRetrieveFrontendTargetInfo
    }
  }

  internal struct FrontendOverride {
    private let overridePath: AbsolutePath?
    let prefixArgs: [String]

    init() {
      overridePath = nil
      prefixArgs = []
    }

    init(_ parsedOptions: inout ParsedOptions, _ diagnosticsEngine: DiagnosticsEngine) throws {
      guard let arg = parsedOptions.getLastArgument(.driverUseFrontendPath)
      else {
        self = Self()
        return
      }
      let frontendCommandLine = arg.asSingle.split(separator: ";").map { String($0) }
      guard let pathString = frontendCommandLine.first else {
        diagnosticsEngine.emit(.error_no_swift_frontend)
        self = Self()
        return
      }
      overridePath = try AbsolutePath(validating: pathString)
      prefixArgs = frontendCommandLine.dropFirst().map {String($0)}
    }

    var appliesToFetchingTargetInfo: Bool {
      guard let path = overridePath else { return true }
      // lowercased() to handle Python
      // starts(with:) to handle both python3 and point versions (Ex: python3.9). Also future versions (Ex: Python4).
      return !path.basename.lowercased().starts(with: "python")
    }
    func setUpForTargetInfo(_ toolchain: Toolchain) {
      if !appliesToFetchingTargetInfo {
        toolchain.clearKnownToolPath(.swiftCompiler)
      }
    }
    var prefixArgsForTargetInfo: [String] {
      appliesToFetchingTargetInfo ? prefixArgs : []
    }
    func setUpForCompilation(_ toolchain: Toolchain) {
      if let path = overridePath {
        toolchain.overrideToolPath(.swiftCompiler, path: path)
      }
    }
  }
}

// Supplementary outputs.
extension Driver {
  /// Determine the output path for a supplementary output.
  static func computeSupplementaryOutputPath(
    _ parsedOptions: inout ParsedOptions,
    type: FileType,
    isOutputOptions: [Option],
    outputPath: Option,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    emitModuleSeparately: Bool,
    outputFileMap: OutputFileMap?,
    moduleName: String
  ) throws -> VirtualPath.Handle? {
    // If there is an explicit argument for the output path, use that
    if let outputPathArg = parsedOptions.getLastArgument(outputPath) {
      for isOutput in isOutputOptions {
        // Consume the isOutput argument
        _ = parsedOptions.hasArgument(isOutput)
      }
      return try VirtualPath.intern(path: outputPathArg.asSingle)
    }

    // If no output option was provided, don't produce this output at all.
    guard isOutputOptions.contains(where: { parsedOptions.hasArgument($0) }) else {
      return nil
    }

    // If this is a single-file compile and there is an entry in the
    // output file map, use that.
    if compilerMode.isSingleCompilation,
        let singleOutputPath = try outputFileMap?.existingOutputForSingleInput(
            outputType: type) {
      return singleOutputPath
    }

    // The driver lacks a compilerMode for *only* emitting a Swift module, but if the
    // primary output type is a .swiftmodule and we are using the emit-module-separately
    // flow, then also consider single output paths specified in the output file-map.
    if compilerOutputType == .swiftModule && emitModuleSeparately,
       let singleOutputPath = try outputFileMap?.existingOutputForSingleInput(
           outputType: type) {
      return singleOutputPath
    }

    // Emit-module serialized diagnostics are always specified as a single-output
    // file
    if type == .emitModuleDiagnostics,
       let singleOutputPath = try outputFileMap?.existingOutputForSingleInput(
           outputType: type) {
      return singleOutputPath
    }

    // Emit-module discovered dependencies are always specified as a single-output
    // file
    if type == .emitModuleDependencies,
       let path = try outputFileMap?.existingOutputForSingleInput(outputType: type) {
      return path
    }

    // If there is an output argument, derive the name from there.
    if let outputPathArg = parsedOptions.getLastArgument(.o) {
      let path = try VirtualPath(path: outputPathArg.asSingle)

      // If the compiler output is of this type, use the argument directly.
      if type == compilerOutputType {
        return path.intern()
      }

      return path
        .parentDirectory
        .appending(component: "\(moduleName).\(type.rawValue)")
        .intern()
    }

    // If an explicit path is not provided by the output file map, attempt to
    // synthesize a path from the master swift dependency path.  This is
    // important as we may otherwise emit this file at the location where the
    // driver was invoked, which is normally the root of the package.
    if let path = try outputFileMap?.existingOutputForSingleInput(outputType: .swiftDeps) {
      return VirtualPath.lookup(path)
                  .parentDirectory
                  .appending(component: "\(moduleName).\(type.rawValue)")
                  .intern()
    }
    return try VirtualPath.intern(path: moduleName.appendingFileTypeExtension(type))
  }

  /// Determine if the build system has created a Project/ directory for auxiliary outputs.
  static func computeProjectDirectoryPath(moduleOutputPath: VirtualPath.Handle?,
                                          fileSystem: FileSystem) -> VirtualPath.Handle? {
    let potentialProjectDirectory = moduleOutputPath
      .map(VirtualPath.lookup)?
      .parentDirectory
      .appending(component: "Project")
      .absolutePath
    guard let projectDirectory = potentialProjectDirectory, fileSystem.exists(projectDirectory) else {
      return nil
    }
    return VirtualPath.absolute(projectDirectory).intern()
  }

  /// Determine the output path for a module documentation.
  static func computeModuleDocOutputPath(
    _ parsedOptions: inout ParsedOptions,
    moduleOutputPath: VirtualPath.Handle?,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    outputFileMap: OutputFileMap?,
    moduleName: String
  ) throws -> VirtualPath.Handle? {
    return try computeModuleAuxiliaryOutputPath(&parsedOptions,
                                                moduleOutputPath: moduleOutputPath,
                                                type: .swiftDocumentation,
                                                isOutput: .emitModuleDoc,
                                                outputPath: .emitModuleDocPath,
                                                compilerOutputType: compilerOutputType,
                                                compilerMode: compilerMode,
                                                outputFileMap: outputFileMap,
                                                moduleName: moduleName)
  }

  /// Determine the output path for a module source info.
  static func computeModuleSourceInfoOutputPath(
    _ parsedOptions: inout ParsedOptions,
    moduleOutputPath: VirtualPath.Handle?,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    outputFileMap: OutputFileMap?,
    moduleName: String,
    projectDirectory: VirtualPath.Handle?
  ) throws -> VirtualPath.Handle? {
    guard !parsedOptions.hasArgument(.avoidEmitModuleSourceInfo) else { return nil }
    return try computeModuleAuxiliaryOutputPath(&parsedOptions,
                                                moduleOutputPath: moduleOutputPath,
                                                type: .swiftSourceInfoFile,
                                                isOutput: .emitModuleSourceInfo,
                                                outputPath: .emitModuleSourceInfoPath,
                                                compilerOutputType: compilerOutputType,
                                                compilerMode: compilerMode,
                                                outputFileMap: outputFileMap,
                                                moduleName: moduleName,
                                                projectDirectory: projectDirectory)
  }

  static func computeDigesterBaselineOutputPath(
    _ parsedOptions: inout ParsedOptions,
    moduleOutputPath: VirtualPath.Handle?,
    mode: DigesterMode,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    outputFileMap: OutputFileMap?,
    moduleName: String,
    projectDirectory: VirtualPath.Handle?
  ) throws -> VirtualPath.Handle? {
    // Only emit a baseline if at least of the arguments was provided.
    guard parsedOptions.hasArgument(.emitDigesterBaseline, .emitDigesterBaselinePath) else { return nil }
    return try computeModuleAuxiliaryOutputPath(&parsedOptions,
                                                moduleOutputPath: moduleOutputPath,
                                                type: mode.baselineFileType,
                                                isOutput: .emitDigesterBaseline,
                                                outputPath: .emitDigesterBaselinePath,
                                                compilerOutputType: compilerOutputType,
                                                compilerMode: compilerMode,
                                                outputFileMap: outputFileMap,
                                                moduleName: moduleName,
                                                projectDirectory: projectDirectory)
  }



  /// Determine the output path for a module auxiliary output.
  static func computeModuleAuxiliaryOutputPath(
    _ parsedOptions: inout ParsedOptions,
    moduleOutputPath: VirtualPath.Handle?,
    type: FileType,
    isOutput: Option?,
    outputPath: Option,
    compilerOutputType: FileType?,
    compilerMode: CompilerMode,
    outputFileMap: OutputFileMap?,
    moduleName: String,
    projectDirectory: VirtualPath.Handle? = nil
  ) throws -> VirtualPath.Handle? {
    // If there is an explicit argument for the output path, use that
    if let outputPathArg = parsedOptions.getLastArgument(outputPath) {
      // Consume the isOutput argument
      if let isOutput = isOutput {
        _ = parsedOptions.hasArgument(isOutput)
      }
      return try VirtualPath.intern(path: outputPathArg.asSingle)
    }

    // If this is a single-file compile and there is an entry in the
    // output file map, use that.
    if compilerMode.isSingleCompilation,
        let singleOutputPath = try outputFileMap?.existingOutputForSingleInput(
          outputType: type) {
      return singleOutputPath
    }

    // If there's a known module output path, put the file next to it.
    if let moduleOutputPath = moduleOutputPath {
      if let isOutput = isOutput {
        _ = parsedOptions.hasArgument(isOutput)
      }

      let parentPath: VirtualPath
      if let projectDirectory = projectDirectory {
        // If the build system has created a Project dir for us to include the file, use it.
        parentPath = VirtualPath.lookup(projectDirectory)
      } else {
        parentPath = VirtualPath.lookup(moduleOutputPath).parentDirectory
      }

      return try parentPath
        .appending(component: VirtualPath.lookup(moduleOutputPath).basename)
        .replacingExtension(with: type)
        .intern()
    }

    // If the output option was not provided, don't produce this output at all.
    guard let isOutput = isOutput, parsedOptions.hasArgument(isOutput) else {
      return nil
    }

    return try VirtualPath.intern(path: moduleName.appendingFileTypeExtension(type))
  }
}

// CAS and Caching.
extension Driver {
  mutating func getCASPluginPath() throws -> AbsolutePath? {
    if let pluginPath = parsedOptions.getLastArgument(.casPluginPath)?.asSingle {
      return try AbsolutePath(validating: pluginPath.description)
    }
    return try toolchain.lookupToolchainCASPluginLib()
  }

  mutating func getOnDiskCASPath() throws -> AbsolutePath? {
    if let casPathOpt = parsedOptions.getLastArgument(.casPath)?.asSingle {
      return try AbsolutePath(validating: casPathOpt.description)
    }
    return nil;
  }

  mutating func getCASPluginOptions() throws -> [(String, String)] {
    var options : [(String, String)] = []
    for opt in parsedOptions.arguments(for: .casPluginOption) {
      let pluginArg = opt.argument.asSingle.split(separator: "=", maxSplits: 1)
      if pluginArg.count != 2 {
        throw Error.invalidArgumentValue(Option.casPluginOption.spelling, opt.argument.asSingle)
      }
      options.append((String(pluginArg[0]), String(pluginArg[1])))
    }
    return options
  }

  static func computeScanningPrefixMapper(_ parsedOptions: inout ParsedOptions) throws -> [AbsolutePath: AbsolutePath] {
    var mapping: [AbsolutePath: AbsolutePath] = [:]
    for opt in parsedOptions.arguments(for: .scannerPrefixMap) {
      let pluginArg = opt.argument.asSingle.split(separator: "=", maxSplits: 1)
      if pluginArg.count != 2 {
        throw Error.invalidArgumentValue(Option.scannerPrefixMap.spelling, opt.argument.asSingle)
      }
      let key = try AbsolutePath(validating: String(pluginArg[0]))
      let value = try AbsolutePath(validating: String(pluginArg[1]))
      mapping[key] = value
    }
    return mapping
  }
}