File: BuildSystem.cpp

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 (4182 lines) | stat: -rw-r--r-- 143,738 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
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
//===-- BuildSystem.cpp ---------------------------------------------------===//
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/BuildSystem/BuildSystem.h"
#include "llbuild/BuildSystem/BuildSystemExtensions.h"
#include "llbuild/BuildSystem/BuildSystemFrontend.h"
#include "llbuild/BuildSystem/BuildSystemHandlers.h"

#include "llbuild/Basic/CrossPlatformCompatibility.h"
#include "llbuild/Basic/ExecutionQueue.h"
#include "llbuild/Basic/FileInfo.h"
#include "llbuild/Basic/FileSystem.h"
#include "llbuild/Basic/Hashing.h"
#include "llbuild/Basic/JSON.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/Basic/PlatformUtility.h"
#include "llbuild/Basic/ShellUtility.h"
#include "llbuild/BuildSystem/BuildFile.h"
#include "llbuild/BuildSystem/BuildKey.h"
#include "llbuild/BuildSystem/BuildNode.h"
#include "llbuild/BuildSystem/BuildValue.h"
#include "llbuild/BuildSystem/ExternalCommand.h"
#include "llbuild/BuildSystem/ShellCommand.h"
#include "llbuild/BuildSystem/Tool.h"
#include "llbuild/Core/BuildDB.h"
#include "llbuild/Core/BuildEngine.h"
#include "llbuild/Core/DependencyInfoParser.h"
#include "llbuild/Core/MakefileDepsParser.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

#include <memory>
#include <mutex>
#include <set>
#include <sstream>

#ifdef _WIN32
#include <Shlwapi.h>
#else
#include <limits.h>
#include <fnmatch.h>
#include <unistd.h>
#endif

using namespace llvm;
using namespace llbuild;
using namespace llbuild::basic;
using namespace llbuild::core;
using namespace llbuild::buildsystem;

/// The extension manager singleton.
static BuildSystemExtensionManager extensionManager{};

BuildSystemDelegate::~BuildSystemDelegate() {}

#pragma mark - BuildSystem implementation

namespace {

class BuildSystemImpl;

/// The delegate used to load the build file for use by a build system.
class BuildSystemFileDelegate : public BuildFileDelegate {
  BuildSystemImpl& system;

  /// FIXME: It would be nice to have a StringSet.
  llvm::StringMap<bool> internedStrings;

public:
  BuildSystemFileDelegate(BuildSystemImpl& system)
      : BuildFileDelegate(), system(system) {}

  BuildSystemDelegate& getSystemDelegate();

  /// @name Delegate Implementation
  /// @{

  virtual StringRef getInternedString(StringRef value) override {
    auto entry = internedStrings.insert(std::make_pair(value, true));
    return entry.first->getKey();
  }

  virtual FileSystem& getFileSystem() override;
  
  virtual void setFileContentsBeingParsed(StringRef buffer) override;
  
  virtual void error(StringRef filename,
                     const BuildFileToken& at,
                     const Twine& message) override;

  virtual void cannotLoadDueToMultipleProducers(Node *output,
                                                std::vector<Command*> commands) override;

  virtual bool configureClient(const ConfigureContext&, StringRef name,
                               uint32_t version,
                               const property_list_type& properties) override;

  virtual std::unique_ptr<Tool> lookupTool(StringRef name) override;

  virtual void loadedTarget(StringRef name,
                            const Target& target) override;

  virtual void loadedDefaultTarget(StringRef target) override;

  virtual void loadedCommand(StringRef name,
                             const Command& target) override;

  virtual std::unique_ptr<Node> lookupNode(StringRef name,
                                           bool isImplicit=false) override;

  /// @}
};

/// The delegate used to build a loaded build file.
class BuildSystemEngineDelegate : public BuildEngineDelegate {
  BuildSystemImpl& system;
  
  // FIXME: This is an inefficent map, the string is duplicated.
  std::unordered_map<std::string, std::unique_ptr<BuildNode>> dynamicNodes;

  // FIXME: This is an inefficent map, the string is duplicated.
  std::unordered_map<std::string, std::unique_ptr<StatNode>> dynamicStatNodes;

  /// The custom tasks which are owned by the build system.
  std::vector<std::unique_ptr<Command>> customTasks;

  const BuildDescription& getBuildDescription() const;

  virtual std::unique_ptr<Rule> lookupRule(const KeyType& keyData) override;
  virtual void determinedRuleNeedsToRun(Rule* ruleNeedingToRun, Rule::RunReason reason, Rule* inputRule) override;
  virtual bool shouldResolveCycle(const std::vector<Rule*>& items,
                                  Rule* candidateRule,
                                  Rule::CycleAction action) override;
  virtual void cycleDetected(const std::vector<Rule*>& items) override;
  virtual void error(const Twine& message) override;

  std::unique_ptr<basic::ExecutionQueue> createExecutionQueue() override;

public:
  BuildSystemEngineDelegate(BuildSystemImpl& system) : system(system) {}

  BuildSystemImpl& getBuildSystem() {
    return system;
  }
};

class BuildSystemImpl {
public:
  /// The internal schema version.
  ///
  /// Version History:
  /// * 9: Added filters to Directory* BuildKeys
  /// * 8: Added DirectoryTreeStructureSignature to BuildValue
  /// * 7: Added StaleFileRemoval to BuildValue
  /// * 6: Added DirectoryContents to BuildKey
  /// * 5: Switch BuildValue to be BinaryCoding based
  /// * 4: Pre-history
  static const uint32_t internalSchemaVersion = 9;

private:
  BuildSystem& buildSystem;

  /// The delegate the BuildSystem was configured with.
  BuildSystemDelegate& delegate;

  /// The file system used by the build system
  std::unique_ptr<basic::FileSystem> fileSystem;

  /// The name of the main input file.
  std::string mainFilename;

  /// The delegate used for the loading the build file.
  BuildSystemFileDelegate fileDelegate;

  /// The build description, once loaded.
  std::unique_ptr<BuildDescription> buildDescription;

  /// The delegate used for building the file contents.
  BuildSystemEngineDelegate engineDelegate;

  /// The build engine.
  BuildEngine buildEngine;

  /// Flag indicating if the build has been aborted.
  bool buildWasAborted = false;

  /// Cache of instantiated shell command handlers.
  llvm::StringMap<std::unique_ptr<ShellCommandHandler>> shellHandlers;

public:
  ShellCommandHandler*
  resolveShellCommandHandler(ShellCommand* command) {
    // Ignore empty commands.
    if (command->getArgs().empty()) { return nullptr; }

    // Check the cache.
    auto toolPath = command->getArgs()[0];
    auto it = shellHandlers.find(toolPath);
    if (it != shellHandlers.end()) return it->second.get();

    // If missing, check for an extension which can provide it.
    auto* extension = extensionManager.lookupByCommandPath(toolPath);
    if (!extension) {
      shellHandlers[toolPath] = nullptr; // Negative caching
      return nullptr;
    }

    auto handler = extension->createShellCommandHandler(toolPath);
    auto *result = handler.get();
    shellHandlers[toolPath] = std::move(handler);

    return result;
  }
  
  /// @}

public:
  BuildSystemImpl(class BuildSystem& buildSystem,
                  BuildSystemDelegate& delegate,
                  std::unique_ptr<basic::FileSystem> fileSystem)
      : buildSystem(buildSystem), delegate(delegate),
        fileSystem(std::move(fileSystem)),
        fileDelegate(*this), engineDelegate(*this), buildEngine(engineDelegate) {}

  BuildSystem& getBuildSystem() {
    return buildSystem;
  }

  BuildSystemDelegate& getDelegate() {
    return delegate;
  }

  basic::FileSystem& getFileSystem() {
    return *fileSystem;
  }

  // FIXME: We should eliminate this, it isn't well formed when loading
  // descriptions not from a file. We currently only use that for unit testing,
  // though.
  StringRef getMainFilename() {
    return mainFilename;
  }

  const BuildDescription& getBuildDescription() const {
    assert(buildDescription);
    return *buildDescription;
  }

  void error(StringRef filename, const Twine& message) {
    getDelegate().error(filename, {}, message);
  }

  void error(StringRef filename, const BuildSystemDelegate::Token& at,
             const Twine& message) {
    getDelegate().error(filename, at, message);
  }

  std::unique_ptr<BuildNode> lookupNode(StringRef name,
                                        bool isImplicit);

  uint32_t getMergedSchemaVersion() {
    // FIXME: Find a cleaner strategy for merging the internal schema version
    // with that from the client.
    auto clientVersion = delegate.getVersion();
    assert(clientVersion <= (1 << 16) && "unsupported client version");
    return internalSchemaVersion + (clientVersion << 16);
  }

  void configureFileSystem(int mode) {
    if (mode == 1) {
      std::unique_ptr<basic::FileSystem> newFS(
          new DeviceAgnosticFileSystem(std::move(fileSystem)));
      fileSystem.swap(newFS);
    } else if (mode == 2) {
      std::unique_ptr<basic::FileSystem> newFS(
          new ChecksumOnlyFileSystem(std::move(fileSystem)));
      fileSystem.swap(newFS);
    }
  }
  
  /// @name Client API
  /// @{

  bool loadDescription(StringRef filename) {
    this->mainFilename = filename;

    auto description = BuildFile(filename, fileDelegate).load();
    if (!description) {
      error(getMainFilename(), "unable to load build file");
      return false;
    }

    buildDescription = std::move(description);
    return true;
  }

  void loadDescription(std::unique_ptr<BuildDescription> description) {
    buildDescription = std::move(description);
  }

  bool attachDB(StringRef filename, std::string* error_out) {
    // FIXME: How do we pass the client schema version here, if we haven't
    // loaded the file yet.
    std::unique_ptr<core::BuildDB> db(
                                      core::createSQLiteBuildDB(filename, getMergedSchemaVersion(), /* recreateUnmatchedVersion = */ true, error_out));
    if (!db)
      return false;

    return buildEngine.attachDB(std::move(db), error_out);
  }

  bool enableTracing(StringRef filename, std::string* error_out) {
    return buildEngine.enableTracing(filename, error_out);
  }

  /// Build the given key, and return the result and an indication of success.
  llvm::Optional<BuildValue> build(BuildKey key);
  
  bool build(StringRef target);

  void setBuildWasAborted(bool value) {
    buildWasAborted = value;
  }

  void resetForBuild() {
    buildEngine.resetForBuild();
  }

  /// Cancel the running build.
  void cancel() {
    buildEngine.cancelBuild();
  }

  /// Check if the build has been cancelled.
  bool isCancelled() {
    return buildEngine.isCancelled();
  }

  void addCancellationDelegate(CancellationDelegate* del) {
    buildEngine.addCancellationDelegate(del);
  }

  void removeCancellationDelegate(CancellationDelegate* del) {
    buildEngine.removeCancellationDelegate(del);
  }

  /// @}
};

#pragma mark - BuildSystem engine integration

std::unique_ptr<basic::ExecutionQueue> BuildSystemEngineDelegate::createExecutionQueue() {
  return system.getDelegate().createExecutionQueue();
}


#pragma mark - Task implementations

static BuildSystemImpl& getBuildSystem(TaskInterface ti) {
  return static_cast<BuildSystemEngineDelegate*>(ti.delegate())->getBuildSystem();
}

static BuildSystemImpl& getBuildSystem(BuildEngine& engine) {
  return static_cast<BuildSystemEngineDelegate*>(engine.getDelegate())->getBuildSystem();
}


FileSystem& BuildSystemFileDelegate::getFileSystem() {
  return system.getFileSystem();
}

  
/// This is the task used to "build" a target, it translates between the request
/// for building a target key and the requests for all of its nodes.
class TargetTask : public Task {
  Target& target;
  
  // Build specific data.
  //
  // FIXME: We should probably factor this out somewhere else, so we can enforce
  // it is never used when initialized incorrectly.

  /// If there are any elements, the command had missing input nodes (this implies
  /// ShouldSkip is true).
  SmallPtrSet<Node*, 1> missingInputNodes;

  virtual void start(TaskInterface ti) override {
    // Request all of the necessary system tasks.
    unsigned id = 0;
    for (auto it = target.getNodes().begin(),
           ie = target.getNodes().end(); it != ie; ++it, ++id) {
      ti.request(BuildKey::makeNode(*it).toData(), id);
    }
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
    // Do nothing.
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& valueData) override {
    // Do nothing.
    auto value = BuildValue::fromData(valueData);

    if (value.isMissingInput()) {
      missingInputNodes.insert(target.getNodes()[inputID]);
    }
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // If the build should cancel, do nothing.
    if (ti.isCancelled()) {
      ti.complete(BuildValue::makeSkippedCommand().toData());
      return;
    }

    if (!missingInputNodes.empty()) {
      std::string inputs;
      raw_string_ostream inputsStream(inputs);
      for (Node* missingInputNode : missingInputNodes) {
        if (missingInputNode != *missingInputNodes.begin()) {
          inputsStream << ", ";
        }
        inputsStream << "'" << missingInputNode->getName() << "'";
      }
      inputsStream.flush();

      // FIXME: Design the logging and status output APIs.
      auto& system = getBuildSystem(ti);
      system.error(system.getMainFilename(),
                   (Twine("cannot build target '") + target.getName() +
                    "' due to missing inputs: " + inputs));
      
      // Report the command failure.
      system.getDelegate().hadCommandFailure();
    }
    
    // Complete the task immediately.
    ti.complete(BuildValue::makeTarget().toData());
  }

public:
  TargetTask(Target& target) : target(target) {}

  static bool isResultValid(BuildEngine&, Target&, const BuildValue&) {
    // Always treat target tasks as invalid.
    return false;
  }
};


/// This is the task to "build" a file node which represents pure raw input to
/// the system.
class FileInputNodeTask : public Task {
  BuildNode& node;

  virtual void start(TaskInterface) override {
    assert(node.getProducers().empty());
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // FIXME: We should do this work in the background.

    // Get the information on the file.
    //
    // FIXME: This needs to delegate, since we want to have a notion of
    // different node types.
    assert(!node.isVirtual());
    auto info = node.getFileInfo(
        getBuildSystem(ti).getFileSystem());
    if (info.isMissing()) {
      ti.complete(BuildValue::makeMissingInput().toData());
      return;
    }

    ti.complete(BuildValue::makeExistingInput(info).toData());
  }

public:
  FileInputNodeTask(BuildNode& node) : node(node) {
    assert(!node.isVirtual());
  }

  static bool isResultValid(BuildEngine& engine, const BuildNode& node,
                            const BuildValue& value) {
    // The result is valid if the existence matches the value type and the file
    // information remains the same.
    //
    // FIXME: This is inefficient, we will end up doing the stat twice, once
    // when we check the value for up to dateness, and once when we "build" the
    // output.
    //
    // We can solve this by caching ourselves but I wonder if it is something
    // the engine should support more naturally. In practice, this is unlikely
    // to be very performance critical in practice because this is only
    // redundant in the case where we have never built the node before (or need
    // to rebuild it), and thus the additional stat is only one small part of
    // the work we need to perform.
    auto info = node.getFileInfo(
        getBuildSystem(engine).getFileSystem());
    if (info.isMissing()) {
      return value.isMissingInput();
    } else {
      return value.isExistingInput() && value.getOutputInfo() == info;
    }
  }
};

/// This is the task to "build" a file info node which represents raw stat info
/// of a file system object.
class StatTask : public Task {
  StatNode& statnode;

  virtual void start(TaskInterface ti) override {
    // Create a weak link on any potential producer nodes so that we get up to
    // date stat information. We always run (see isResultValid) so this should
    // be safe (unlike directory contents where it may not run).
    ti.mustFollow(BuildKey::makeNode(statnode.getName()).toData());
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // FIXME: We should do this work in the background.

    // Get the information on the file.
    auto info = statnode.getFileInfo(getBuildSystem(ti).getFileSystem());
    if (info.isMissing()) {
      ti.complete(BuildValue::makeMissingInput().toData());
      return;
    }

    ti.complete(BuildValue::makeExistingInput(info).toData());
  }

public:
  StatTask(StatNode& statnode) : statnode(statnode) {}

  static bool isResultValid(BuildEngine&, const StatNode&, const BuildValue&) {
    // Always read the stat information
    return false;
  }
};

/// This is the task to "build" a directory node.
///
/// This node effectively just adapts a directory tree signature to a node. The
/// reason why we need it (versus simply making the directory tree signature
/// *be* this, is that we want the directory signature to be able to interface
/// with other build nodes produced by commands).
class DirectoryInputNodeTask : public Task {
  BuildNode& node;

  core::ValueType directorySignature;

  int totalBlockingDeps = 0;
  int finishedBlockingDeps = 0;

  void performUnblockedRequest(TaskInterface ti) {
    // Remove any trailing slash from the node name.
    StringRef path =  node.getName();
    if (path.endswith("/") && path != "/") {
      path = path.substr(0, path.size() - 1);
    }

    ti.request(BuildKey::makeDirectoryTreeSignature(path,
                 node.contentExclusionPatterns()).toData(),
               /*inputID=*/0);
  }

  virtual void start(TaskInterface ti) override {
    // We reserve inputID=0 for the blocked DirectoryTreeSignature request.
    // inputID=1, 2, ... are used for mustScanAfterPaths
    for (auto mustScanAfterPath: node.getMustScanAfterPaths()) {
      ++totalBlockingDeps;
      ti.request(BuildKey::makeNode(mustScanAfterPath).toData(), totalBlockingDeps);
    }

    // If mustScanAfterPaths is empty, simply request DirectoryTreeSignature in start
    if (totalBlockingDeps == 0) {
      performUnblockedRequest(ti);
    }
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                            const ValueType& valueData) override {
    if (inputID == 0) {
      directorySignature = valueData;
    } else {
      auto value = BuildValue::fromData(valueData);

      ++finishedBlockingDeps;
      if (finishedBlockingDeps == totalBlockingDeps) {
        // All paths within mustScanAfterPaths are scanned..
        // DirectoryTreeSignature is unblocked
        performUnblockedRequest(ti);
      }
    }
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // Simply propagate the value.
    ti.complete(ValueType(directorySignature));
  }

public:
  DirectoryInputNodeTask(BuildNode& node) : node(node) {
    assert(!node.isVirtual());
  }
};


/// This is the task to "build" a directory structure node.
///
/// This node effectively just adapts a directory tree structure signature to a
/// node. The reason why we need it (versus simply making the directory tree
/// signature *be* this, is that we want the directory signature to be able to
/// interface with other build nodes produced by commands).
class DirectoryStructureInputNodeTask : public Task {
  BuildNode& node;

  core::ValueType directorySignature;

  virtual void start(TaskInterface ti) override {
    // Remove any trailing slash from the node name.
    StringRef path =  node.getName();
    if (path.endswith("/") && path != "/") {
      path = path.substr(0, path.size() - 1);
    }
    ti.request(BuildKey::makeDirectoryTreeStructureSignature(path,
                 node.contentExclusionPatterns()).toData(),
               /*inputID=*/0);
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
    directorySignature = value;
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // Simply propagate the value.
    ti.complete(ValueType(directorySignature));
  }

public:
  DirectoryStructureInputNodeTask(BuildNode& node) : node(node) {
    assert(!node.isVirtual());
  }
};


/// This is the task to build a virtual node which isn't connected to any
/// output.
class VirtualInputNodeTask : public Task {
  virtual void start(TaskInterface) override {
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    ti.complete(BuildValue::makeVirtualInput().toData());
  }

public:
  VirtualInputNodeTask() {}

  static bool isResultValid(BuildEngine& engine, const BuildNode& node,
                            const BuildValue& value) {
    // Virtual input nodes are always valid unless the value type is wrong.
    return value.isVirtualInput();
  }
};


/// This is the task to "build" a node which is the product of some command.
///
/// It is responsible for selecting the appropriate producer command to run to
/// produce the node, and for synchronizing any external state the node depends
/// on.
class ProducedNodeTask : public Task {
  Node& node;
  BuildValue nodeResult;
  Command* producingCommand = nullptr;

  // Build specific data.
  //
  // FIXME: We should probably factor this out somewhere else, so we can enforce
  // it is never used when initialized incorrectly.

  // Whether this is a node we are unable to produce.
  bool isInvalid = false;
  
  virtual void start(TaskInterface ti) override {
    // Request the producer command.
    auto getCommand = [&]()->Command* {
      if (node.getProducers().size() == 1) {
        return node.getProducers()[0];
      }
      // Give the delegate a chance to resolve to a single command.
      return getBuildSystem(ti).getDelegate().
          chooseCommandFromMultipleProducers(&node, node.getProducers());
    };

    if (Command* foundCommand = getCommand()) {
      producingCommand = foundCommand;
      ti.request(BuildKey::makeCommand(producingCommand->getName()).toData(),
                 /*InputID=*/0);
      return;
    }

    // Notify that we could not resolve to a single producer.
    getBuildSystem(ti).getDelegate().
        cannotBuildNodeDueToMultipleProducers(&node, node.getProducers());
    isInvalid = true;
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& valueData) override {
    auto value = BuildValue::fromData(valueData);

    // Extract the node result from the command.
    assert(producingCommand);
    nodeResult = producingCommand->getResultForOutput(&node, value);
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    if (isInvalid) {
      getBuildSystem(ti).getDelegate().hadCommandFailure();
      ti.complete(BuildValue::makeFailedInput().toData());
      return;
    }
    
    assert(!nodeResult.isInvalid());
    
    // Complete the task immediately.
    ti.complete(nodeResult.toData());
  }

public:
  ProducedNodeTask(Node& node)
      : node(node), nodeResult(BuildValue::makeInvalid()) {}
  
  static bool isResultValid(BuildEngine& engine, Node& node,
                            const BuildValue& value) {
    // If the result was failure, we always need to rebuild (it may produce an
    // error).
    if (value.isFailedInput())
      return false;

    // If the result was previously a missing input, it may have been because
    // we did not previously know how to produce this node. We do now, so
    // attempt to build it now.
    if (value.isMissingInput())
      return false;

    // The produced node result itself doesn't need any synchronization.
    return true;
  }
};

class ProducedDirectoryNodeTask : public Task {
  Node& node;

  BuildValue nodeResult;
  core::ValueType directorySignature;

  Command* producingCommand = nullptr;

  // Whether this is a node we are unable to produce.
  bool isInvalid = false;
  bool returnDirectorySignature = false;

  virtual void start(TaskInterface ti) override {
    // Request the producer command.
    auto getCommand = [&]()->Command* {
      if (node.getProducers().size() == 1) {
        return node.getProducers()[0];
      }
      // Give the delegate a chance to resolve to a single command.
      return getBuildSystem(ti).getDelegate().
          chooseCommandFromMultipleProducers(&node, node.getProducers());
    };

    if (Command* foundCommand = getCommand()) {
      producingCommand = foundCommand;
      ti.request(BuildKey::makeCommand(producingCommand->getName()).toData(),
                 /*InputID=*/0);
      return;
    }

    // Notify that we could not resolve to a single producer.
    getBuildSystem(ti).getDelegate().
        cannotBuildNodeDueToMultipleProducers(&node, node.getProducers());
    isInvalid = true;
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                            const ValueType& valueData) override {
    if (inputID == 0) {
      auto value = BuildValue::fromData(valueData);

      // Extract the node result from the command.
      assert(producingCommand);

      // NOTE: nodeResult only contains stat info of the directory, not its signature.
      nodeResult = producingCommand->getResultForOutput(&node, value);

      if (nodeResult.isExistingInput()) {
        // The external command must have produced the directory node.
        // Request for its signature and store it

        StringRef path =  node.getName();
        if (path.endswith("/") && path != "/") {
          path = path.substr(0, path.size() - 1);
        }
        ti.request(BuildKey::makeDirectoryTreeSignature(path,basic::StringList()).toData(), /*inputID=*/1);
        returnDirectorySignature = true;
      }
    } else if (inputID == 1) {
      directorySignature = valueData;
    }
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    if (returnDirectorySignature) {
      ti.complete(ValueType(directorySignature));
      return;
    } else {
      if (isInvalid) {
        getBuildSystem(ti).getDelegate().hadCommandFailure();
        ti.complete(BuildValue::makeFailedInput().toData());
        return;
      }
      assert(!nodeResult.isInvalid());
      
      // Complete the task immediately.
      ti.complete(nodeResult.toData());
    }
  }

public:
  ProducedDirectoryNodeTask(Node& node)
      : node(node), nodeResult(BuildValue::makeInvalid()) {}

  static bool isResultValid(BuildEngine& engine, Node& node,
                            const BuildValue& value) {
    // If the result was failure, we always need to rebuild (it may produce an
    // error).
    if (value.isFailedInput())
      return false;

    // If the result was previously a missing input, it may have been because
    // we did not previously know how to produce this node. We do now, so
    // attempt to build it now.
    if (value.isMissingInput())
      return false;

    // The produced node result itself doesn't need any synchronization.
    // If the directory signature is changed, it will be reflected in value of this node.
    return true;
  }
};


/// This task is responsible for computing the lists of files in directories.
class DirectoryContentsTask : public Task {
  std::string path;

  /// The value for the input directory.
  BuildValue directoryValue;
  
  virtual void start(TaskInterface ti) override {
    // Request the base directory node -- this task doesn't actually use the
    // value, but this connects the task to its producer if present.

    // FIXME:
    //
    //engine.taskMustFollow(this, BuildKey::makeNode(path).toData());
    //
    // The taskMustFollow method expresses the weak dependency we have on
    // 'path', but only at the task level. What we really want is to say at the
    // 'isResultValid'/scanning level is 'must scan after'. That way we hold up
    // this and downstream rules until the 'path' node has been set into its
    // final state*.
    //
    // With the explicit dependency we are establishing with request(), we
    // will unfortunately mark directory contents as 'needs to be built' under
    // situations where non-releveant stat info has changed. This causes
    // unnecessary rebuilds. See rdar://problem/30640904
    //
    // * The 'final state' of a directory is also a thorny patch of toxic land
    // mines. We really want directory contents to weakly depend upon anything
    // that is currently and/or may be altered within it. i.e. if one rule
    // creates the directory and another rule writes a file into it, we want to
    // defer scanning until both of them have been scanned and possibly run.
    // Having a 'must scan after' would help with the first rule (mkdir), but
    // not the second, in particular if rules are added in subsequent builds.
    // Related rdar://problem/30638921
    //
    ti.request(BuildKey::makeNode(path).toData(), /*inputID=*/0);
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
    if (inputID == 0) {
      directoryValue = BuildValue::fromData(value);
      return;
    }
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // FIXME: We should do this work in the background.
    
    if (directoryValue.isMissingInput()) {
      ti.complete(BuildValue::makeMissingInput().toData());
      return;
    }

    if (directoryValue.isMissingOutput()) {
      // Rewrite a missing output as a missing input build value for this node, both conceptually and as a hedge against violating the downstream expectations of other rules.
      ti.complete(BuildValue::makeMissingInput().toData());
      return;
    }

    if (directoryValue.isFailedInput()) {
      ti.complete(BuildValue::makeFailedInput().toData());
      return;
    }

    // The input directory may be a 'mkdir' command, which can be cancelled or
    // skipped by the engine or the delegate. rdar://problem/50380532
    if (directoryValue.isSkippedCommand()) {
      ti.complete(BuildValue::makeSkippedCommand().toData());
      return;
    }

    std::vector<std::string> filenames;
    std::error_code ec = getContents(path, filenames);

    // Currently, tests and presumably clients expect that errors are silently
    // ignored when reading directory contents listings.
    (void)ec;

    // Create the result.
    ti.complete(BuildValue::makeDirectoryContents(directoryValue.getOutputInfo(),
                                                  filenames).toData());
  }


  static std::error_code getContents(StringRef path, std::vector<std::string>& filenames) {
    // Get the list of files in the directory.
    // FIXME: This is not going through the filesystem object. Indeed the fs
    // object does not currently support directory listing/iteration, but
    // probably should so that clients may override it.
    //
    // Exit the loop if we encounter any errors, to prevent infinitely looping
    // over an invalid directory in some circumstances. rdar://101717159
    std::error_code ec;
    for (auto it = llvm::sys::fs::directory_iterator(path, ec),
         end = llvm::sys::fs::directory_iterator(); it != end && !ec;
         it = it.increment(ec)) {
      filenames.push_back(llvm::sys::path::filename(it->path()));
    }

    // Order the filenames.
    std::sort(filenames.begin(), filenames.end(),
              [](const std::string& a, const std::string& b) {
                return a < b;
              });

    return ec;
  }


public:
  DirectoryContentsTask(StringRef path)
      : path(path), directoryValue(BuildValue::makeInvalid()) {}

  static bool isResultValid(BuildEngine& engine, StringRef path,
                            const BuildValue& value) {
    // The result is valid if the existence matches the existing value type, and
    // the file information remains the same.
    auto info = getBuildSystem(engine).getFileSystem().getFileInfo(
        path);
    if (info.isMissing()) {
      return value.isMissingInput();
    } else {
      if (!value.isDirectoryContents())
        return false;

      // If the type changes rebuild
      if (info.isDirectory() != value.getOutputInfo().isDirectory())
        return false;

      // For files, it is direct stat info that matters
      if (!info.isDirectory())
        return value.getOutputInfo() == info;

      // With filters, we list the current filtered contents and then compare
      // the lists.
      std::vector<std::string> cur;
      std::error_code ec = getContents(path, cur);

      // Currently, tests and presumably clients expect that errors are silently
      // ignored when reading directory contents listings.
      (void)ec;

      auto prev = value.getDirectoryContents();

      if (cur.size() != prev.size())
        return false;

      auto cur_it = cur.begin();
      auto prev_it = prev.begin();
      for (; cur_it != cur.end() && prev_it != prev.end(); cur_it++, prev_it++) {
        if (*cur_it != *prev_it) {
          return false;
        }
      }

      return true;
    }
  }
};


/// This task is responsible for computing the filtered lists of files in
/// directories.
class FilteredDirectoryContentsTask : public Task {
  std::string path;

  /// The exclusion filters used while computing the signature
  StringList filters;

  /// The value for the input directory.
  BuildValue directoryValue;

  virtual void start(TaskInterface ti) override {
    // FIXME:
    //
    //engine.taskMustFollow(this, BuildKey::makeNode(path).toData());
    //
    // The taskMustFollow method expresses the weak dependency we have on
    // 'path', but only at the task level. What we really want is to say at the
    // 'isResultValid'/scanning level is 'must scan after'. That way we hold up
    // this and downstream rules until the 'path' node has been set into its
    // final state*.
    //
    // Here we depend on the file node so that it can be connected up to
    // potential producers and the raw stat information, in case something else
    // has changed the contents of the directory. The value does not encode the
    // raw stat information, thus will produce the same result if the filtered
    // contents is otherwise the same. This reduces unnecessary rebuilds. That
    // said, we are still subject to the 'final state' problem:
    //
    // * The 'final state' of a directory is also a thorny patch of toxic land
    // mines. We really want directory contents to weakly depend upon anything
    // that is currently and/or may be altered within it. i.e. if one rule
    // creates the directory and another rule writes a file into it, we want to
    // defer scanning until both of them have been scanned and possibly run.
    // Having a 'must scan after' would help with the first rule (mkdir), but
    // not the second, in particular if rules are added in subsequent builds.
    // Related rdar://problem/30638921
    ti.request(BuildKey::makeNode(path).toData(), /*inputID=*/0);
    ti.request(BuildKey::makeStat(path).toData(), /*inputID=*/1);
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& value) override {
    if (inputID == 1) {
      directoryValue = BuildValue::fromData(value);
      return;
    }
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    if (directoryValue.isMissingInput()) {
      ti.complete(BuildValue::makeMissingInput().toData());
      return;
    }

    if (!directoryValue.isExistingInput()) {
      ti.complete(BuildValue::makeFailedInput().toData());
      return;
    }

    auto& info = directoryValue.getOutputInfo();

    // Non-directory things are just plain-ol' inputs
    if (!info.isDirectory()) {
      ti.complete(BuildValue::makeExistingInput(info).toData());
      return;
    }

    // Collect the filtered contents
    std::vector<std::string> filenames;
    getFilteredContents(path, filters, filenames);

    // Create the result.
    ti.complete(BuildValue::makeFilteredDirectoryContents(filenames).toData());
  }


  static std::error_code getFilteredContents(StringRef path, const StringList& filters,
                                  std::vector<std::string>& filenames) {
    auto filterStrings = filters.getValues();

    // Get the list of files in the directory.
    // FIXME: This is not going through the filesystem object. Indeed the fs
    // object does not currently support directory listing/iteration, but
    // probably should so that clients may override it.
    //
    // Exit the loop if we encounter any errors, to prevent infinitely looping
    // over an invalid directory in some circumstances. rdar://101717159
    std::error_code ec;
    for (auto it = llvm::sys::fs::directory_iterator(path, ec),
         end = llvm::sys::fs::directory_iterator(); it != end && !ec;
         it = it.increment(ec)) {
      std::string filename = llvm::sys::path::filename(it->path());
      bool excluded = false;
      for (auto pattern : filterStrings) {
        if (llbuild::basic::sys::filenameMatch(pattern.data(),
                                               filename.c_str()) ==
            llbuild::basic::sys::MATCH) {
          excluded = true;
          break;
        }
      }
      if (!excluded)
        filenames.push_back(filename);
    }

    // Order the filenames.
    std::sort(filenames.begin(), filenames.end(),
              [](const std::string& a, const std::string& b) {
                return a < b;
              });

    return ec;
  }


public:
  FilteredDirectoryContentsTask(StringRef path, StringList&& filters)
      : path(path), filters(std::move(filters))
      , directoryValue(BuildValue::makeInvalid()) {}
};



/// This is the task to "build" a directory node which will encapsulate (via a
/// signature) a (optionally) filtered view of the contents of the directory,
/// recursively.
class DirectoryTreeSignatureTask : public Task {
  // The basic algorithm we need to follow:
  //
  // 1. Get the directory contents.
  // 2. Get the subpath directory info.
  // 3. For each node input, if it is a directory, get the input node for it.
  //
  // FIXME: This algorithm currently does a redundant stat for each directory,
  // because we stat it once to find out it is a directory, then again when we
  // gather its contents (to use for validating the directory contents).
  //
  // FIXME: We need to fix the directory list to not get contents for symbolic
  // links.

  /// This structure encapsulates the information we need on each child.
  struct SubpathInfo {
    /// The filename;
    std::string filename;

    /// The result of requesting the node at this subpath, once available.
    ValueType value;

    /// The directory signature, if needed.
    llvm::Optional<ValueType> directorySignatureValue;
  };

  /// The path we are taking the signature of.
  std::string path;

  /// The exclusion filters used while computing the signature
  StringList filters;

  /// The value for the directory itself.
  ValueType directoryValue;

  /// The accumulated list of child input info.
  ///
  /// Once we have the input directory information, we resize this to match the
  /// number of children to avoid dynamically resizing it.
  std::vector<SubpathInfo> childResults;

  virtual void start(TaskInterface ti) override {
    // Ask for the base directory directory contents.
    if (filters.isEmpty()) {
      ti.request(BuildKey::makeDirectoryContents(path).toData(), /*inputID=*/0);
    } else {
      ti.request(BuildKey::makeFilteredDirectoryContents(path, filters).toData(),
                 /*inputID=*/0);
    }
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                            const ValueType& valueData) override {
    // The first input is the directory contents.
    if (inputID == 0) {
      // Record the value for the directory.
      directoryValue = valueData;

      // Request the inputs for each subpath.
      auto value = BuildValue::fromData(valueData);
      if ((filters.isEmpty() && !value.isDirectoryContents()) ||
          (!filters.isEmpty() && !value.isFilteredDirectoryContents())) {
        return;
      }

      assert(value.isFilteredDirectoryContents() || value.isDirectoryContents());
      auto filenames = value.getDirectoryContents();
      for (size_t i = 0; i != filenames.size(); ++i) {
        SmallString<256> childPath{ path };
        llvm::sys::path::append(childPath, filenames[i]);
        childResults.emplace_back(SubpathInfo{ filenames[i], {}, None });
        ti.request(BuildKey::makeNode(childPath).toData(), /*inputID=*/1 + i);
      }
      return;
    }

    // If the input is a child, add it to the collection and dispatch a
    // directory request if needed.
    if (inputID >= 1 && inputID < 1 + childResults.size()) {
      auto index = inputID - 1;
      auto& childResult = childResults[index];
      childResult.value = valueData;

      // If this node is a directory, request its signature recursively.
      auto value = BuildValue::fromData(valueData);
      if (value.isExistingInput()) {
        if (value.getOutputInfo().isDirectory()) {
          SmallString<256> childPath{ path };
          llvm::sys::path::append(childPath, childResult.filename);

          ti.request(BuildKey::makeDirectoryTreeSignature(childPath,
                                                          filters).toData(),
                     /*inputID=*/1 + childResults.size() + index);
        }
      }
      return;
    }

    // Otherwise, the input should be a directory signature.
    auto index = inputID - 1 - childResults.size();
    assert(index < childResults.size());
    childResults[index].directorySignatureValue = valueData;
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // Compute the signature across all of the inputs.
    using llvm::hash_combine;
    llvm::hash_code code = hash_value(path);

    // Add the signature for the actual input path.
    code = hash_combine(
        code, hash_combine_range(directoryValue.begin(), directoryValue.end()));

    // For now, we represent this task as the aggregation of all the inputs.
    for (const auto& info: childResults) {
      // We merge the children by simply combining their encoded representation.
      code = hash_combine(
          code, hash_combine_range(info.value.begin(), info.value.end()));
      if (info.directorySignatureValue.hasValue()) {
        auto& data = info.directorySignatureValue.getValue();
        code = hash_combine(
            code, hash_combine_range(data.begin(), data.end()));
      } else {
        // Combine a random number to represent nil.
        code = hash_combine(code, 0XC183979C3E98722E);
      }
    }

    // Compute the signature.
    ti.complete(BuildValue::makeDirectoryTreeSignature(
                  CommandSignature(uint64_t(code))).toData());
  }

public:
  DirectoryTreeSignatureTask(StringRef path, StringList&& filters)
      : path(path), filters(std::move(filters)) {}
};


/// This is the task to "build" a directory structure node which will
/// encapsulate (via a signature) the structure of the directory, recursively.
class DirectoryTreeStructureSignatureTask : public Task {
  // The basic algorithm we need to follow:
  //
  // 1. Get the directory contents.
  // 2. Get the subpath directory info.
  // 3. For each node input, if it is a directory, get the input node for it.
  //
  // FIXME: This algorithm currently does a redundant stat for each directory,
  // because we stat it once to find out it is a directory, then again when we
  // gather its contents (to use for validating the directory contents).
  //
  // FIXME: We need to fix the directory list to not get contents for symbolic
  // links.

  /// This structure encapsulates the information we need on each child.
  struct SubpathInfo {
    /// The filename;
    std::string filename;
    
    /// The result of requesting the node at this subpath, once available.
    ValueType value;

    /// The directory structure signature, if needed.
    llvm::Optional<ValueType> directoryStructureSignatureValue;
  };
  
  /// The path we are taking the signature of.
  std::string path;

  /// The exclusion filters used while computing the signature
  StringList filters;

  /// The value for the directory itself.
  ValueType directoryValue;

  /// The accumulated list of child input info.
  ///
  /// Once we have the input directory information, we resize this to match the
  /// number of children to avoid dynamically resizing it.
  std::vector<SubpathInfo> childResults;
  
  virtual void start(TaskInterface ti) override {
    // Ask for the base directory directory contents.
    if (filters.isEmpty()) {
      ti.request(BuildKey::makeDirectoryContents(path).toData(), /*inputID=*/0);
    } else {
      ti.request(BuildKey::makeFilteredDirectoryContents(path, filters).toData(),
                 /*inputID=*/0);
    }
  }

  virtual void providePriorValue(TaskInterface,
                                 const ValueType& value) override {
  }

  virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                            const ValueType& valueData) override {
    // The first input is the directory contents.
    if (inputID == 0) {
      // Record the value for the directory.
      directoryValue = valueData;

      // Request the inputs for each subpath.
      auto value = BuildValue::fromData(valueData);
      if (value.isMissingInput() || value.isSkippedCommand())
        return;

      assert(value.isFilteredDirectoryContents() || value.isDirectoryContents());
      auto filenames = value.getDirectoryContents();
      for (size_t i = 0; i != filenames.size(); ++i) {
        SmallString<256> childPath{ path };
        llvm::sys::path::append(childPath, filenames[i]);
        childResults.emplace_back(SubpathInfo{ filenames[i], {}, None });
        ti.request(BuildKey::makeNode(childPath).toData(), /*inputID=*/1 + i);
      }
      return;
    }

    // If the input is a child, add it to the collection and dispatch a
    // directory structure request if needed.
    if (inputID >= 1 && inputID < 1 + childResults.size()) {
      auto index = inputID - 1;
      auto& childResult = childResults[index];
      childResult.value = valueData;

      // If this node is a directory, request its signature recursively.
      auto value = BuildValue::fromData(valueData);
      if (value.isExistingInput()) {
        if (value.getOutputInfo().isDirectory()) {
          SmallString<256> childPath{ path };
          llvm::sys::path::append(childPath, childResult.filename);
        
          ti.request(
            BuildKey::makeDirectoryTreeStructureSignature(childPath, filters).toData(),
            /*inputID=*/1 + childResults.size() + index);
        }
      }
      return;
    }

    // Otherwise, the input should be a directory signature.
    auto index = inputID - 1 - childResults.size();
    assert(index < childResults.size());
    childResults[index].directoryStructureSignatureValue = valueData;
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    // Compute the signature across all of the inputs.
    using llvm::hash_combine;
    llvm::hash_code code = hash_value(path);

    // Only merge the structure information on the directory itself.
    {
      // We need to merge mode information about the directory itself, in case
      // it changes type.
      auto value = BuildValue::fromData(directoryValue);
      if (value.isDirectoryContents()) {
        code = hash_combine(code, value.getOutputInfo().mode);
      } else {
        code = hash_combine(
            code, hash_combine_range(directoryValue.begin(),
                                     directoryValue.end()));
      }
    }
    
    // For now, we represent this task as the aggregation of all the inputs.
    for (const auto& info: childResults) {
      // We only merge the "structural" information on a child; i.e. its
      // filename and type.
      code = hash_combine(code, info.filename);
      auto value = BuildValue::fromData(info.value);
      if (value.isExistingInput()) {
        code = hash_combine(code, value.getOutputInfo().mode);
      } else {
        // If this node has been modified to report a non-file value, just merge
        // the encoded representation.
        code = hash_combine(
            code, hash_combine_range(info.value.begin(), info.value.end()));
      }
      
      if (info.directoryStructureSignatureValue.hasValue()) {
        auto& data = info.directoryStructureSignatureValue.getValue();
        code = hash_combine(
            code, hash_combine_range(data.begin(), data.end()));
      } else {
        // Combine a random number to represent nil.
        code = hash_combine(code, 0XC183979C3E98722E);
      }
    }
    
    // Compute the signature.
    ti.complete(BuildValue::makeDirectoryTreeStructureSignature(
                  CommandSignature(uint64_t(code))).toData());
  }

public:
  DirectoryTreeStructureSignatureTask(StringRef path, StringList&& filters) : path(path), filters(std::move(filters)) {}
};


/// This is the task to actually execute a command.
class CommandTask : public Task {
  Command& command;

  virtual void start(TaskInterface ti) override {
    // Notify the client the command is preparing to run.
    getBuildSystem(ti).getDelegate().commandPreparing(&command);

    command.start(getBuildSystem(ti).getBuildSystem(), ti);
  }

  virtual void providePriorValue(TaskInterface ti,
                                 const ValueType& valueData) override {
    BuildValue value = BuildValue::fromData(valueData);
    command.providePriorValue(getBuildSystem(ti).getBuildSystem(), ti, value);
  }

  virtual void provideValue(TaskInterface ti, uintptr_t inputID,
                            const ValueType& valueData) override {
    command.provideValue(getBuildSystem(ti).getBuildSystem(), ti, inputID,
                         BuildValue::fromData(valueData));
  }

  virtual void inputsAvailable(TaskInterface ti) override {
    auto fn = [this, ti](QueueJobContext* context) mutable {
      // If the build should cancel, do nothing.
      if (ti.isCancelled()) {
        ti.complete(BuildValue::makeCancelledCommand().toData());
        return;
      }

      // Check if the command should be skipped.
      if (!getBuildSystem(ti).getDelegate().shouldCommandStart(&command)) {
        // We need to call commandFinished here because commandPreparing and
        // shouldCommandStart guarantee that they're followed by
        // commandFinished.
        getBuildSystem(ti).getDelegate().commandFinished(&command, ProcessStatus::Skipped);
        ti.complete(BuildValue::makeSkippedCommand().toData());
        return;
      }
    
      // Execute the command, with notifications to the delegate.
      command.execute(getBuildSystem(ti).getBuildSystem(), ti, context, [ti](BuildValue&& result) mutable {
        // Inform the engine of the result.
        if (result.isFailedCommand()) {
          getBuildSystem(ti).getDelegate().hadCommandFailure();
        }
        ti.complete(result.toData());
      });
    };
    if (command.isDetached()) {
      struct DetachedContext: public QueueJobContext {
        unsigned laneID() const override { return -1; }
      };
      DetachedContext ctx;
      fn(&ctx);
    } else {
      ti.spawn({ &command, std::move(fn) });
    }
  }

public:
  CommandTask(Command& command) : command(command) {}

  static bool isResultValid(BuildEngine& engine, Command& command,
                            const BuildValue& value) {
    // Delegate to the command for further checking.
    auto& buildSystem =
      static_cast<BuildSystemEngineDelegate*>(engine.getDelegate())->getBuildSystem();
    return command.isResultValid(buildSystem.getBuildSystem(), value);
  }
};

#pragma mark - BuildSystemEngineDelegate implementation

/// This is a synthesized task used to represent a missing command.
///
/// This command is used in cases where a command has been removed from the
/// manifest, but can still be found during an incremental rebuild. This command
/// is used to inject an invalid value thus forcing downstream clients to
/// rebuild.
class MissingCommandTask : public Task {
private:
  virtual void start(TaskInterface) override { }
  virtual void providePriorValue(TaskInterface,
                                 const ValueType& valueData) override { }

  virtual void provideValue(TaskInterface, uintptr_t inputID,
                            const ValueType& valueData) override { }

  virtual void inputsAvailable(TaskInterface ti) override {
    // A missing command always builds to an invalid value, and forces
    // downstream clients to be rebuilt (at which point they will presumably see
    // the command is no longer used).
    return ti.complete(BuildValue::makeInvalid().toData(),
                       /*forceChange=*/true);
  }

public:
  using Task::Task;
};

const BuildDescription& BuildSystemEngineDelegate::getBuildDescription() const {
  return system.getBuildDescription();
}

static BuildSystemDelegate::CommandStatusKind
convertStatusKind(core::Rule::StatusKind kind) {
  switch (kind) {
  case core::Rule::StatusKind::IsScanning:
    return BuildSystemDelegate::CommandStatusKind::IsScanning;
  case core::Rule::StatusKind::IsUpToDate:
    return BuildSystemDelegate::CommandStatusKind::IsUpToDate;
  case core::Rule::StatusKind::IsComplete:
    return BuildSystemDelegate::CommandStatusKind::IsComplete;
  }
  assert(0 && "unknown status kind");
  return BuildSystemDelegate::CommandStatusKind::IsScanning;
}

class BuildSystemRule : public Rule {
private:
  /// Called to create the task to build the rule, when necessary.
  std::function<Task*(BuildEngine&)> action;

  /// Called to check whether the previously computed value for this rule is
  /// still valid.
  ///
  /// This callback is designed for use in synchronizing values which represent
  /// state managed externally to the build engine. For example, a rule which
  /// computes something on the file system may use this to verify that the
  /// computed output has not changed since it was built.
  std::function<bool(BuildEngine&, const Rule&,
                     const ValueType&)> resultValid;

  /// Called to indicate a change in the rule status.
  std::function<void(BuildEngine&, StatusKind)> update;

public:
  BuildSystemRule(
    const KeyType& key,
    const basic::CommandSignature& signature,
    std::function<Task*(BuildEngine&)> action,
    std::function<bool(BuildEngine&, const Rule&, const ValueType&)> valid = nullptr,
    std::function<void(BuildEngine&, StatusKind)> update = nullptr)
  : Rule(key, signature), action(action), resultValid(valid), update(update)
  { }

public:
  Task* createTask(BuildEngine& engine) override {
    return action(engine);
  }

  bool isResultValid(BuildEngine& engine, const ValueType& value) override {
    if (!resultValid) return true;
    return resultValid(engine, *this, value);
  }

  void updateStatus(BuildEngine& engine, Rule::StatusKind status) override {
    if (update) update(engine, status);
  }
};





std::unique_ptr<Rule> BuildSystemEngineDelegate::lookupRule(const KeyType& keyData) {
  // Decode the key.
  auto key = BuildKey::fromData(keyData);

  switch (key.getKind()) {
  case BuildKey::Kind::Unknown:
    break;
    
  case BuildKey::Kind::Command: {
    // Find the comand.
    auto it = getBuildDescription().getCommands().find(key.getCommandName());
    if (it == getBuildDescription().getCommands().end()) {
      // If there is no such command, produce an error task.
      return std::unique_ptr<Rule>(new BuildSystemRule(
        keyData,
        /*signature=*/{},
        /*Action=*/ [](BuildEngine& engine) -> Task* {
          return new MissingCommandTask();
        },
        /*IsValid=*/ [](BuildEngine&, const Rule&, const ValueType&) -> bool {
          // The cached result for a missing command is never valid.
          return false;
        }
      ));
    }

    // Create the rule for the command.
    Command* command = it->second.get();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      command->getSignature(),
      /*Action=*/ [command](BuildEngine& engine) -> Task* {
        return new CommandTask(*command);
      },
      /*IsValid=*/ [command](BuildEngine& engine, const Rule& rule,
                             const ValueType& value) -> bool {
        return CommandTask::isResultValid(
            engine, *command, BuildValue::fromData(value));
      },
      /*UpdateStatus=*/ [command](BuildEngine& engine,
                                  core::Rule::StatusKind status) {
        return ::getBuildSystem(engine).getDelegate().commandStatusChanged(
            command, convertStatusKind(status));
      }
    ));
  }

  case BuildKey::Kind::CustomTask: {
    // Search for a tool which knows how to create the given custom task.
    //
    // FIXME: We should most likely have some kind of registration process so we
    // can do an efficient query here, but exactly how this should look isn't
    // clear yet.
    for (const auto& it: getBuildDescription().getTools()) {
      auto result = it.second->createCustomCommand(key);
      if (!result) continue;

      // Save the custom command.
      customTasks.emplace_back(std::move(result));
      Command *command = customTasks.back().get();
      
      return std::unique_ptr<Rule>(new BuildSystemRule(
        keyData,
        command->getSignature(),
        /*Action=*/ [command](BuildEngine& engine) -> Task* {
          return new CommandTask(*command);
        },
        /*IsValid=*/ [command](BuildEngine& engine, const Rule& rule,
                               const ValueType& value) -> bool {
          return CommandTask::isResultValid(
              engine, *command, BuildValue::fromData(value));
        },
        /*UpdateStatus=*/ [command](BuildEngine& engine,
                                    core::Rule::StatusKind status) {
          return ::getBuildSystem(engine).getDelegate().commandStatusChanged(
              command, convertStatusKind(status));
        }
      ));
    }
    
    // We were unable to create an appropriate custom command, produce an error
    // task.
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [](BuildEngine& engine) -> Task* {
        return new MissingCommandTask();
      },
      /*IsValid=*/ [](BuildEngine&, const Rule&, const ValueType&) -> bool {
        // The cached result for a missing command is never valid.
        return false;
      }
    ));
  }

  case BuildKey::Kind::DirectoryContents: {
    std::string path = key.getDirectoryPath();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [path](BuildEngine& engine) -> Task* {
        return new DirectoryContentsTask(path);
      },
      /*IsValid=*/ [path](BuildEngine& engine, const Rule& rule,
          const ValueType& value) mutable -> bool {
        return DirectoryContentsTask::isResultValid(
            engine, path, BuildValue::fromData(value));
      }
    ));
  }

  case BuildKey::Kind::FilteredDirectoryContents: {
    std::string path = key.getFilteredDirectoryPath();
    std::string patterns = key.getContentExclusionPatterns();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [path, patterns](BuildEngine& engine) -> Task* {
        BinaryDecoder decoder(patterns);
        return new FilteredDirectoryContentsTask(path, StringList(decoder));
      },
      /*IsValid=*/ nullptr
    ));
  }

  case BuildKey::Kind::DirectoryTreeSignature: {
    std::string path = key.getDirectoryTreeSignaturePath();
    std::string filters = key.getContentExclusionPatterns();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [path, filters](
          BuildEngine& engine) mutable -> Task* {
        BinaryDecoder decoder(filters);
        return new DirectoryTreeSignatureTask(path, StringList(decoder));
      },
        // Directory signatures don't require any validation outside of their
        // concrete dependencies.
      /*IsValid=*/ nullptr
    ));
  }

  case BuildKey::Kind::DirectoryTreeStructureSignature: {
    std::string path = key.getFilteredDirectoryPath();
    std::string filters = key.getContentExclusionPatterns();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [path, filters](
          BuildEngine& engine) mutable -> Task* {
        BinaryDecoder decoder(filters);
        return new DirectoryTreeStructureSignatureTask(path, StringList(decoder));
      },
        // Directory signatures don't require any validation outside of their
        // concrete dependencies.
      /*IsValid=*/ nullptr
    ));
  }
    
  case BuildKey::Kind::Node: {
    // Find the node.
    auto it = getBuildDescription().getNodes().find(key.getNodeName());
    BuildNode* node;
    if (it != getBuildDescription().getNodes().end()) {
      node = static_cast<BuildNode*>(it->second.get());
    } else {
      auto it = dynamicNodes.find(key.getNodeName());
      if (it != dynamicNodes.end()) {
        node = it->second.get();
      } else {
        // Create nodes on the fly for any unknown ones.
        auto nodeOwner = system.lookupNode(
            key.getNodeName(), /*isImplicit=*/true);
        node = nodeOwner.get();
        dynamicNodes[key.getNodeName()] = std::move(nodeOwner);
      }
    }

    // Create the rule used to construct this node.
    //
    // We could bypass this level and directly return the rule to run the
    // command, which would reduce the number of tasks in the system. For now we
    // do the uniform thing, but do differentiate between input and command
    // nodes.

    // Create an input node if there are no producers.
    if (node->getProducers().empty()) {
      if (node->isVirtual()) {
        return std::unique_ptr<Rule>(new BuildSystemRule(
          keyData,
          node->getSignature(),
          /*Action=*/ [](BuildEngine& engine) -> Task* {
            return new VirtualInputNodeTask();
          },
          /*IsValid=*/ [node](BuildEngine& engine, const Rule& rule,
                                const ValueType& value) -> bool {
            return VirtualInputNodeTask::isResultValid(
                engine, *node, BuildValue::fromData(value));
          }
        ));
      }

      // DirectoryInputNodeTask
      if (node->isDirectory()) {
        return std::unique_ptr<Rule>(new BuildSystemRule(
          keyData,
          node->getSignature(),
          /*Action=*/ [node](BuildEngine& engine) -> Task* {
            return new DirectoryInputNodeTask(*node);
          },
            // Directory nodes don't require any validation outside of their
            // concrete dependencies.
          /*IsValid=*/ nullptr
        ));
      }

      if (node->isDirectoryStructure()) {
        return std::unique_ptr<Rule>(new BuildSystemRule(
          keyData,
          node->getSignature(),
          /*Action=*/ [node](BuildEngine& engine) -> Task* {
            return new DirectoryStructureInputNodeTask(*node);
          },
            // Directory nodes don't require any validation outside of their
            // concrete dependencies.
          /*IsValid=*/ nullptr
        ));
      }

      // FileInputNodeTask
      return std::unique_ptr<Rule>(new BuildSystemRule(
        keyData,
        node->getSignature(),
        /*Action=*/ [node](BuildEngine& engine) -> Task* {
          return new FileInputNodeTask(*node);
        },
        /*IsValid=*/ [node](BuildEngine& engine, const Rule& rule,
                            const ValueType& value) -> bool {
          return FileInputNodeTask::isResultValid(
              engine, *node, BuildValue::fromData(value));
        }
      ));
    }

    // Otherwise, create a task for a produced node.
    // ProducedDirectoryNodeTask
    if (node->isDirectory()) {
      return std::unique_ptr<Rule>(new BuildSystemRule(
        keyData,
        node->getSignature(),
        /*Action=*/ [node](BuildEngine& engine) -> Task* {
          return new ProducedDirectoryNodeTask(*node);
        },
        /*IsValid=*/ [node](BuildEngine& engine, const Rule& rule,
                            const ValueType& value) -> bool {
          return ProducedDirectoryNodeTask::isResultValid(
              engine, *node, BuildValue::fromData(value));
        }
      ));
    }

    // ProducedNodeTask
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      node->getSignature(),
      /*Action=*/ [node](BuildEngine& engine) -> Task* {
        return new ProducedNodeTask(*node);
      },
      /*IsValid=*/ [node](BuildEngine& engine, const Rule& rule,
                          const ValueType& value) -> bool {
        return ProducedNodeTask::isResultValid(
            engine, *node, BuildValue::fromData(value));
      }
    ));
  }

  case BuildKey::Kind::Stat: {
    StatNode* statnode;
    auto it = dynamicStatNodes.find(key.getStatName());
    if (it != dynamicStatNodes.end()) {
      statnode = it->second.get();
    } else {
      // Create nodes on the fly for any unknown ones.
      auto statOwner = llvm::make_unique<StatNode>(key.getStatName());
      statnode = statOwner.get();
      dynamicStatNodes[key.getStatName()] = std::move(statOwner);
    }

    // Create the rule to construct this target.
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [statnode](BuildEngine& engine) -> Task* {
        return new StatTask(*statnode);
      },
      /*IsValid=*/ [statnode](BuildEngine& engine, const Rule& rule,
                            const ValueType& value) -> bool {
        return StatTask::isResultValid(
            engine, *statnode, BuildValue::fromData(value));
      }
    ));
  }
  case BuildKey::Kind::Target: {
    // Find the target.
    auto it = getBuildDescription().getTargets().find(key.getTargetName());
    if (it == getBuildDescription().getTargets().end()) {
      // FIXME: Invalid target name, produce an error.
      assert(0 && "FIXME: invalid target");
      abort();
    }

    // Create the rule to construct this target.
    Target* target = it->second.get();
    return std::unique_ptr<Rule>(new BuildSystemRule(
      keyData,
      /*signature=*/{},
      /*Action=*/ [target](BuildEngine& engine) -> Task* {
        return new TargetTask(*target);
      },
      /*IsValid=*/ [target](BuildEngine& engine, const Rule& rule,
                            const ValueType& value) -> bool {
        return TargetTask::isResultValid(
            engine, *target, BuildValue::fromData(value));
      }
    ));
  }
  }

  assert(0 && "invalid key type");
  abort();
}

void BuildSystemEngineDelegate::determinedRuleNeedsToRun(Rule* ruleNeedingToRun, Rule::RunReason reason, Rule* inputRule) {
  return getBuildSystem().getDelegate().determinedRuleNeedsToRun(ruleNeedingToRun, reason, inputRule);
}

bool BuildSystemEngineDelegate::shouldResolveCycle(const std::vector<Rule*>& cycle,
                                                     Rule* candidateRule,
                                                     Rule::CycleAction action) {
  return static_cast<BuildSystemFrontendDelegate*>(&getBuildSystem().getDelegate())->shouldResolveCycle(cycle, candidateRule, action);
}

void BuildSystemEngineDelegate::cycleDetected(const std::vector<Rule*>& cycle) {
  // Track that the build has been aborted.
  getBuildSystem().setBuildWasAborted(true);
  static_cast<BuildSystemFrontendDelegate*>(&getBuildSystem().getDelegate())->cycleDetected(cycle);
}

void BuildSystemEngineDelegate::error(const Twine& message) {
  system.error(system.getMainFilename(), message);
}

#pragma mark - BuildSystemImpl implementation

std::unique_ptr<BuildNode>
BuildSystemImpl::lookupNode(StringRef name, bool isImplicit) {
  if (name.endswith("/")) {
    return BuildNode::makeDirectory(name);
  }

  if (!name.empty() && name[0] == '<' && name.back() == '>') {
    return BuildNode::makeVirtual(name);
  }

  return BuildNode::makePlain(name);
}

llvm::Optional<BuildValue> BuildSystemImpl::build(BuildKey key) {

  if (basic::sys::raiseOpenFileLimit() != 0) {
    error(getMainFilename(), "failed to raise open file limit");
    return None;
  }

  // Build the target.
  buildWasAborted = false;
  auto result = buildEngine.build(key.toData());
    
  // Clear out the shell handlers, as we do not want to hold on to them across
  // multiple builds.
  shellHandlers.clear();

  if (buildWasAborted)
    return None;
  return BuildValue::fromData(result);
}

bool BuildSystemImpl::build(StringRef target) {
  // The build description must have been loaded.
  if (!buildDescription) {
    error(getMainFilename(), "no build description loaded");
    return false;
  }

  // If target name is not passed then we try to load the default target name
  // from manifest file
  if (target.empty()) {
    target = getBuildDescription().getDefaultTarget();
  }

  // Validate the target name.
  auto& targets = getBuildDescription().getTargets();
  if (targets.find(target) == targets.end()) {
    error(getMainFilename(), "No target named '" + target + "' in build description");
    return false;
  }

  return build(BuildKey::makeTarget(target)).hasValue();
}

#pragma mark - PhonyTool implementation

class PhonyCommand : public ExternalCommand {
public:
  using ExternalCommand::ExternalCommand;

  virtual bool shouldShowStatus() override { return false; }

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << getName();
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << getName();
  }

  virtual void startExternalCommand(BuildSystem&, TaskInterface) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(
      BuildSystem&,
      TaskInterface,
      QueueJobContext* context,
      llvm::Optional<ProcessCompletionFn> completionFn) override {
    // Nothing needs to be done for phony commands.
    if (completionFn.hasValue())
      completionFn.getValue()(ProcessStatus::Succeeded);
  }

  virtual BuildValue getResultForOutput(Node* node, const BuildValue& value) override {
    // If the node is virtual, the output is always a virtual input value,
    // regardless of the actual build value.
    //
    // This is a special case for phony commands, to avoid them incorrectly
    // propagating failed/cancelled states onwards to downstream commands when
    // they are being used only for ordering purposes.
    auto buildNode = static_cast<BuildNode*>(node);
    if (buildNode->isVirtual() && !buildNode->isCommandTimestamp()) {
      return BuildValue::makeVirtualInput();
    }

    // Otherwise, delegate to the inherited implementation.
    return ExternalCommand::getResultForOutput(node, value);
  }
};

class PhonyTool : public Tool {
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported configuration attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported configuration attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<PhonyCommand>(name);
  }
};

#pragma mark - ShellTool implementation

class ShellTool : public Tool {
private:
  bool controlEnabled = true;

public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "control-enabled") {
      if (value != "true" && value != "false") {
        ctx.error("invalid value: '" + value + "' for attribute '" +
                  name + "'");
        return false;
      }
      controlEnabled = (value == "true");
    } else {
      ctx.error("unexpected attribute: '" + name + "'");
      return false;
    }
    return true;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<ShellCommand>(name, controlEnabled);
  }
};

#pragma mark - ClangTool implementation

class ClangShellCommand : public ExternalCommand {
  /// The compiler command to invoke.
  std::vector<StringRef> args;
  
  /// The path to the dependency output file, if used.
  std::string depsPath;
  
  virtual CommandSignature getSignature() const override {
    return ExternalCommand::getSignature()
        .combine(args);
  }

  bool processDiscoveredDependencies(TaskInterface ti,
                                     QueueJobContext* context) {
    // Read the dependencies file.
    auto input = getBuildSystem(ti).getFileSystem().getFileContents(depsPath);
    if (!input) {
      getBuildSystem(ti).getDelegate().commandHadError(this,
                     "unable to open dependencies file (" + depsPath + ")");
      return false;
    }

    // Parse the output.
    //
    // We just ignore the rule, and add any dependency that we encounter in the
    // file.
    struct DepsActions : public core::MakefileDepsParser::ParseActions {
      TaskInterface ti;
      ClangShellCommand* command;
      unsigned numErrors{0};

      DepsActions(TaskInterface ti,
                  ClangShellCommand* command)
          : ti(ti), command(command) {}

      virtual void error(StringRef message, uint64_t position) override {
        getBuildSystem(ti).getDelegate().commandHadError(command,
                       "error reading dependency file '" + command->depsPath +
                       "': " + message.str());
        ++numErrors;
      }

      virtual void actOnRuleDependency(StringRef dependency,
                                       StringRef unescapedWord) override {
        ti.discoveredDependency(BuildKey::makeNode(unescapedWord).toData());
        getBuildSystem(ti).getDelegate().commandFoundDiscoveredDependency(command, unescapedWord,
                                                                          DiscoveredDependencyKind::Input);
      }

      virtual void actOnRuleStart(StringRef name,
                                  StringRef unescapedWord) override {}

      virtual void actOnRuleEnd() override {}
    };

    DepsActions actions(ti, this);
    core::MakefileDepsParser(input->getBuffer(), actions, false).parse();
    return actions.numErrors == 0;
  }

public:
  using ExternalCommand::ExternalCommand;

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << getDescription();
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream os(result);
    bool first = true;
    for (const auto& arg: args) {
      if (!first) os << " ";
      first = false;
      basic::appendShellEscapedString(os, arg);
    }
  }
  
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "args") {
      // When provided as a scalar string, we default to executing using the
      // shell.
      args.clear();
      args.push_back(ctx.getDelegate().getInternedString(DefaultShellPath));
      args.push_back(ctx.getDelegate().getInternedString("-c"));
      args.push_back(ctx.getDelegate().getInternedString(value));
    } else if (name == "deps") {
      depsPath = value;
    } else {
      return ExternalCommand::configureAttribute(ctx, name, value);
    }

    return true;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    if (name == "args") {
      args.clear();
      args.reserve(values.size());
      for (auto arg: values) {
        args.emplace_back(ctx.getDelegate().getInternedString(arg));
      }
    } else {
        return ExternalCommand::configureAttribute(ctx, name, values);
    }

    return true;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    return ExternalCommand::configureAttribute(ctx, name, values);
  }

  virtual void startExternalCommand(BuildSystem&, TaskInterface) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(BuildSystem&,
                                      TaskInterface ti,
                                      QueueJobContext* context,
                                      llvm::Optional<ProcessCompletionFn> completionFn) override {
    // Execute the command.
    ti.spawn(context, args, {}, {true}, {[this, ti, completionFn](ProcessResult result) mutable {

      if (result.status != ProcessStatus::Succeeded) {
        // If the command failed, there is no need to gather dependencies.
        if (completionFn.hasValue())
          completionFn.getValue()(result);
        return;
      }

      // Otherwise, collect the discovered dependencies, if used.
      if (!depsPath.empty()) {
        ti.spawn({ this, [this, ti, completionFn, result](QueueJobContext* context) mutable {
          if (!processDiscoveredDependencies(ti, context)) {
            // If we were unable to process the dependencies output, report a
            // failure.
            if (completionFn.hasValue())
              completionFn.getValue()(ProcessStatus::Failed);
            return;
          }
          if (completionFn.hasValue())
            completionFn.getValue()(result);
        }}, QueueJobPriority::High);
        return;
      }

      if (completionFn.hasValue())
        completionFn.getValue()(result);
    }});
  }
};

class ClangTool : public Tool {
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<ClangShellCommand>(name);
  }
};

#pragma mark - SwiftCompilerTool implementation

class SwiftGetVersionCommand : public Command {
  std::string executable;
  
public:
  SwiftGetVersionCommand(const BuildKey& key)
      : Command("swift-get-version"), executable(key.getCustomTaskData()) {
  }

  // FIXME: Should create a CustomCommand class, to avoid all the boilerplate
  // required implementations.

  bool shouldShowStatus() override { return false; }
    
  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << "Checking Swift Compiler Version";
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << '"' << executable << '"'
                                      << " --version";
  }

  virtual void configureDescription(const ConfigureContext&,
                                    StringRef value) override { }
  virtual void configureInputs(const ConfigureContext&,
                               const std::vector<Node*>& value) override { }
  virtual void configureOutputs(const ConfigureContext&,
                                const std::vector<Node*>& value) override { }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual BuildValue getResultForOutput(Node* node,
                                        const BuildValue& value) override {
    // This method should never be called on a custom command.
    llvm_unreachable("unexpected");
    return BuildValue::makeInvalid();
  }
  
  virtual bool isResultValid(BuildSystem&, const BuildValue& value) override {
    // Always rebuild this task.
    return false;
  }

  virtual void start(BuildSystem&, TaskInterface ti) override { }
  virtual void providePriorValue(BuildSystem&, TaskInterface ti,
                                 const BuildValue&) override { }
  virtual void provideValue(BuildSystem&,
                            TaskInterface ti,
                            uintptr_t inputID,
                            const BuildValue& value) override { }

  virtual void execute(BuildSystem&,
                       TaskInterface ti,
                       QueueJobContext* context,
                       ResultFn resultFn) override {
    // Construct the command line used to query the swift compiler version.
    //
    // FIXME: Need a decent subprocess interface.
    SmallString<256> command;
    llvm::raw_svector_ostream commandOS(command);
    commandOS << basic::shellEscaped(executable);
    commandOS << " " << "--version";
#if defined(_WIN32)
    // FIXME:  cmd.exe uses different syntax for I/O redirection to null.
    commandOS << " 2>NUL";
#else
    commandOS << " " << "2>/dev/null";
#endif

    // Read the result.
    FILE *fp = basic::sys::popen(commandOS.str().str().c_str(), "r");
    SmallString<4096> result;
    if (fp) {
      char buf[4096];
      for (;;) {
        ssize_t numRead = fread(buf, 1, sizeof(buf), fp);
        if (numRead == 0) {
          // FIXME: Error handling.
          break;
        }
        result.append(StringRef(buf, numRead));
      }
      basic::sys::pclose(fp);
    }

    // For now, we can get away with just encoding this as a successful
    // command and relying on the signature to detect changes.
    //
    // FIXME: We should support BuildValues with arbitrary payloads.
    resultFn(BuildValue::makeSuccessfulCommandWithOutputSignature(
       basic::FileInfo{}, CommandSignature(result)));
  }
};

class SwiftCompilerShellCommand : public ExternalCommand {
  /// The compiler command to invoke.
  std::string executable = "swiftc";
  
  /// The name of the module.
  std::string moduleName;
  
  /// Module aliases used to build this module. For example, if
  /// `-module-alias Foo=Bar` was passed, and source files in
  /// this module references `Foo`, e.g.  `import Foo`, the `Bar`
  /// module will loaded and used to compile this module.
  std::vector<std::string> moduleAliases;

  /// The path of the output module.
  std::string moduleOutputPath;

  /// The list of sources (combined).
  std::vector<std::string> sourcesList;

  /// The list of objects (combined).
  std::vector<std::string> objectsList;

  /// The list of import paths (combined).
  std::vector<std::string> importPaths;

  /// The directory in which to store temporary files.
  std::string tempsPath;

  /// Additional arguments, as a string.
  std::vector<std::string> otherArgs;

  /// Whether the sources are part of a library or not.
  bool isLibrary = false;
  
  /// Whether to enable -whole-module-optimization.
  bool enableWholeModuleOptimization = false;

  /// Enables multi-threading with the thread count if > 0.
  ///
  /// Note: This is only used when whole module optimization is enabled.
  std::string numThreads = "0";

  virtual CommandSignature getSignature() const override {
    return ExternalCommand::getSignature()
        .combine(executable)
        .combine(moduleName)
        .combine(moduleAliases)
        .combine(moduleOutputPath)
        .combine(sourcesList)
        .combine(objectsList)
        .combine(importPaths)
        .combine(tempsPath)
        .combine(otherArgs)
        .combine(isLibrary);
  }

  /// Get the path to use for the output file map.
  void getOutputFileMapPath(SmallVectorImpl<char>& result) const {
    llvm::sys::path::append(result, tempsPath, "output-file-map.json");
  }
    
  /// Compute the complete set of command line arguments to invoke swift with.
  void constructCommandLineArgs(StringRef outputFileMapPath,
                                std::vector<StringRef>& result) const {
    result.push_back(executable);
    result.push_back("-module-name");
    result.push_back(moduleName);

    for (const auto& nameAndAlias: moduleAliases) {
      // E.g. `-module-alias Foo=Bar`
      result.push_back("-module-alias");
      result.push_back(nameAndAlias);
    }

    result.push_back("-emit-dependencies");
    if (!moduleOutputPath.empty()) {
      result.push_back("-emit-module");
      result.push_back("-emit-module-path");
      result.push_back(moduleOutputPath);
    }
    result.push_back("-output-file-map");
    result.push_back(outputFileMapPath);
    if (isLibrary) {
      result.push_back("-parse-as-library");
    }
    if (enableWholeModuleOptimization) {
      result.push_back("-whole-module-optimization");
      result.push_back("-num-threads");
      result.push_back(numThreads);
    } else {
      result.push_back("-incremental");
    }
    result.push_back("-c");
    for (const auto& source: sourcesList) {
      result.push_back(source);
    }
    for (const auto& import: importPaths) {
      result.push_back("-I");
      result.push_back(import);
    }
    for (const auto& arg: otherArgs) {
      result.push_back(arg);
    }
  }
  
public:
  using ExternalCommand::ExternalCommand;

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
      llvm::raw_svector_ostream(result)
        << "Compiling Swift Module '" << moduleName
        << "' (" << sourcesList.size() << " sources)";
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    SmallString<64> outputFileMapPath;
    getOutputFileMapPath(outputFileMapPath);
    
    std::vector<StringRef> commandLine;
    constructCommandLineArgs(outputFileMapPath, commandLine);
    
    llvm::raw_svector_ostream os(result);
    bool first = true;
    for (const auto& arg: commandLine) {
      if (!first) os << " ";
      first = false;
      // FIXME: This isn't correct, we need utilities for doing shell quoting.
      if (arg.find(' ') != StringRef::npos) {
        os << '"' << arg << '"';
      } else {
        os << arg;
      }
    }
  }
  
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "executable") {
      executable = value;
    } else if (name == "module-name") {
      moduleName = value;
    } else if (name == "module-output-path") {
      moduleOutputPath = value;
    } else if (name == "sources") {
      SmallVector<StringRef, 32> sources;
      StringRef(value).split(sources, " ", /*MaxSplit=*/-1,
                             /*KeepEmpty=*/false);
      sourcesList = std::vector<std::string>(sources.begin(), sources.end());
    } else if (name == "objects") {
      SmallVector<StringRef, 32> objects;
      StringRef(value).split(objects, " ", /*MaxSplit=*/-1,
                             /*KeepEmpty=*/false);
      objectsList = std::vector<std::string>(objects.begin(), objects.end());
    } else if (name == "import-paths") {
      SmallVector<StringRef, 32> imports;
      StringRef(value).split(imports, " ", /*MaxSplit=*/-1,
                             /*KeepEmpty=*/false);
      importPaths = std::vector<std::string>(imports.begin(), imports.end());
    } else if (name == "temps-path") {
      tempsPath = value;
    } else if (name == "is-library") {
      if (!configureBool(ctx, isLibrary, name, value))
        return false;
    } else if (name == "enable-whole-module-optimization") {
      if (!configureBool(ctx, enableWholeModuleOptimization, name, value))
        return false;
    } else if (name == "num-threads") {
      int numThreadsInt = 0;
      if (value.getAsInteger(10, numThreadsInt)) {
        ctx.error("'" + name + "' should be an int.");
        return false;
      }
      if (numThreadsInt < 0) {
        ctx.error("'" + name + "' should be greater than or equal to zero.");
        return false;
      }
      numThreads = value;
    } else if (name == "other-args") {
      SmallVector<StringRef, 32> args;
      StringRef(value).split(args, " ", /*MaxSplit=*/-1,
                             /*KeepEmpty=*/false);
      otherArgs = std::vector<std::string>(args.begin(), args.end());
    } else {
      return ExternalCommand::configureAttribute(ctx, name, value);
    }

    return true;
  }

  // Extracts and stores the bool value of an attribute inside "to" variable.
  // Returns true on success and false on error.
  bool configureBool(const ConfigureContext& ctx, bool& to, StringRef name, StringRef value) {
    if (value != "true" && value != "false") {
      ctx.error("invalid value: '" + value + "' for attribute '" +
          name + "'");
      return false;
    }
    to = value == "true";
    return true;
  }

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    if (name == "sources") {
      sourcesList = std::vector<std::string>(values.begin(), values.end());
    } else if (name == "objects") {
      objectsList = std::vector<std::string>(values.begin(), values.end());
    } else if (name == "import-paths") {
      importPaths = std::vector<std::string>(values.begin(), values.end());
    } else if (name == "other-args") {
      otherArgs = std::vector<std::string>(values.begin(), values.end());
    } else if (name == "module-aliases") {
      moduleAliases = std::vector<std::string>(values.begin(), values.end());
    } else {
      return ExternalCommand::configureAttribute(ctx, name, values);
    }
    
    return true;
  }

  bool writeOutputFileMap(TaskInterface ti,
                          StringRef outputFileMapPath,
                          std::vector<std::string>& depsFiles_out) const {
    assert(sourcesList.size() == objectsList.size());

    SmallString<16> data;
    std::error_code ec;
    llvm::raw_fd_ostream os(outputFileMapPath, ec,
                            llvm::sys::fs::OpenFlags::F_Text);
    if (ec) {
      getBuildSystem(ti).getDelegate().commandHadError((Command*)this,
                      "unable to create output file map: '" + outputFileMapPath.str() + "'");
      return false;
    }

    os << "{\n";

    // Write the master file dependencies entry.
    SmallString<16> masterDepsPath;
    llvm::sys::path::append(masterDepsPath, tempsPath, "master.swiftdeps");
    os << "  \"\": {\n";
    if (enableWholeModuleOptimization) {
      SmallString<16> depsPath;
      llvm::sys::path::append(depsPath, tempsPath, moduleName + ".d");
      depsFiles_out.push_back(depsPath.str());
      SmallString<16> object;
      llvm::sys::path::append(object, tempsPath, moduleName + ".o");
      os << "    \"dependencies\": \"" << escapeForJSON(depsPath) << "\",\n";
      os << "    \"object\": \"" << escapeForJSON(object) << "\",\n";
    }
    os << "    \"swift-dependencies\": \"" << escapeForJSON(masterDepsPath) << "\"\n";
    os << "  },\n";

    // Write out the entries for each source file.
    for (unsigned i = 0; i != sourcesList.size(); ++i) {
      auto source = sourcesList[i];
      auto object = objectsList[i];
      auto objectDir = llvm::sys::path::parent_path(object);
      auto sourceStem = llvm::sys::path::stem(source);
      SmallString<16> partialModulePath;
      llvm::sys::path::append(partialModulePath, objectDir,
                              sourceStem + "~partial.swiftmodule");
      SmallString<16> swiftDepsPath;
      llvm::sys::path::append(swiftDepsPath, objectDir,
                              sourceStem + ".swiftdeps");

      os << "  \"" << escapeForJSON(source) << "\": {\n";
      if (!enableWholeModuleOptimization) {
        SmallString<16> depsPath;
        llvm::sys::path::append(depsPath, objectDir, sourceStem + ".d");
        os << "    \"dependencies\": \"" << escapeForJSON(depsPath) << "\",\n";
        depsFiles_out.push_back(depsPath.str());
      }
      os << "    \"object\": \"" << escapeForJSON(object) << "\",\n";
      os << "    \"swiftmodule\": \"" << escapeForJSON(partialModulePath) << "\",\n";
      os << "    \"swift-dependencies\": \"" << escapeForJSON(swiftDepsPath) << "\"\n";
      os << "  }" << ((i + 1) < sourcesList.size() ? "," : "") << "\n";
    }

    os << "}\n";

    os.close();

    return true;
  }

  bool processDiscoveredDependencies(TaskInterface ti, StringRef depsPath) {
    // Read the dependencies file.
    auto input = getBuildSystem(ti).getFileSystem().getFileContents(depsPath);
    if (!input) {
      getBuildSystem(ti).getDelegate().commandHadError(this,
                     "unable to open dependencies file (" + depsPath.str() + ")");
      return false;
    }

    // Parse the output.
    //
    // We just ignore the rule, and add any dependency that we encounter in the
    // file.
    struct DepsActions : public core::MakefileDepsParser::ParseActions {
      TaskInterface ti;
      StringRef depsPath;
      Command* command;
      unsigned numErrors{0};
      unsigned ruleNumber{0};
      
      DepsActions(TaskInterface ti,
                  StringRef depsPath, Command* command)
          : ti(ti), depsPath(depsPath) {}

      virtual void error(StringRef message, uint64_t position) override {
        getBuildSystem(ti).getDelegate().commandHadError(command,
                       "error reading dependency file '" + depsPath.str() +
                       "': " + message.str());
        ++numErrors;
      }

      virtual void actOnRuleDependency(StringRef dependency,
                                       StringRef unescapedWord) override {
        // Only process dependencies for the first rule (the output file), the
        // rest are identical.
        if (ruleNumber == 0) {
          ti.discoveredDependency(BuildKey::makeNode(unescapedWord).toData());
          getBuildSystem(ti).getDelegate().commandFoundDiscoveredDependency(command, unescapedWord,
                                                                            DiscoveredDependencyKind::Input);
        }
      }

      virtual void actOnRuleStart(StringRef name,
                                  StringRef unescapedWord) override {}

      virtual void actOnRuleEnd() override {
        ++ruleNumber;
      }
    };

    DepsActions actions(ti, depsPath, this);
    core::MakefileDepsParser(input->getBuffer(), actions, false).parse();
    return actions.numErrors == 0;
  }

  /// Overridden start to also introduce a dependency on the Swift compiler
  /// version.
  virtual void start(BuildSystem& system, TaskInterface ti) override {
    ExternalCommand::start(system, ti);
    
    // The Swift compiler version is also an input.
    //
    // FIXME: We need to fix the input ID situation, this is not extensible. We
    // either have to build a registration of the custom tasks so they can divy
    // up the input ID namespace, or we should just use the keys. Probably move
    // to just using the keys, unless there is a place where that is really not
    // cheap.
    auto getVersionKey = BuildKey::makeCustomTask(
        "swift-get-version", executable);
    ti.request(getVersionKey.toData(), core::BuildEngine::kMaximumInputID - 1);
  }

  /// Overridden to access the Swift compiler version.
  virtual void provideValue(BuildSystem& system,
                            TaskInterface ti,
                            uintptr_t inputID,
                            const BuildValue& value) override {
    // We can ignore the 'swift-get-version' input, it is just used to detect
    // that we need to rebuild.
    if (inputID == core::BuildEngine::kMaximumInputID - 1) {
      return;
    }
    
    ExternalCommand::provideValue(system, ti, inputID, value);
  }

  virtual void startExternalCommand(BuildSystem&, TaskInterface) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface ti,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(
      BuildSystem& system,
      TaskInterface ti,
      QueueJobContext* context,
      llvm::Optional<ProcessCompletionFn> completionFn) override {
    // FIXME: Need to add support for required parameters.
    if (sourcesList.empty()) {
      system.getDelegate().error("", {}, "no configured 'sources'");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }
    if (objectsList.empty()) {
      system.getDelegate().error("", {}, "no configured 'objects'");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }
    if (moduleName.empty()) {
      system.getDelegate().error("", {}, "no configured 'module-name'");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }
    if (tempsPath.empty()) {
      system.getDelegate().error("", {}, "no configured 'temps-path'");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }

    if (sourcesList.size() != objectsList.size()) {
      system.getDelegate().error(
          "", {}, "'sources' and 'objects' are not the same size");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }

    // Ensure the temporary directory exists.
    //
    // We ignore failures here, and just let things that depend on this fail.
    //
    // FIXME: This should really be done using an additional implicit input, so
    // it only happens once per build.
    (void) system.getFileSystem().createDirectories(tempsPath);
 
    SmallString<64> outputFileMapPath;
    getOutputFileMapPath(outputFileMapPath);
    
    // Form the complete command.
    std::vector<StringRef> commandLine;
    constructCommandLineArgs(outputFileMapPath, commandLine);

    // Write the output file map.
    std::vector<std::string> depsFiles;
    if (!writeOutputFileMap(ti, outputFileMapPath, depsFiles)) {
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }

    // Execute the command.
    auto result = ti.spawn(context, commandLine);

    if (result != ProcessStatus::Succeeded) {
      // If the command failed, there is no need to gather dependencies.
      if (completionFn.hasValue())
        completionFn.getValue()(result);
      return;
    }

    // Load all of the discovered dependencies.
    ti.spawn({ this, [this, ti, completionFn, result, depsFiles](QueueJobContext* context) mutable {
      for (const auto& depsPath: depsFiles) {
        if (!processDiscoveredDependencies(ti, depsPath)) {
          if (completionFn.hasValue())
            completionFn.getValue()(ProcessStatus::Failed);
          return;
        }
      }
      if (completionFn.hasValue())
        completionFn.getValue()(result);
    }}, basic::QueueJobPriority::High);
  }
};

class SwiftCompilerTool : public Tool {
public:
  SwiftCompilerTool(StringRef name) : Tool(name) {}

  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name, StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<SwiftCompilerShellCommand>(name);
  }

  virtual std::unique_ptr<Command> createCustomCommand(
      const BuildKey& key) override {
    if (key.getCustomTaskName() == "swift-get-version" ) {
      return llvm::make_unique<SwiftGetVersionCommand>(key);
    }

    return nullptr;
  }
};


#pragma mark - MkdirTool implementation

class MkdirCommand : public ExternalCommand {
  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << getDescription();
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream os(result);
    os << "mkdir -p ";
    // FIXME: This isn't correct, we need utilities for doing shell quoting.
    if (StringRef(getOutputs()[0]->getName()).find(' ') != StringRef::npos) {
      os << '"' << getOutputs()[0]->getName() << '"';
    } else {
      os << getOutputs()[0]->getName();
    }
  }

  virtual bool isResultValid(BuildSystem& system,
                             const BuildValue& value) override {
    // If the prior value wasn't for a successful command, recompute.
    if (!value.isSuccessfulCommand())
      return false;

    // Otherwise, the result is valid if the directory still exists.
    auto info = getOutputs()[0]->getFileInfo(
        system.getFileSystem());
    if (info.isMissing())
      return false;

    // If the item is not a directory, it needs to be recreated.
    if (!info.isDirectory())
      return false;

    // FIXME: We should strictly enforce the integrity of this validity routine
    // by ensuring that the build result for this command does not fully encode
    // the file info, but rather just encodes its success. As is, we are leaking
    // out the details of the file info (like the timestamp), but not rerunning
    // when they change. This is by design for this command, but it would still
    // be nice to be strict about it.
    
    return true;
  }
  
  virtual void startExternalCommand(BuildSystem&, TaskInterface ti) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface ti,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(
      BuildSystem& system,
      TaskInterface ti,
      QueueJobContext* context,
      llvm::Optional<ProcessCompletionFn> completionFn) override {
    auto output = getOutputs()[0];
    if (!system.getFileSystem().createDirectories(
            output->getName())) {
      getBuildSystem(ti).getDelegate().commandHadError(this,
                     "unable to create directory '" + output->getName().str() + "'");
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }
    if (completionFn.hasValue())
      completionFn.getValue()(ProcessStatus::Succeeded);
  }
  
public:
  using ExternalCommand::ExternalCommand;
};

class MkdirTool : public Tool {

public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    auto res = llvm::make_unique<MkdirCommand>(name);
    return res;
  }
};

#pragma mark - SymlinkTool implementation

class SymlinkCommand : public Command {
  /// The path of the actual symbolic link to create, if different from the
  /// output node.
  std::string linkOutputPath;
  
  /// The command description.
  std::string description;

  /// The contents to write at the output path.
  std::string contents;

  /// Get the destination path.
  StringRef getActualOutputPath() const {
    return linkOutputPath.empty() ? outputs[0]->getName() :
      StringRef(linkOutputPath);
  }
  
  virtual CommandSignature getSignature() const override {
    CommandSignature code(outputs[0]->getName());
    code = code.combine(contents);
    for (const auto* input: inputs) {
      code = code.combine(input->getName());
    }
    return code;
  }

  virtual void configureDescription(const ConfigureContext&,
                                    StringRef value) override {
    description = value;
  }

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << description;
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream os(result);
    os << "ln -sfh ";
    StringRef outputPath = getActualOutputPath();
    if (outputs.empty() || !outputPath.empty()) {
      // FIXME: This isn't correct, we need utilities for doing shell quoting.
      if (outputPath.find(' ') != StringRef::npos) {
        os << '"' << outputPath << '"';
      } else {
        os << outputPath;
      }
    } else {
      os << "<<<missing output>>>";
    }
    os << ' ';
    // FIXME: This isn't correct, we need utilities for doing shell quoting.
    if (StringRef(contents).find(' ') != StringRef::npos) {
      os << '"' << contents << '"';
    } else {
      os << contents;
    }
  }
  
  virtual void configureInputs(const ConfigureContext& ctx,
                               const std::vector<Node*>& value) override {
    inputs.reserve(value.size());
    for (auto* node: value) {
      inputs.emplace_back(static_cast<BuildNode*>(node));
    }
  }

  virtual void configureOutputs(const ConfigureContext& ctx,
                                const std::vector<Node*>& value) override {
    if (value.size() == 1) {
      outputs.push_back(static_cast<BuildNode*>(value[0]));
    } else if (value.empty()) {
      ctx.error("missing declared output");
    } else {
      ctx.error("unexpected explicit output: '" + value[1]->getName() + "'");
    }
  }
  
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "contents") {
      contents = value;
      return true;
    } else if (name == "link-output-path") {
      linkOutputPath = value;
      return true;
    } else if (name == "repair-via-ownership-analysis") {
      if (value == "true") {
        repairViaOwnershipAnalysis = true;
        return true;
      } else if (value == "false") {
        repairViaOwnershipAnalysis = false;
        return true;
      } else {
        ctx.error("invalid value for attribute: '" + name + "'");
        return false;
      }
    } else {
      ctx.error("unexpected attribute: '" + name + "'");
      return false;
    }
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual BuildValue getResultForOutput(Node* node,
                                        const BuildValue& value) override {
    // If the value was a failed command, propagate the failure.
    if (value.isFailedCommand() || value.isPropagatedFailureCommand() ||
        value.isCancelledCommand())
      return BuildValue::makeFailedInput();
    if (value.isSkippedCommand())
      return BuildValue::makeSkippedCommand();

    // Otherwise, we should have a successful command -- return the actual
    // result for the output.
    assert(value.isSuccessfulCommand());

    auto info = value.getOutputInfo();
    if (info.isMissing())
        return BuildValue::makeMissingOutput();
    return BuildValue::makeExistingInput(info);
  }

  virtual bool isResultValid(BuildSystem& system,
                             const BuildValue& value) override {
    // It is an error if this command isn't configured properly.
    StringRef outputPath = getActualOutputPath();
    if (outputs.empty() || outputPath.empty())
      return false;

    // If the prior value wasn't for a successful command, recompute.
    if (!value.isSuccessfulCommand())
      return false;

    // If the prior command doesn't look like one for a link, recompute.
    if (value.getNumOutputs() != 1)
      return false;

    // Otherwise, assume the result is valid if its link status matches the
    // previous one.
    auto info = system.getFileSystem().getLinkInfo(outputPath);
    if (info.isMissing())
      return false;

    return info == value.getOutputInfo();
  }
  
  virtual void start(BuildSystem&, TaskInterface ti) override {
    // The command itself takes no inputs, so just treat any declared inputs as
    // "must follow" directives.
    //
    // FIXME: We should make this explicit once we have actual support for must
    // follow inputs.
    for (auto it = inputs.begin(), ie = inputs.end(); it != ie; ++it) {
      ti.mustFollow(BuildKey::makeNode(*it).toData());
    }
  }

  virtual void providePriorValue(BuildSystem&, TaskInterface ti,
                                 const BuildValue& value) override {
    // Ignored.
  }

  virtual void provideValue(BuildSystem&, TaskInterface ti,
                            uintptr_t inputID,
                            const BuildValue& value) override {
    assert(0 && "unexpected API call");
  }

  virtual void execute(BuildSystem& system,
                       TaskInterface ti,
                       QueueJobContext* context,
                       ResultFn resultFn) override {
    // It is an error if this command isn't configured properly.
    StringRef outputPath = getActualOutputPath();
    if (outputs.empty() || outputPath.empty()) {
      resultFn(BuildValue::makeFailedCommand());
      return;
    }

    auto& fs = system.getFileSystem();

    // Create the directory containing the symlink, if necessary.
    //
    // FIXME: Shared behavior with ExternalCommand.
    {
      auto parent = llvm::sys::path::parent_path(outputPath);
      if (!parent.empty()) {
        (void) fs.createDirectories(parent);
      }
    }

    // Create the symbolic link (note that despite the poorly chosen LLVM
    // name, this is a symlink).
    system.getDelegate().commandStarted(this);
    auto success = true;
    if (!fs.createSymlink(contents, outputPath.str())) {
      // On failure, we attempt to unlink the file and retry.
      fs.remove(outputPath.str());

      if (!fs.createSymlink(contents, outputPath.str())) {
        getBuildSystem(ti).getDelegate().commandHadError(this,
                       "unable to create symlink at '" + outputPath.str() + "'");
        success = false;
      }
    }
    system.getDelegate().commandFinished(this, success ? ProcessStatus::Succeeded : ProcessStatus::Failed);
    
    // Process the result.
    if (!success) {
      resultFn(BuildValue::makeFailedCommand());
      return;
    }

    // Capture the *link* information of the output.
    FileInfo outputInfo = fs.getLinkInfo(outputPath);
      
    // Complete with a successful result.
    resultFn(BuildValue::makeSuccessfulCommand(outputInfo));
  }

public:
  using Command::Command;
};

class SymlinkTool : public Tool {
  bool repairViaOwnershipAnalysis = false;
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "repair-via-ownership-analysis") {
      if (value == "true") {
        repairViaOwnershipAnalysis = true;
        return true;
      } else if(value == "false") {
        repairViaOwnershipAnalysis = false;
        return true;
      } else {
        ctx.error("invalid value for attribute: '" + name + "'");
        return false;
      }
    } else {
      ctx.error("unexpected attribute: '" + name + "'");
      return false;
    }
  }

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    auto res = llvm::make_unique<SymlinkCommand>(name);
    res->repairViaOwnershipAnalysis = repairViaOwnershipAnalysis;
    return res;
  }
};

#pragma mark - ArchiveTool implementation

class ArchiveShellCommand : public ExternalCommand {

  std::string archiveName;
  std::vector<std::string> archiveInputs;

  virtual void startExternalCommand(BuildSystem&, TaskInterface ti) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface ti,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(
      BuildSystem&,
      TaskInterface ti,
      QueueJobContext* context,
      llvm::Optional<ProcessCompletionFn> completionFn) override {
    // First delete the current archive
    // TODO instead insert, update and remove files from the archive
    if (llvm::sys::fs::remove(archiveName, /*IgnoreNonExisting*/ true)) {
      if (completionFn.hasValue())
        completionFn.getValue()(ProcessStatus::Failed);
      return;
    }

    // Create archive
    auto args = getArgs();
    ti.spawn(context,
             std::vector<StringRef>(args.begin(), args.end()),
             {}, {true},
             {[completionFn](ProcessResult result) {
      if (completionFn.hasValue())
        completionFn.getValue()(result);
    }});
  }

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    if (getDescription().empty()) {
      llvm::raw_svector_ostream(result) << "Archiving " + archiveName;
    } else {
      llvm::raw_svector_ostream(result) << getDescription();
    }
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream stream(result);
    bool first = true;
    for (const auto& arg: getArgs()) {
      if (!first) {
        stream << " ";
      }
      first = false;
      stream << arg;
    }
  }
  
  virtual void configureInputs(const ConfigureContext& ctx,
                                const std::vector<Node*>& value) override {
    ExternalCommand::configureInputs(ctx, value);

    for (const auto& input: getInputs()) {
      if (!input->isVirtual()) {
        archiveInputs.push_back(input->getName());
      }
    }
    if (archiveInputs.empty()) {
      ctx.error("missing expected input");
    }
  }
  
  virtual void configureOutputs(const ConfigureContext& ctx,
                                const std::vector<Node*>& value) override {
    ExternalCommand::configureOutputs(ctx, value);

    for (const auto& output: getOutputs()) {
      if (!output->isVirtual()) {
        if (archiveName.empty()) {
          archiveName = output->getName();
        } else {
          ctx.error("unexpected explicit output: " + output->getName());
        }
      }
    }
    if (archiveName.empty()) {
      ctx.error("missing expected output");
    }
  }

  std::vector<std::string> getArgs() const {
    std::vector<std::string> args;
    if (const char *ar = std::getenv("AR"))
      args.push_back(std::string(ar));
    else
      args.push_back("ar");
    args.push_back("cr");
    args.push_back(archiveName);
    args.insert(args.end(), archiveInputs.begin(), archiveInputs.end());
    return args;
  }

public:
  using ExternalCommand::ExternalCommand;
};

class ArchiveTool : public Tool {
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<ArchiveShellCommand>(name);
  }
};

#pragma mark - SharedLibraryTool implementation

class SharedLibraryShellCommand : public ExternalCommand {

  // Defaults compilers. Can be overwritten on the build config is required.
  std::string executable = "";
  std::string sharedLibName;
  std::string compilerStyle;
  std::vector<std::string> sharedLibInputs;
  /// Additional arguments, as a string.
  std::vector<std::string> otherArgs;

  virtual void startExternalCommand(BuildSystem&, TaskInterface ti) override {
    return;
  }

  virtual void provideValueExternalCommand(
      BuildSystem&,
      TaskInterface ti,
      uintptr_t inputID,
      const BuildValue& value) override { }

  virtual void executeExternalCommand(
      BuildSystem&, TaskInterface ti, QueueJobContext* context,
      llvm::Optional<ProcessCompletionFn> completionFn) override {

    auto args = getArgs();
    ti.spawn(
        context, std::vector<StringRef>(args.begin(), args.end()), {},
        {true}, {[completionFn](ProcessResult result) {
          if (completionFn.hasValue())
            completionFn.getValue()(result);
        }});
  }

  virtual void
  getShortDescription(SmallVectorImpl<char>& result) const override {
    if (getDescription().empty()) {
      llvm::raw_svector_ostream(result)
          << "Creating Shared library: " + sharedLibName;
    } else {
      llvm::raw_svector_ostream(result) << getDescription();
    }
  }

  virtual void
  getVerboseDescription(SmallVectorImpl<char>& result) const override {
    llvm::raw_svector_ostream stream(result);
    bool first = true;
    for (const auto& arg : getArgs()) {
      if (first) {
        first = false;
      } else {
        stream << " ";
      }
      stream << arg;
    }
  }

  virtual void configureInputs(const ConfigureContext& ctx,
                               const std::vector<Node*>& value) override {
    ExternalCommand::configureInputs(ctx, value);

    for (const auto& input : getInputs()) {
      if (!input->isVirtual()) {
        sharedLibInputs.push_back(input->getName());
      }
    }
    if (sharedLibInputs.empty()) {
      ctx.error("SharedLibraryTool requires inputs to be specified");
    }
  }

  virtual void configureOutputs(const ConfigureContext& ctx,
                                const std::vector<Node*>& value) override {
    ExternalCommand::configureOutputs(ctx, value);

    for (const auto& output : getOutputs()) {
      if (!output->isVirtual()) {
        if (sharedLibName.empty()) {
          sharedLibName = output->getName();
        } else {
          ctx.error("unexpected explicit output: " + output->getName());
        }
      }
    }
    if (sharedLibName.empty()) {
      ctx.error("SharedLibraryTool requires the resulting shared library name "
                "to be specified");
    }
  }

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    if (name == "executable") {
      executable = value;
    } else if (name == "other-args") {
      SmallVector<StringRef, 32> args;
      StringRef(value).split(args, " ", /*MaxSplit=*/-1,
                             /*KeepEmpty=*/false);
      otherArgs = std::vector<std::string>(args.begin(), args.end());
    } else if (name == "compiler-style") {
      if (value != "cl" && value != "clang" && value != "swiftc") {
        ctx.error("Unsupported : compiler-style'" + value +
                  "' for shared libraries'.  Supported styles are cl, clang, "
                  "and swiftc");
      }
      compilerStyle = value;
    }
    return true;
  }

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    if (name == "other-args") {
      otherArgs = std::vector<std::string>(values.begin(), values.end());
    } else {
      return ExternalCommand::configureAttribute(ctx, name, values);
    }

    return true;
  }

  std::vector<std::string> getArgs() const {
    std::vector<std::string> args;

    if (compilerStyle == "swiftc") {
      args.push_back(executable);
      args.push_back("-emit-library");
      args.insert(args.end(), sharedLibInputs.begin(), sharedLibInputs.end());
      args.push_back("-o");
      args.push_back(sharedLibName);
      args.insert(args.end(), otherArgs.begin(), otherArgs.end());
    } else if (compilerStyle == "clang") {
      args.push_back(executable);
      args.insert(args.end(), sharedLibInputs.begin(), sharedLibInputs.end());
      args.push_back("-o");
      args.push_back(sharedLibName);
      args.insert(args.end(), otherArgs.begin(), otherArgs.end());
      args.push_back("-shared");
    } else if (compilerStyle == "cl") {
      args.push_back(executable);
      args.insert(args.end(), sharedLibInputs.begin(), sharedLibInputs.end());
      args.push_back("/o");
      args.push_back(sharedLibName);
      args.push_back("/LD");
      args.push_back("/MD");
      args.push_back("/link");
      args.push_back("MSVCRT.lib");
    }

    return args;
  }

public:
  using ExternalCommand::ExternalCommand;
};

class SharedLibraryTool : public Tool {
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
      const ConfigureContext& ctx, StringRef name,
      ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<SharedLibraryShellCommand>(name);
  }
};

#pragma mark - StaleFileRemovalTool implementation

class StaleFileRemovalCommand : public Command {
  std::string description;

  std::vector<std::string> expectedOutputs;
  mutable std::vector<std::string> filesToDelete;
  std::vector<std::string> roots;
  mutable bool computedFilesToDelete = false;

  BuildValue priorValue;
  bool hasPriorResult = false;

  std::string pathSeparators = llbuild::basic::sys::getPathSeparators();

  virtual void configureDescription(const ConfigureContext&, StringRef value) override {
    description = value;
  }

  virtual void getShortDescription(SmallVectorImpl<char> &result) const override {
    llvm::raw_svector_ostream(result) << (description.empty() ? "Stale file removal" : description);
  }

  virtual void getVerboseDescription(SmallVectorImpl<char> &result) const override {
    computeFilesToDelete();

    getShortDescription(result);
    llvm::raw_svector_ostream(result) << ", stale files: [";
    for (auto fileToDelete : filesToDelete) {
      llvm::raw_svector_ostream(result) << fileToDelete;
      if (fileToDelete != *(--filesToDelete.end())) {
        llvm::raw_svector_ostream(result) << ", ";
      }
    }
    llvm::raw_svector_ostream(result) << "], roots: [";
    for (auto root : roots) {
      llvm::raw_svector_ostream(result) << root;
      if (root != *(--roots.end())) {
        llvm::raw_svector_ostream(result) << ", ";
      }
    }
    llvm::raw_svector_ostream(result) << "]";
  }

  virtual void configureInputs(const ConfigureContext& ctx,
                               const std::vector<Node*>& value) override {}

  virtual void configureOutputs(const ConfigureContext& ctx,
                                const std::vector<Node*>& value) override {}

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    if (name == "expectedOutputs") {
      expectedOutputs.reserve(values.size());
      for (auto value : values) {
        expectedOutputs.emplace_back(value.str());
      }
      return true;
    } else if (name == "roots") {
      roots.reserve(values.size());
      for (auto value : values) {
        roots.emplace_back(value.str());
      }
      return true;
    }

    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual BuildValue getResultForOutput(Node* node,
                                        const BuildValue& value) override {
    // If the value was a failed command, propagate the failure.
    if (value.isFailedCommand() || value.isPropagatedFailureCommand() ||
        value.isCancelledCommand())
      return BuildValue::makeFailedInput();
    if (value.isSkippedCommand())
      return BuildValue::makeSkippedCommand();

    // Otherwise, this was successful, return the value as-is.
    return BuildValue::fromData(value.toData());;
  }

  virtual bool isResultValid(BuildSystem& system,
                             const BuildValue& value) override {
    // Always re-run stale file removal.
    return false;
  }

  virtual void start(BuildSystem&, TaskInterface) override {}

  virtual void providePriorValue(BuildSystem&, TaskInterface,
                                 const BuildValue& value) override {
    hasPriorResult = true;
    priorValue = BuildValue::fromData(value.toData());
  }

  virtual void provideValue(BuildSystem&,
                            TaskInterface,
                            uintptr_t inputID,
                            const BuildValue& value) override {
    assert(0 && "unexpected API call");
  }

  void computeFilesToDelete() const {
    if (computedFilesToDelete) {
      return;
    }

    std::vector<StringRef> priorValueList = priorValue.getStaleFileList();
    std::set<std::string> priorNodes(priorValueList.begin(), priorValueList.end());
    std::set<std::string> expectedNodes(expectedOutputs.begin(), expectedOutputs.end());

    std::set_difference(priorNodes.begin(), priorNodes.end(),
                        expectedNodes.begin(), expectedNodes.end(),
                        std::back_inserter(filesToDelete));

    computedFilesToDelete = true;
  }

  virtual void execute(BuildSystem& system,
                       TaskInterface ti,
                       QueueJobContext* context,
                       ResultFn resultFn) override {
    // Nothing to do if we do not have a prior result.
    if (!hasPriorResult || !priorValue.isStaleFileRemoval()) {
      system.getDelegate().commandStarted(this);
      system.getDelegate().commandFinished(this, ProcessStatus::Succeeded);
      resultFn(BuildValue::makeStaleFileRemoval(expectedOutputs));
      return;
    }

    computeFilesToDelete();

    system.getDelegate().commandStarted(this);

    for (auto fileToDelete : filesToDelete) {
      // If no root paths are specified, any path is valid.
      bool isLocatedUnderRootPath = roots.size() == 0 ? true : false;

      // If root paths are defined, stale file paths should be absolute.
      if (roots.size() > 0 &&
          pathSeparators.find(fileToDelete[0]) == std::string::npos) {
        system.getDelegate().commandHadWarning(this, "Stale file '" + fileToDelete + "' has a relative path. This is invalid in combination with the root path attribute.\n");
        continue;
      }

      // Check if the file is located under one of the allowed root paths.
      for (auto root : roots) {
        if (pathIsPrefixedByPath(fileToDelete, root)) {
          isLocatedUnderRootPath = true;
        }
      }

      if (!isLocatedUnderRootPath) {
        system.getDelegate().commandHadWarning(this, "Stale file '" + fileToDelete + "' is located outside of the allowed root paths.\n");
        continue;
      }

      if (getBuildSystem(ti).getFileSystem().remove(fileToDelete)) {
        system.getDelegate().commandHadNote(this, "Removed stale file '" + fileToDelete + "'\n");
      } else {
        // Do not warn if the file has already been deleted.
        if (errno != ENOENT) {
          system.getDelegate().commandHadWarning(this, "cannot remove stale file '" + fileToDelete + "': " + strerror(errno) + "\n");
        }
      }
    }

    system.getDelegate().commandFinished(this, ProcessStatus::Succeeded);

    // Complete with a successful result.
    resultFn(BuildValue::makeStaleFileRemoval(expectedOutputs));
  }

public:
  StaleFileRemovalCommand(const StringRef name)
  : Command(name), priorValue(BuildValue::makeInvalid()) {}
};

class StaleFileRemovalTool : public Tool {
public:
  using Tool::Tool;

  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  StringRef value) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<StringRef> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }
  virtual bool configureAttribute(
                                  const ConfigureContext& ctx, StringRef name,
                                  ArrayRef<std::pair<StringRef, StringRef>> values) override {
    // No supported attributes.
    ctx.error("unexpected attribute: '" + name + "'");
    return false;
  }

  virtual std::unique_ptr<Command> createCommand(StringRef name) override {
    return llvm::make_unique<StaleFileRemovalCommand>(name);
  }
};

#pragma mark - BuildSystemFileDelegate

BuildSystemDelegate& BuildSystemFileDelegate::getSystemDelegate() {
  return system.getDelegate();
}

void BuildSystemFileDelegate::setFileContentsBeingParsed(StringRef buffer) {
  getSystemDelegate().setFileContentsBeingParsed(buffer);
}

void BuildSystemFileDelegate::error(StringRef filename,
                                    const BuildFileToken& at,
                                    const Twine& message) {
  // Delegate to the system delegate.
  auto atSystemToken = BuildSystemDelegate::Token{at.start, at.length};
  system.error(filename, atSystemToken, message);
}

void
BuildSystemFileDelegate::cannotLoadDueToMultipleProducers(Node *output,
                                                          std::vector<Command*> commands) {
  getSystemDelegate().cannotBuildNodeDueToMultipleProducers(output, commands);
}

bool
BuildSystemFileDelegate::configureClient(const ConfigureContext& ctx,
                                         StringRef name,
                                         uint32_t version,
                                         const property_list_type& properties) {
  // The client must match the configured name of the build system.
  if (name != getSystemDelegate().getName())
    return false;

  // The client version must match the configured version.
  //
  // FIXME: We should give the client the opportunity to support a previous
  // schema version (auto-upgrade).
  if (version != getSystemDelegate().getVersion())
    return false;

  for (auto prop : properties) {
    if (prop.first == "file-system") {
      if (prop.second == "device-agnostic") {
        system.configureFileSystem(1);
      } else if (prop.second == "checksum-only") {
        system.configureFileSystem(2);
      } else if (prop.second != "default") {
        ctx.error("unsupported client file-system: '" + prop.second + "'");
        return false;
      }
    }
  }

  return true;
}

std::unique_ptr<Tool>
BuildSystemFileDelegate::lookupTool(StringRef name) {
  // First, give the client an opportunity to create the tool.
  if (auto tool = getSystemDelegate().lookupTool(name)) {
    return tool;
  }

  // Otherwise, look for one of the builtin tool definitions.
  if (name == "shell") {
    return llvm::make_unique<ShellTool>(name);
  } else if (name == "phony") {
    return llvm::make_unique<PhonyTool>(name);
  } else if (name == "clang") {
    return llvm::make_unique<ClangTool>(name);
  } else if (name == "mkdir") {
    return llvm::make_unique<MkdirTool>(name);
  } else if (name == "symlink") {
    return llvm::make_unique<SymlinkTool>(name);
  } else if (name == "archive") {
    return llvm::make_unique<ArchiveTool>(name);
  } else if (name == "shared-library") {
    return llvm::make_unique<SharedLibraryTool>(name);
  } else if (name == "stale-file-removal") {
    return llvm::make_unique<StaleFileRemovalTool>(name);
  } else if (name == "swift-compiler") {
    return llvm::make_unique<SwiftCompilerTool>(name);
  }

  return nullptr;
}

void BuildSystemFileDelegate::loadedTarget(StringRef name,
                                           const Target& target) {
}

void BuildSystemFileDelegate::loadedDefaultTarget(StringRef target) {
}

void BuildSystemFileDelegate::loadedCommand(StringRef name,
                                            const Command& command) {
}

std::unique_ptr<Node>
BuildSystemFileDelegate::lookupNode(StringRef name,
                                    bool isImplicit) {
  return system.lookupNode(name, isImplicit);
}

}

#pragma mark - BuildSystem

BuildSystem::BuildSystem(BuildSystemDelegate& delegate, std::unique_ptr<basic::FileSystem> fileSystem)
  : impl(new BuildSystemImpl(*this, delegate, std::move(fileSystem)))
{
}

BuildSystem::~BuildSystem() {
  delete static_cast<BuildSystemImpl*>(impl);
}

BuildSystemDelegate& BuildSystem::getDelegate() {
  return static_cast<BuildSystemImpl*>(impl)->getDelegate();
}

basic::FileSystem& BuildSystem::getFileSystem() {
  return static_cast<BuildSystemImpl*>(impl)->getFileSystem();
}

bool BuildSystem::loadDescription(StringRef mainFilename) {
  return static_cast<BuildSystemImpl*>(impl)->loadDescription(mainFilename);
}

void BuildSystem::loadDescription(
    std::unique_ptr<BuildDescription> description) {
  return static_cast<BuildSystemImpl*>(impl)->loadDescription(
      std::move(description));
}

bool BuildSystem::attachDB(StringRef path,
                                std::string* error_out) {
  return static_cast<BuildSystemImpl*>(impl)->attachDB(path, error_out);
}

bool BuildSystem::enableTracing(StringRef path,
                                std::string* error_out) {
  return static_cast<BuildSystemImpl*>(impl)->enableTracing(path, error_out);
}

llvm::Optional<BuildValue> BuildSystem::build(BuildKey key) {
  return static_cast<BuildSystemImpl*>(impl)->build(key);
}

bool BuildSystem::build(StringRef name) {
  return static_cast<BuildSystemImpl*>(impl)->build(name);
}

void BuildSystem::cancel() {
  if (impl) {
    static_cast<BuildSystemImpl*>(impl)->cancel();
  }
}

void BuildSystem::addCancellationDelegate(CancellationDelegate* del) {
  if (impl) {
    static_cast<BuildSystemImpl*>(impl)->addCancellationDelegate(del);
  }
}

void BuildSystem::removeCancellationDelegate(CancellationDelegate* del) {
  if (impl) {
    static_cast<BuildSystemImpl*>(impl)->removeCancellationDelegate(del);
  }
}

void BuildSystem::resetForBuild() {
  static_cast<BuildSystemImpl*>(impl)->resetForBuild();
}

uint32_t BuildSystem::getSchemaVersion() {
  return BuildSystemImpl::internalSchemaVersion;
}

ShellCommandHandler*
BuildSystem::resolveShellCommandHandler(ShellCommand* command) {
  return static_cast<BuildSystemImpl*>(impl)->resolveShellCommandHandler(command);
}

// This function checks if the given path is prefixed by another path.
bool llbuild::buildsystem::pathIsPrefixedByPath(std::string path,
                                                std::string prefixPath) {
  std::string pathSeparators = llbuild::basic::sys::getPathSeparators();
  // Note: GCC 4.8 doesn't support the mismatch(first1, last1, first2, last2)
  // overload, just mismatch(first1, last1, first2), so we have to handle the
  // case where prefixPath is longer than path.
  if (prefixPath.length() > path.length()) {
    // The only case where the prefix can be longer and still be a valid prefix
    // is "/foo/" is a prefix of "/foo"
    return prefixPath.substr(0, prefixPath.length() - 1) == path &&
           pathSeparators.find(prefixPath[prefixPath.length() - 1]) !=
               std::string::npos;
  }
  auto res = std::mismatch(prefixPath.begin(), prefixPath.end(), path.begin());
  // Check if `prefixPath` has been exhausted or just a separator remains.
  bool isPrefix = res.first == prefixPath.end() ||
                  (pathSeparators.find(*(res.first++)) != std::string::npos);
  // Check if `path` has been exhausted or just a separator remains.
  return isPrefix &&
         (res.second == path.end() ||
          (pathSeparators.find(*(res.second++)) != std::string::npos));
}