aboutsummaryrefslogtreecommitdiff
path: root/libbuild2/cc/compile-rule.cxx
blob: 99c3b900e23619cef4169aefc65123f0fbfecc97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
// file      : libbuild2/cc/compile-rule.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbuild2/cc/compile-rule.hxx>

#include <cerrno>
#include <cstdlib>  // exit()
#include <cstring>  // strlen(), strchr(), strncmp()

#include <libbutl/path-pattern.hxx>

#include <libbuild2/file.hxx>
#include <libbuild2/depdb.hxx>
#include <libbuild2/scope.hxx>
#include <libbuild2/context.hxx>
#include <libbuild2/variable.hxx>
#include <libbuild2/algorithm.hxx>
#include <libbuild2/filesystem.hxx>  // mtime()
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/make-parser.hxx>

#include <libbuild2/bin/target.hxx>

#include <libbuild2/cc/parser.hxx>
#include <libbuild2/cc/target.hxx>  // h
#include <libbuild2/cc/module.hxx>
#include <libbuild2/cc/utility.hxx>

using std::exit;
using std::strlen;

using namespace butl;

namespace build2
{
  namespace cc
  {
    using namespace bin;

    // Module type/info string serialization.
    //
    // The string representation is a space-separated list of module names
    // or quoted paths for header units with the following rules:
    //
    // 1. If this is a module unit, then the first name is the module name
    //    intself following by either '!' for an interface, interface
    //    partition, or header unit and by '+' for an implementation or
    //    implementation partition unit.
    //
    // 2. If an imported module is re-exported, then the module name is
    //    followed by '*'.
    //
    // For example:
    //
    // foo! foo.core* foo.base* foo:intf! foo.impl
    // foo.base+ foo.impl
    // foo.base foo.impl
    // foo:impl+
    // foo:intf! foo:impl
    // "/usr/include/stdio.h"!
    // "/usr/include/stdio.h"! "/usr/include/stddef.h"
    //
    // NOTE: currently we omit the imported header units since we have no need
    //       for this information (everything is handled by the mapper). Plus,
    //       resolving an import declaration to an absolute path would require
    //       some effort.
    //
    static string
    to_string (unit_type ut, const module_info& mi)
    {
      string s;

      if (ut != unit_type::non_modular)
      {
        if (ut == unit_type::module_header) s += '"';
        s += mi.name;
        if (ut == unit_type::module_header) s += '"';

        s += (ut == unit_type::module_impl ||
              ut == unit_type::module_impl_part ? '+' : '!');
      }

      for (const module_import& i: mi.imports)
      {
        if (!s.empty ())
          s += ' ';

        if (i.type == import_type::module_header) s += '"';
        s += i.name;
        if (i.type == import_type::module_header) s += '"';

        if (i.exported)
          s += '*';
      }

      return s;
    }

    static unit_type
    to_module_info (const string& s, module_info& mi)
    {
      unit_type ut (unit_type::non_modular);

      for (size_t b (0), e (0), n (s.size ()), m; e < n; )
      {
        // Let's handle paths with spaces seeing that we already quote them.
        //
        char d (s[b = e] == '"' ? '"' : ' ');

        if ((m = next_word (s, n, b, e, d)) == 0)
          break;

        char c (d == ' '  ? s[e - 1] : // Before delimiter.
                e + 1 < n ? s[e + 1] : // After delimiter.
                '\0');

        switch (c)
        {
        case '!':
        case '+':
        case '*': break;
        default:  c = '\0';
        }

        string w (s, b, m - (d == ' ' && c != '\0' ? 1 : 0));

        if (c == '!' || c == '+')
        {
          if (d == ' ')
          {
            ut = w.find (':') != string::npos
              ? (c == '!'
                 ? unit_type::module_intf_part
                 : unit_type::module_impl_part)
              : (c == '!'
                 ? unit_type::module_intf
                 : unit_type::module_impl);
          }
          else
            ut = unit_type::module_header;

          mi.name = move (w);
        }
        else
        {
          import_type t (d == ' '
                         ? (w.find (':') != string::npos
                            ? import_type::module_part
                            : import_type::module_intf)
                         : import_type::module_header);

          mi.imports.push_back (module_import {t, move (w), c == '*', 0});
        }

        // Skip to the next word (quote and space or just space).
        //
        e += (d == '"' ? 2 : 1);
      }

      return ut;
    }

    // preprocessed
    //
    template <typename T>
    inline bool
    operator< (preprocessed l, T r) // Template because of VC14 bug.
    {
      return static_cast<uint8_t> (l) < static_cast<uint8_t> (r);
    }

    preprocessed
    to_preprocessed (const string& s)
    {
      if (s == "none")     return preprocessed::none;
      if (s == "includes") return preprocessed::includes;
      if (s == "modules")  return preprocessed::modules;
      if (s == "all")      return preprocessed::all;
      throw invalid_argument ("invalid preprocessed value '" + s + '\'');
    }

    // Return true if the compiler supports -isystem (GCC class) or
    // /external:I (MSVC class).
    //
    static inline bool
    isystem (const data& d)
    {
      switch (d.cclass)
      {
      case compiler_class::gcc:
        {
          return true;
        }
      case compiler_class::msvc:
        {
          if (d.cvariant.empty ())
          {
            // While /external:I is available since 15.6, it required
            // /experimental:external (and was rather buggy) until 16.10.
            //
            return d.cmaj > 19 || (d.cmaj == 19 && d.cmin >= 29);
          }
          else if (d.cvariant != "clang")
          {
            // clang-cl added support for /external:I (by translating it to
            // -isystem) in version 13.
            //
            return d.cvmaj >= 13;
          }
          else
            return false;
        }
      }

      return false;
    }

    optional<path> compile_rule::
    find_system_header (const path& f) const
    {
      path p; // Reuse the buffer.
      for (const dir_path& d: sys_hdr_dirs)
      {
        if (file_exists ((p = d, p /= f),
                         true /* follow_symlinks */,
                         true /* ignore_errors */))
          return p;
      }

      return nullopt;
    }

    // Note that we don't really need this for clean (where we only need
    // unrefined unit type) so we could make this update-only. But let's keep
    // it simple for now. Note that now we do need the source prerequisite
    // type in clean to deal with Objective-X.
    //
    struct compile_rule::match_data
    {
      match_data (const compile_rule& r,
                  unit_type t,
                  const prerequisite_member& s)
          : type (t), src (s), rule (r) {}

      unit_type type;
      preprocessed pp = preprocessed::none;
      bool deferred_failure = false;        // Failure deferred to compilation.
      bool symexport = false;               // Target uses __symexport.
      bool touch = false;                   // Target needs to be touched.
      timestamp mt = timestamp_unknown;     // Target timestamp.
      prerequisite_member src;
      file_cache::entry psrc;               // Preprocessed source, if any.
      path dd;                              // Dependency database path.
      size_t header_units = 0;              // Number of imported header units.
      module_positions modules = {0, 0, 0}; // Positions of imported modules.

      const compile_rule& rule;

      target_state
      operator() (action a, const target& t)
      {
        return rule.perform_update (a, t, *this);
      }
    };

    compile_rule::
    compile_rule (data&& d, const scope& rs)
        : common (move (d)),
          rule_id (string (x) += ".compile 6")
    {
      // Locate the header cache (see enter_header() for details).
      //
      {
        string mn (string (x) + ".config");

        header_cache_ = rs.find_module<config_module> (mn); // Must be there.

        const scope* ws (rs.weak_scope ());
        if (ws != &rs)
        {
          const scope* s (&rs);
          do
          {
            s = s->parent_scope ()->root_scope ();

            if (const auto* m = s->find_module<config_module> (mn))
              header_cache_ = m;

          } while (s != ws);
        }
      }
    }

    template <typename T>
    void compile_rule::
    append_sys_hdr_options (T& args) const
    {
      assert (sys_hdr_dirs_mode + sys_hdr_dirs_extra <= sys_hdr_dirs.size ());

      // Note that the mode options are added as part of cmode.
      //
      auto b (sys_hdr_dirs.begin () + sys_hdr_dirs_mode);
      auto x (b + sys_hdr_dirs_extra);

      // Add extras.
      //
      // Note: starting from 16.10, MSVC gained /external:I option though it
      // doesn't seem to affect the order, only "system-ness".
      //
      append_option_values (
        args,
        cclass == compiler_class::gcc  ? "-isystem" :
        cclass == compiler_class::msvc ? (isystem (*this)
                                          ? "/external:I"
                                          : "/I") : "-I",
        b, x,
        [] (const dir_path& d) {return d.string ().c_str ();});

      // For MSVC if we have no INCLUDE environment variable set, then we
      // add all of them. But we want extras to come first. Note also that
      // clang-cl takes care of this itself.
      //
      // Note also that we don't use /external:I to have consistent semantics
      // with when INCLUDE is set (there is separate /external:env for that).
      //
      if (ctype == compiler_type::msvc && cvariant != "clang")
      {
        if (!getenv ("INCLUDE"))
        {
          append_option_values (
            args, "/I",
            x, sys_hdr_dirs.end (),
            [] (const dir_path& d) {return d.string ().c_str ();});
        }
      }
    }

    size_t compile_rule::
    append_lang_options (cstrings& args, const match_data& md) const
    {
      size_t r (args.size ());

      // Normally there will be one or two options/arguments.
      //
      const char* o1 (nullptr);
      const char* o2 (nullptr);

      switch (cclass)
      {
      case compiler_class::msvc:
        {
          switch (x_lang)
          {
          case lang::c:   o1 = "/TC"; break;
          case lang::cxx: o1 = "/TP"; break;
          }

          // Note: /interface and /internalPartition are in addition to /TP.
          //
          switch (md.type)
          {
          case unit_type::non_modular:
          case unit_type::module_impl:
            {
              break;
            }
          case unit_type::module_intf:
          case unit_type::module_intf_part:
            {
              o2 = "/interface";
              break;
            }
          case unit_type::module_impl_part:
            {
              o2 = "/internalPartition";
              break;
            }
          case unit_type::module_header:
            {
              //@@ MODHDR TODO: /exportHeader
              assert (false);
              break;
            }
          }

          break;
        }
      case compiler_class::gcc:
        {
          // For GCC we ignore the preprocessed value since it is handled via
          // -fpreprocessed -fdirectives-only.
          //
          // Clang has *-cpp-output (but not c++-module-cpp-output) and they
          // handle comments and line continuations. However, currently this
          // is only by accident since these modes are essentially equivalent
          // to their cpp-output-less versions.
          //
          switch (md.type)
          {
          case unit_type::non_modular:
          case unit_type::module_impl:
            {
              o1 = "-x";

              if (x_assembler_cpp (md.src))
                o2 = "assembler-with-cpp";
              else
              {
                bool obj (x_objective (md.src));

                switch (x_lang)
                {
                case lang::c:   o2 = obj ? "objective-c"   : "c";   break;
                case lang::cxx: o2 = obj ? "objective-c++" : "c++"; break;
                }
              }

              break;
            }
          case unit_type::module_intf:
          case unit_type::module_intf_part:
          case unit_type::module_impl_part:
          case unit_type::module_header:
            {
              // Here things get rather compiler-specific. We also assume
              // the language is C++.
              //
              bool h (md.type == unit_type::module_header);

              //@@ MODHDR TODO: should we try to distinguish c-header vs
              //   c++-header based on the source target type?

              switch (ctype)
              {
              case compiler_type::gcc:
                {
                  // In GCC compiling a header unit required -fmodule-header
                  // in addition to -x c/c++-header. Probably because relying
                  // on just -x would be ambigous with its PCH support.
                  //
                  if (h)
                    args.push_back ("-fmodule-header");

                  o1 = "-x";
                  o2 = h ? "c++-header" : "c++";
                  break;
                }
              case compiler_type::clang:
                {
                  o1 = "-x";
                  o2 =  h ? "c++-header" : "c++-module";
                  break;
                }
              default:
                  assert (false);
              }

              break;
            }
          }

          break;
        }
      }

      if (o1 != nullptr) args.push_back (o1);
      if (o2 != nullptr) args.push_back (o2);

      return args.size () - r;
    }

    inline void compile_rule::
    append_symexport_options (cstrings& args, const target& t) const
    {
      // With VC if a BMI is compiled with dllexport, then when such BMI is
      // imported, it is auto-magically treated as dllimport. Let's hope
      // other compilers follow suit.
      //
      args.push_back (t.is_a<bmis> () && tclass == "windows"
                      ? "-D__symexport=__declspec(dllexport)"
                      : "-D__symexport=");
    }

    bool compile_rule::
    match (action a, target& t) const
    {
      tracer trace (x, "compile_rule::match");

      // Note: unit type will be refined in apply().
      //
      unit_type ut (t.is_a<hbmix> () ? unit_type::module_header :
                    t.is_a<bmix> ()  ? unit_type::module_intf  :
                    unit_type::non_modular);

      // Link-up to our group (this is the obj/bmi{} target group protocol
      // which means this can be done whether we match or not).
      //
      if (t.group == nullptr)
        t.group = &search (t,
                           (ut == unit_type::module_header ? hbmi::static_type:
                            ut == unit_type::module_intf   ? bmi::static_type :
                            obj::static_type),
                           t.dir, t.out, t.name);

      // See if we have a source file. Iterate in reverse so that a source
      // file specified for a member overrides the one specified for the
      // group. Also "see through" groups.
      //
      for (prerequisite_member p: reverse_group_prerequisite_members (a, t))
      {
        // If excluded or ad hoc, then don't factor it into our tests.
        //
        if (include (a, t, p) != include_type::normal)
          continue;

        // For a header unit we check the "real header" plus the C header.
        //
        if (ut == unit_type::module_header ? p.is_a (**x_hdrs) || p.is_a<h> () :
            ut == unit_type::module_intf   ? p.is_a (*x_mod)                   :
            p.is_a (x_src)                        ||
            (x_asp != nullptr && p.is_a (*x_asp)) ||
            (x_obj != nullptr && p.is_a (*x_obj)))
        {
          // Save in the target's auxiliary storage.
          //
          t.data (a, match_data (*this, ut, p));
          return true;
        }
      }

      l4 ([&]{trace << "no " << x_lang << " source file for target " << t;});
      return false;
    }

    // Append or hash library options from a pair of *.export.* variables
    // (first is x.* then cc.*) recursively, prerequisite libraries first.
    // If common is true, then only append common options from the lib{}
    // groups.
    //
    template <typename T>
    void compile_rule::
    append_library_options (appended_libraries& ls, T& args,
                            const scope& bs,
                            const scope* is, // Internal scope.
                            action a, const file& l, bool la,
                            linfo li, bool common,
                            library_cache* lib_cache) const
    {
      struct data
      {
        appended_libraries& ls;
        T& args;
        const scope* is;
      } d {ls, args, is};

      // See through utility libraries.
      //
      auto imp = [] (const target& l, bool la) {return la && l.is_a<libux> ();};

      auto opt = [&d, this] (const target& l, // Note: could be lib{}
                             const string& t, bool com, bool exp)
      {
        // Note that in our model *.export.poptions are always "interface",
        // even if set on liba{}/libs{}, unlike loptions.
        //
        if (!exp) // Ignore libux.
          return true;

        // Suppress duplicates.
        //
        // Compilation is the simple case: we can add the options on the first
        // occurrence of the library and ignore (and prune) all subsequent
        // occurrences. See GitHub issue #114 for details.
        //
        if (find (d.ls.begin (), d.ls.end (), &l) != d.ls.end ())
          return false;

        // Note: go straight for the public variable pool.
        //
        const variable& var (
          com
          ? c_export_poptions
          : (t == x
             ? x_export_poptions
             : l.ctx.var_pool[t + ".export.poptions"]));

        if (const strings* ops = cast_null<strings> (l[var]))
        {
          // If enabled, remap -I to -isystem or /external:I for paths that
          // are outside of the internal scope provided the library is not
          // whitelisted.
          //
          auto whitelist = [&l] (const strings& pats)
          {
            return find_if (pats.begin (), pats.end (),
                            [&l] (const string& pat)
                            {
                              return path_match (l.name, pat);
                            }) != pats.end ();
          };

          const scope* is (d.is);

          if (is != nullptr && c_ilibs != nullptr && whitelist (*c_ilibs))
            is = nullptr;

          if (is != nullptr && x_ilibs != nullptr && whitelist (*x_ilibs))
            is = nullptr;

          for (auto i (ops->begin ()), e (ops->end ()); i != e; ++i)
          {
            const string& o (*i);

            if (is != nullptr)
            {
              // See if this is -I<dir> or -I <dir> (or /I... for MSVC).
              //
              // While strictly speaking we can only attempt to recognize
              // options until we hit something unknown (after that, we don't
              // know what's an option and what's a value), it doesn't seem
              // likely to cause issues here, where we only expect to see -I,
              // -D, and -U.
              //
              bool msvc (cclass == compiler_class::msvc);

              if ((o[0] == '-' || (msvc && o[0] == '/')) && o[1] == 'I')
              {
                bool sep (o.size () == 2); // -I<dir> vs -I <dir>

                const char* v (nullptr);
                size_t vn (0);
                if (sep)
                {
                  if (i + 1 == e)
                    ; // Append as is and let the compiler complain.
                  else
                  {
                    ++i;
                    v = i->c_str ();
                    vn = i->size ();
                  }
                }
                else
                {
                  v = o.c_str () + 2;
                  vn = o.size () - 2;
                }

                if (v != nullptr)
                {
                  // See if we need to translate the option for this path. We
                  // only do this for absolute paths and try to optimize for
                  // the already normalized ones.
                  //
                  if (path_traits::absolute (v))
                  {
                    const char* p (nullptr);
                    size_t pn (0);

                    dir_path nd;
                    if (path_traits::normalized (v, vn, true /* separators */))
                    {
                      p = v;
                      pn = vn;
                    }
                    else
                    try
                    {
                      nd = dir_path (v, vn);
                      nd.normalize ();
                      p = nd.string ().c_str ();
                      pn = nd.string ().size ();
                    }
                    catch (const invalid_path&)
                    {
                      // Ignore this path.
                    }

                    if (p != nullptr)
                    {
                      auto sub = [p, pn] (const dir_path& d)
                      {
                        return path_traits::sub (
                          p, pn,
                          d.string ().c_str (), d.string ().size ());
                      };

                      // Translate if it's neither in src nor in out of the
                      // internal scope.
                      //
                      if (!sub (is->src_path ()) &&
                          (is->out_eq_src () || !sub (is->out_path ())))
                      {
                        // Note: must use original value (path is temporary).
                        //
                        append_option (d.args,
                                       msvc ? "/external:I" : "-isystem");
                        append_option (d.args, v);
                        continue;
                      }
                    }
                  }

                  // If not translated, preserve the original form.
                  //
                  append_option (d.args, o.c_str ());
                  if (sep) append_option (d.args, v);

                  continue;
                }
              }
            }

            append_option (d.args, o.c_str ());
          }
        }

        // From the process_libraries() semantics we know that the final call
        // is always for the common options.
        //
        if (com)
          d.ls.push_back (&l);

        return true;
      };

      process_libraries (a, bs, li, sys_lib_dirs,
                         l, la, 0, // lflags unused.
                         imp, nullptr, opt,
                         false /* self */,
                         common /* proc_opt_group */,
                         lib_cache);
    }

    void compile_rule::
    append_library_options (appended_libraries& ls, strings& args,
                            const scope& bs,
                            action a, const file& l, bool la,
                            linfo li,
                            bool common,
                            bool original) const
    {
      const scope* is (!original && isystem (*this)
                       ? effective_iscope (bs)
                       : nullptr);
      append_library_options (ls, args, bs, is, a, l, la, li, common, nullptr);
    }

    template <typename T>
    void compile_rule::
    append_library_options (T& args,
                            const scope& bs,
                            action a, const target& t, linfo li) const
    {
      auto iscope = [this, &bs, is = optional<const scope*> ()] () mutable
      {
        if (!is)
          is = isystem (*this) ? effective_iscope (bs) : nullptr;

        return *is;
      };

      appended_libraries ls;
      library_cache lc;

      for (prerequisite_member p: group_prerequisite_members (a, t))
      {
        if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
          continue;

        // Should be already searched and matched for libraries.
        //
        if (const target* pt = p.load ())
        {
          if (const libx* l = pt->is_a<libx> ())
            pt = link_member (*l, a, li);

          bool la;
          const file* f;
          if ((la = (f = pt->is_a<liba> ()))  ||
              (la = (f = pt->is_a<libux> ())) ||
              (     (f = pt->is_a<libs> ())))
          {
            append_library_options (ls,
                                    args,
                                    bs, iscope (),
                                    a, *f, la,
                                    li,
                                    false /* common */,
                                    &lc);
          }
        }
      }
    }

    // Append library prefixes based on the *.export.poptions variables
    // recursively, prerequisite libraries first.
    //
    void compile_rule::
    append_library_prefixes (appended_libraries& ls, prefix_map& pm,
                             const scope& bs,
                             action a, const target& t, linfo li) const
    {
      struct data
      {
        appended_libraries& ls;
        prefix_map&         pm;
      } d {ls, pm};

      auto imp = [] (const target& l, bool la) {return la && l.is_a<libux> ();};

      auto opt = [&d, this] (const target& lt,
                             const string& t, bool com, bool exp)
      {
        if (!exp)
          return true;

        const file& l (lt.as<file> ());

        // Suppress duplicates like in append_library_options().
        //
        if (find (d.ls.begin (), d.ls.end (), &l) != d.ls.end ())
          return false;

        // If this target does not belong to any project (e.g, an "imported as
        // installed" library), then it can't possibly generate any headers
        // for us.
        //
        if (const scope* rs = l.base_scope ().root_scope ())
        {
          // Note: go straight for the public variable pool.
          //
          const variable& var (
            com
            ? c_export_poptions
            : (t == x
               ? x_export_poptions
               : l.ctx.var_pool[t + ".export.poptions"]));

          append_prefixes (d.pm, *rs, l, var);
        }

        if (com)
          d.ls.push_back (&l);

        return true;
      };

      // The same logic as in append_library_options().
      //
      const function<bool (const target&, bool)> impf (imp);
      const function<bool (const target&, const string&, bool, bool)> optf (opt);

      library_cache lib_cache;
      for (prerequisite_member p: group_prerequisite_members (a, t))
      {
        if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
          continue;

        if (const target* pt = p.load ())
        {
          if (const libx* l = pt->is_a<libx> ())
            pt = link_member (*l, a, li);

          bool la;
          if (!((la = pt->is_a<liba> ())  ||
                (la = pt->is_a<libux> ()) ||
                pt->is_a<libs> ()))
            continue;

          process_libraries (a, bs, li, sys_lib_dirs,
                             pt->as<file> (), la, 0, // lflags unused.
                             impf, nullptr, optf,
                             false /* self */,
                             false /* proc_opt_group */,
                             &lib_cache);
        }
      }
    }

    recipe compile_rule::
    apply (action a, target& xt) const
    {
      tracer trace (x, "compile_rule::apply");

      file& t (xt.as<file> ()); // Either obj*{} or bmi*{}.

      match_data& md (t.data<match_data> (a));

      context& ctx (t.ctx);

      // Note: until refined below, non-BMI-generating translation unit is
      // assumed non-modular.
      //
      unit_type ut (md.type);

      const scope& bs (t.base_scope ());
      const scope& rs (*bs.root_scope ());

      otype ot (compile_type (t, ut));
      linfo li (link_info (bs, ot)); // Link info for selecting libraries.
      compile_target_types tts (compile_types (ot));

      // Derive file name from target name.
      //
      string e; // Primary target extension (module or object).
      {
        const char* o ("o"); // Object extension (.o or .obj).

        if (tsys == "win32-msvc")
        {
          switch (ot)
          {
          case otype::e: e = "exe."; break;
          case otype::a: e = "lib."; break;
          case otype::s: e = "dll."; break;
          }
          o = "obj";
        }
        else if (tsys == "mingw32")
        {
          switch (ot)
          {
          case otype::e: e = "exe."; break;
          case otype::a: e = "a.";   break;
          case otype::s: e = "dll."; break;
          }
        }
        else if (tsys == "darwin")
        {
          switch (ot)
          {
          case otype::e: e = "";       break;
          case otype::a: e = "a.";     break;
          case otype::s: e = "dylib."; break;
          }
        }
        else
        {
          switch (ot)
          {
          case otype::e: e = "";    break;
          case otype::a: e = "a.";  break;
          case otype::s: e = "so."; break;
          }
        }

        switch (ctype)
        {
        case compiler_type::gcc:
          {
            e += (ut != unit_type::non_modular ? "gcm" : o);
            break;
          }
        case compiler_type::clang:
          {
            e += (ut != unit_type::non_modular ? "pcm" : o);
            break;
          }
        case compiler_type::msvc:
          {
            e += (ut != unit_type::non_modular ? "ifc" : o);
            break;
          }
        case compiler_type::icc:
          {
            assert (ut == unit_type::non_modular);
            e += o;
          }
        }

        // If we are compiling a BMI-producing module TU, then add obj*{} an
        // ad hoc member of bmi*{} unless we only need the BMI (see
        // config_data::b_binless for details).
        //
        // For now neither GCC nor Clang produce an object file for a header
        // unit (but something tells me this might change).
        //
        // Note: ut is still unrefined.
        //
        if ((ut == unit_type::module_intf      ||
             ut == unit_type::module_intf_part ||
             ut == unit_type::module_impl_part) && cast_true<bool> (t[b_binless]))
        {
          // The module interface unit can be the same as an implementation
          // (e.g., foo.mxx and foo.cxx) which means obj*{} targets could
          // collide. So we add the module extension to the target name.
          //
          file& obj (add_adhoc_member<file> (t, tts.obj, e.c_str ()));

          if (obj.path ().empty ())
            obj.derive_path (o);
        }
      }

      const path& tp (t.derive_path (e.c_str ()));

      // Inject dependency on the output directory.
      //
      const fsdir* dir (inject_fsdir (a, t));

      // Match all the existing prerequisites. The injection code takes care
      // of the ones it is adding.
      //
      // When cleaning, ignore prerequisites that are not in the same or a
      // subdirectory of our project root.
      //
      auto& pts (t.prerequisite_targets[a]);
      optional<dir_paths> usr_lib_dirs; // Extract lazily.

      // Start asynchronous matching of prerequisites. Wait with unlocked
      // phase to allow phase switching.
      //
      wait_guard wg (ctx, ctx.count_busy (), t[a].task_count, true);

      size_t src_i (~0);          // Index of src target.
      size_t start (pts.size ()); // Index of the first to be added.
      for (prerequisite_member p: group_prerequisite_members (a, t))
      {
        const target* pt (nullptr);
        include_type  pi (include (a, t, p));

        if (!pi)
          continue;

        // A dependency on a library is there so that we can get its
        // *.export.poptions, modules, importable headers, etc. This is the
        // library metadata protocol. See also append_library_options().
        //
        if (pi == include_type::normal &&
            (p.is_a<libx> () ||
             p.is_a<liba> () ||
             p.is_a<libs> () ||
             p.is_a<libux> ()))
        {
          if (a.operation () == update_id)
          {
            // Handle (phase two) imported libraries. We know that for such
            // libraries we don't need to do match() in order to get options
            // (if any, they would be set by search_library()). But we do need
            // to match it if we may need its modules or importable headers
            // (see search_modules(), make_header_sidebuild() for details).
            //
            // Well, that was the case until we've added support for immediate
            // importation of libraries, which happens during the load phase
            // and natually leaves the library unmatched. While we could have
            // returned from search_library() an indication of whether the
            // library has been matched, this doesn't seem worth the trouble.
            //
            if (p.proj ())
            {
              pt = search_library (a,
                                   sys_lib_dirs,
                                   usr_lib_dirs,
                                   p.prerequisite);

#if 0
              if (pt != nullptr && !modules)
                continue;
#endif
            }

            if (pt == nullptr)
              pt = &p.search (t);

            if (const libx* l = pt->is_a<libx> ())
              pt = link_member (*l, a, li);
          }
          else
            continue;
        }
        //
        // For modules we pick only what we import which is done below so
        // skip it here. One corner case is clean: we assume that someone
        // else (normally library/executable) also depends on it and will
        // clean it up.
        //
        else if (pi == include_type::normal &&
                 (p.is_a<bmi> ()  || p.is_a (tts.bmi) ||
                  p.is_a<hbmi> () || p.is_a (tts.hbmi)))
        {
          continue;
        }
        else
        {
          pt = &p.search (t);

          if (pt == dir ||
              (a.operation () == clean_id && !pt->dir.sub (rs.out_path ())))
            continue;
        }

        match_async (a, *pt, ctx.count_busy (), t[a].task_count);

        if (p == md.src)
          src_i = pts.size ();

        pts.push_back (prerequisite_target (pt, pi));
      }

      wg.wait ();

      // Finish matching all the targets that we have started.
      //
      for (size_t i (start), n (pts.size ()); i != n; ++i)
      {
        const target*& pt (pts[i]);

        // Making sure a library is updated before us will only restrict
        // parallelism. But we do need to match it in order to get its imports
        // resolved and prerequisite_targets populated. So we match it but
        // then unmatch if it is safe. And thanks to the two-pass prerequisite
        // match in link::apply() it will be safe unless someone is building
        // an obj?{} target directly.
        //
        // @@ If for some reason unmatch fails, this messes up the for_install
        //    logic because we will update this library during match. Perhaps
        //    we should postpone updating them until execute if we failed to
        //    unmatch. See how we do this in ad hoc rule.
        //
        pair<bool, target_state> mr (
          match_complete (
            a,
            *pt,
            pt->is_a<liba> () || pt->is_a<libs> () || pt->is_a<libux> ()
            ? unmatch::safe
            : unmatch::none));

        if (mr.first)
          pt = nullptr; // Ignore in execute.
      }

      // Inject additional prerequisites. We only do it when performing update
      // since chances are we will have to update some of our prerequisites in
      // the process (auto-generated source code, header units).
      //
      if (a == perform_update_id)
      {
        const file& src (pts[src_i]->as<file> ());

        // Figure out if __symexport is used. While normally it is specified
        // on the project root (which we cached), it can be overridden with
        // a target-specific value for installed modules (which we sidebuild
        // as part of our project).
        //
        // @@ MODHDR MSVC: are we going to do the same for header units? I
        //    guess we will figure it out when MSVC supports header units.
        //    Also see hashing below.
        //
        if (ut == unit_type::module_intf) // Note: still unrefined.
        {
          lookup l (src.vars[x_symexport]);
          md.symexport = l ? cast<bool> (l) : symexport;
        }

        // NOTE: see similar code in adhoc_buildscript_rule::apply().

        // Make sure the output directory exists.
        //
        // Is this the right thing to do? It does smell a bit, but then we do
        // worse things in inject_prerequisites() below. There is also no way
        // to postpone this until update since we need to extract and inject
        // header dependencies now (we don't want to be calling search() and
        // match() in update), which means we need to cache them now as well.
        // So the only alternative, it seems, is to cache the updates to the
        // database until later which will sure complicate (and slow down)
        // things.
        //
        if (dir != nullptr)
        {
          // We can do it properly by using execute_direct(). But this means
          // we will be switching to the execute phase with all the associated
          // overheads. At the same time, in case of update, creation of a
          // directory is not going to change the external state in any way
          // that would affect any parallel efforts in building the internal
          // state. So we are just going to create the directory directly.
          // Note, however, that we cannot modify the fsdir{} target since
          // this can very well be happening in parallel. But that's not a
          // problem since fsdir{}'s update is idempotent.
          //
          fsdir_rule::perform_update_direct (a, *dir);
        }

        // Note: the leading '@' is reserved for the module map prefix (see
        // extract_modules()) and no other line must start with it.
        //
        // NOTE: see also the predefs rule if changing anything here.
        //
        depdb dd (tp + ".d");

        // First should come the rule name/version.
        //
        if (dd.expect (rule_id) != nullptr)
          l4 ([&]{trace << "rule mismatch forcing update of " << t;});

        // Then the compiler checksum. Note that here we assume it
        // incorporates the (default) target so that if the compiler changes
        // but only in what it targets, then the checksum will still change.
        //
        if (dd.expect (cast<string> (rs[x_checksum])) != nullptr)
          l4 ([&]{trace << "compiler mismatch forcing update of " << t;});

        // Then the compiler environment checksum.
        //
        if (dd.expect (env_checksum) != nullptr)
          l4 ([&]{trace << "environment mismatch forcing update of " << t;});

        // Then the options checksum.
        //
        // The idea is to keep them exactly as they are passed to the compiler
        // since the order may be significant.
        //
        {
          sha256 cs;

          // These flags affect how we compile the source and/or the format of
          // depdb so factor them in.
          //
          cs.append (&md.pp, sizeof (md.pp));

          if (ut == unit_type::module_intf) // Note: still unrefined.
            cs.append (&md.symexport, sizeof (md.symexport));

          // If we track translate_include then we should probably also track
          // the cc.importable flag for each header we include, which would be
          // quite heavy-handed indeed. Or maybe we shouldn't bother with this
          // at all: after all include translation is an optimization so why
          // rebuild an otherwise up-to-date target?
          //
#if 0
          if (modules)
          {
            // While there is also the companion importable_headers map, it's
            // unlikely to change in a way that affects us without changes to
            // other things that we track (e.g., compiler version, etc).
            //
            if (const auto* v = cast_null<translatable_headers> (
                  t[x_translate_include]))
            {
              for (const auto& p: *v)
              {
                cs.append (p.first);
                cs.append (!p.second || *p.second);
              }
            }
          }
#endif
          if (md.pp != preprocessed::all)
          {
            append_options (cs, t, x_poptions);
            append_options (cs, t, c_poptions);

            // Hash *.export.poptions from prerequisite libraries.
            //
            append_library_options (cs, bs, a, t, li);
          }

          append_options (cs, t, c_coptions);
          append_options (cs, t, x_coptions);
          append_options (cs, cmode);

          if (md.pp != preprocessed::all)
            append_sys_hdr_options (cs); // Extra system header dirs (last).

          if (dd.expect (cs.string ()) != nullptr)
            l4 ([&]{trace << "options mismatch forcing update of " << t;});
        }

        // Finally the source file.
        //
        {
          const path& p (src.path ());
          assert (!p.empty ()); // Sanity check.

          if (dd.expect (p) != nullptr)
            l4 ([&]{trace << "source file mismatch forcing update of " << t;});
        }

        // If any of the above checks resulted in a mismatch (different
        // compiler, options, or source file) or if the depdb is newer than
        // the target (interrupted update), then do unconditional update.
        //
        // Note that load_mtime() can only be used in the execute phase so we
        // have to check for a cached value manually.
        //
        bool u;
        timestamp mt;

        if (dd.writing ())
          u = true;
        else
        {
          if ((mt = t.mtime ()) == timestamp_unknown)
            t.mtime (mt = mtime (tp)); // Cache.

          u = dd.mtime > mt;
        }

        // If updating for any of the above reasons, treat it as if doesn't
        // exist.
        //
        if (u)
          mt = timestamp_nonexistent;

        // Update prerequisite targets (normally just the source file).
        //
        // This is an unusual place and time to do it. But we have to do it
        // before extracting dependencies. The reasoning for source file is
        // pretty clear. What other prerequisites could we have? While
        // normally they will be some other sources (as in, static content
        // from src_root), it's possible they are some auto-generated stuff.
        // And it's possible they affect the preprocessor result. Say some ad
        // hoc/out-of-band compiler input file that is passed via the command
        // line. So, to be safe, we make sure everything is up to date.
        //
        for (const target* pt: pts)
        {
          if (pt == nullptr || pt == dir)
            continue;

          u = update (trace, a, *pt, u ? timestamp_unknown : mt) || u;
        }

        // Check if the source is already preprocessed to a certain degree.
        // This determines which of the following steps we perform and on
        // what source (original or preprocessed).
        //
        // Note: must be set on the src target.
        //
        if (const string* v = cast_null<string> (src[x_preprocessed]))
        try
        {
          md.pp = to_preprocessed (*v);
        }
        catch (const invalid_argument& e)
        {
          fail << "invalid " << x_preprocessed.name << " variable value "
               << "for target " << src << ": " << e;
        }

        unit tu;

        // If we have no #include directives (or header unit imports), then
        // skip header dependency extraction.
        //
        pair<file_cache::entry, bool> psrc (file_cache::entry (), false);
        if (md.pp < preprocessed::includes)
        {
          // Note: trace is used in a test.
          //
          l5 ([&]{trace << "extracting headers from " << src;});
          auto& is (tu.module_info.imports);
          extract_headers (a, bs, t, li, src, md, dd, u, mt, is, psrc);
          is.clear (); // No longer needed.
        }

        // Next we "obtain" the translation unit information. What exactly
        // "obtain" entails is tricky: If things changed, then we re-parse the
        // translation unit. Otherwise, we re-create this information from
        // depdb. We, however, have to do it here and now in case the database
        // is invalid and we still have to fallback to re-parse.
        //
        // Store the translation unit's checksum to detect ignorable changes
        // (whitespaces, comments, etc).
        //
        // Note that we skip all of this if we have deferred a failure from
        // the header extraction phase (none of the module information should
        // be relevant).
        //
        if (!md.deferred_failure)
        {
          optional<string> cs;
          if (string* l = dd.read ())
            cs = move (*l);
          else
            u = true; // Database is invalid, force re-parse.

          for (bool first (true);; first = false)
          {
            if (u)
            {
              // Flush depdb since it can be used (as a module map) by
              // parse_unit().
              //
              if (dd.writing ())
                dd.flush ();

              string ncs (
                parse_unit (a, t, li, src, psrc.first, md, dd.path, tu));

              if (!cs || *cs != ncs)
              {
                assert (first); // Unchanged TU has a different checksum?
                dd.write (ncs);
              }
              //
              // Don't clear the update flag if it was forced or the checksum
              // should not be relied upon.
              //
              else if (first && !ncs.empty ())
              {
                // Clear the update flag and set the touch flag. Unless there
                // is no (usable) object file, of course. See also the md.mt
                // logic below.
                //
                if (mt != timestamp_nonexistent)
                {
                  // Appended to by to_module_info() below.
                  //
                  tu.module_info.imports.clear ();

                  u = false;
                  md.touch = true;
                }
              }
            }

            if (modules)
            {
              if (u || !first)
              {
                string s (to_string (tu.type, tu.module_info));

                if (first)
                  dd.expect (s);
                else
                  dd.write (s);
              }
              else
              {
                if (string* l = dd.read ())
                {
                  tu.type = to_module_info (*l, tu.module_info);
                }
                else
                {
                  u = true; // Database is invalid, force re-parse.
                  continue;
                }
              }
            }

            break;
          }

          // Make sure the translation unit type matches the resulting target
          // type. Note that tu here is the unrefined type.
          //
          switch (tu.type)
          {
          case unit_type::non_modular:
          case unit_type::module_impl:
            {
              if (ut != unit_type::non_modular)
                fail << "translation unit " << src << " is not a module "
                     << "interface or partition" <<
                  info << "consider using " << x_src.name << "{} instead";
              break;
            }
          case unit_type::module_intf:
          case unit_type::module_intf_part:
          case unit_type::module_impl_part:
            {
              if (ut != unit_type::module_intf)
                fail << "translation unit " << src << " is a module "
                     << "interface or partition" <<
                  info << "consider using " << x_mod->name << "{} instead";
              break;
            }
          case unit_type::module_header:
            {
              assert (ut == unit_type::module_header);
              break;
            }
          }

          // Refine the non-modular/module-impl decision from match().
          //
          ut = md.type = tu.type;

          // Note: trace is used in a test.
          //
          l5 ([&]{trace << "extracting modules from " << src;});

          // Extract the module dependency information in addition to header
          // dependencies.
          //
          // NOTE: assumes that no further targets will be added into
          //       t.prerequisite_targets!
          //
          if (modules)
          {
            extract_modules (a, bs, t, li,
                             tts, src,
                             md, move (tu.module_info), dd, u);
          }
        }

        // If anything got updated, then we didn't rely on the cache. However,
        // the cached data could actually have been valid and the compiler run
        // in extract_headers() as well as the code above merely validated it.
        //
        // We do need to update the database timestamp, however. Failed that,
        // we will keep re-validating the cached data over and over again.
        //
        // @@ DRYRUN: note that for dry-run we would keep re-touching the
        // database on every run (because u is true). So for now we suppress
        // it (the file will be re-validated on the real run anyway). It feels
        // like support for reusing the (partially) preprocessed output (see
        // note below) should help solve this properly (i.e., we don't want
        // to keep re-validating the file on every subsequent dry-run as well
        // on the real run).
        //
        if (u && dd.reading () && !ctx.dry_run_option)
          dd.touch = timestamp_unknown;

        dd.close (false /* mtime_check */);
        md.dd = move (dd.path);

        // If the preprocessed output is suitable for compilation, then pass
        // it along.
        //
        if (psrc.second)
        {
          md.psrc = move (psrc.first);

          // Now is also the right time to unpin the cache entry (we don't do
          // it earlier because parse_unit() may need to read it).
          //
          md.psrc.unpin ();

          // Without modules keeping the (partially) preprocessed output
          // around doesn't buy us much: if the source/headers haven't changed
          // then neither will the object file. Modules make things more
          // interesting: now we may have to recompile an otherwise unchanged
          // translation unit because a named module BMI it depends on has
          // changed. In this case re-processing the translation unit would be
          // a waste and compiling the original source would break distributed
          // compilation.
          //
          // Note also that the long term trend will (hopefully) be for
          // modularized projects to get rid of #include's which means the
          // need for producing this partially preprocessed output will
          // (hopefully) gradually disappear. Or not, most C headers will stay
          // headers, and probably not importable.
          //
          // @@ TODO: no use keeping it if there are no named module imports
          //          (but see also file_cache::create() hint, and
          //          extract_headers() the cache case: there we just assume
          //          it exists if modules is true).
          //
          if (modules)
            md.psrc.temporary = false; // Keep.
        }

        // Above we may have ignored changes to the translation unit. The
        // problem is, unless we also update the target's timestamp, we will
        // keep re-checking this on subsequent runs and it is not cheap.
        // Updating the target's timestamp is not without problems either: it
        // will cause a re-link on a subsequent run. So, essentially, we
        // somehow need to remember two timestamps: one for checking
        // "preprocessor prerequisites" above and one for checking other
        // prerequisites (like modules) below. So what we are going to do is
        // "store" the first in the target file (so we do touch it) and the
        // second in depdb (which is never newer that the target).
        //
        // Perhaps when we start keeping the partially preprocessed output
        // this will fall away? Yes, please.
        //
        md.mt = u ? timestamp_nonexistent : dd.mtime;
      }

      switch (a)
      {
      case perform_update_id: return move (md);
      case perform_clean_id:
        {
          return [this, srct = &md.src.type ()] (action a, const target& t)
          {
            return perform_clean (a, t, *srct);
          };
        }
      default: return noop_recipe; // Configure update.
      }
    }

    void compile_rule::
    append_prefixes (prefix_map& m,
                     const scope& rs, const target& t,
                     const variable& var) const
    {
      tracer trace (x, "compile_rule::append_prefixes");

      if (auto l = t[var])
      {
        const auto& v (cast<strings> (l));

        for (auto i (v.begin ()), e (v.end ()); i != e; ++i)
        {
          const string& o (*i);

          // -I can either be in the "-Ifoo" or "-I foo" form. For MSVC it
          // can also be /I.
          //
          // Note that we naturally assume that -isystem, /external:I, etc.,
          // are not relevant here.
          //
          bool msvc (cclass == compiler_class::msvc);

          if (!((o[0] == '-' || (msvc && o[0] == '/')) && o[1] == 'I'))
            continue;

          dir_path d;

          try
          {
            if (o.size () == 2)
            {
              if (++i == e)
                break; // Let the compiler complain.

              d = dir_path (*i);
            }
            else
              d = dir_path (*i, 2, string::npos);
          }
          catch (const invalid_path& e)
          {
            fail << "invalid directory '" << e.path << "'"
                 << " in option '" << o << "'"
                 << " in variable " << var
                 << " for target " << t;
          }

          l6 ([&]{trace << "-I " << d;});

          if (d.relative ())
            fail << "relative directory " << d
                 << " in option '" << o << "'"
                 << " in variable " << var
                 << " for target " << t;

          // If the directory is not normalized, we can complain or normalize
          // it. Let's go with normalizing to minimize questions/complaints.
          //
          if (!d.normalized (false)) // Allow non-canonical dir separators.
            d.normalize ();

          // If we are not inside our project root, then ignore.
          //
          if (d.sub (rs.out_path ()))
            append_prefix (trace, m, t, move (d));
        }
      }
    }

    auto compile_rule::
    build_prefix_map (const scope& bs,
                      action a,
                      const target& t,
                      linfo li) const -> prefix_map
    {
      prefix_map pm;

      // First process our own.
      //
      const scope& rs (*bs.root_scope ());
      append_prefixes (pm, rs, t, x_poptions);
      append_prefixes (pm, rs, t, c_poptions);

      // Then process the include directories from prerequisite libraries.
      //
      appended_libraries ls;
      append_library_prefixes (ls, pm, bs, a, t, li);

      return pm;
    }

    // VC /showIncludes output. The first line is the file being compiled
    // (unless clang-cl; handled by our caller). Then we have the list of
    // headers, one per line, in this form (text can presumably be
    // translated):
    //
    // Note: including file: C:\Program Files (x86)\[...]\iostream
    //
    // Finally, if we hit a non-existent header, then we end with an error
    // line in this form:
    //
    // x.cpp(3): fatal error C1083: Cannot open include file: 'd/h.hpp':
    // No such file or directory
    //
    // @@ TODO: this is not the case for clang-cl: it issues completely
    //          different diagnostics and before any /showIncludes lines.
    //
    // Distinguishing between the include note and the include error is
    // easy: we can just check for C1083. Distinguising between the note and
    // other errors/warnings is harder: an error could very well end with
    // what looks like a path so we cannot look for the note but rather have
    // to look for an error. Here we assume that a line containing ' CNNNN:'
    // is an error. Should be robust enough in the face of language
    // translation, etc.
    //
    // It turns out C1083 is also used when we are unable to open the main
    // source file and the error line (which is printed after the first line
    // containing the file name) looks like this:
    //
    // c1xx: fatal error C1083: Cannot open source file: 's.cpp': No such
    // file or directory
    //
    // And it turns out C1083 is also used when we are unable to open a type
    // library specified with #import. In this case the error looks like this
    // (at least in VC 14, 15, and 16):
    //
    // ...\comdef.h: fatal error C1083: Cannot open type library file:
    // 'l.tlb': Error loading type library/DLL.
    //

    pair<size_t, size_t>
    msvc_sense_diag (const string&, char); // msvc.cxx

    static inline bool
    msvc_header_c1083 (const string& l, const pair<size_t, size_t>& pr)
    {
      return
        l.compare (pr.second, 5, "c1xx:")     != 0 && /* Not source file. */
        l.compare (pr.second, 9, "comdef.h:") != 0;   /* Not type library. */
    }

    // Extract the include path from the VC /showIncludes output line. Return
    // empty string if the line is not an include note or include error. Set
    // the good_error flag if it is an include error (which means the process
    // will terminate with the error status that needs to be ignored).
    //
    static string
    next_show (const string& l, bool& good_error)
    {
      // The include error should be the last line that we handle.
      //
      assert (!good_error);

      pair<size_t, size_t> pr (msvc_sense_diag (l, 'C'));
      size_t p (pr.first);

      if (p == string::npos)
      {
        // Include note.
        //
        // We assume the path is always at the end but need to handle both
        // absolute Windows and POSIX ones.
        //
        // Note that VC appears to always write the absolute path to the
        // included file even if it is ""-included and the source path is
        // relative. Aren't we lucky today?
        //
        p = l.rfind (':');

        if (p != string::npos)
        {
          // See if this one is part of the Windows drive letter.
          //
          if (p > 1 && p + 1 < l.size () && // 2 chars before, 1 after.
              l[p - 2] == ' '            &&
              alpha (l[p - 1])           &&
              path::traits_type::is_separator (l[p + 1]))
            p = l.rfind (':', p - 2);
        }

        if (p != string::npos)
        {
          // VC uses indentation to indicate the include nesting so there
          // could be any number of spaces after ':'. Skip them.
          //
          p = l.find_first_not_of (' ', p + 1);
        }

        if (p == string::npos)
          fail << "unable to parse /showIncludes include note line \""
               << l << '"';

        return string (l, p);
      }
      else if (l.compare (p, 4, "1083") == 0 && msvc_header_c1083 (l, pr))
      {
        // Include error.
        //
        // The path is conveniently quoted with ''. Or so we thought: turns
        // out different translations (e.g., Chinese) can use different quote
        // characters and some translations (e.g., Russian) don't use quotes
        // at all. But the overall structure seems to be stable:
        //
        // ...C1083: <translated>: [']d/h.hpp[']: <translated>
        //
        // Where `'` is some sort of a quote character which could to be
        // multi-byte (e.g., in Chinese).
        //
        // Plus, in some internal (debug?) builds the second <translated> part
        // may have the "No such file or directory (c:\...\p0prepro.c:1722)"
        // form (so it may contain `:`).
#if 0
        string l;
        //l = "...: fatal error C1083: ...: 'libhello/version.hxx': ..."; //en
        //l = "...: fatal error C1083: ...: libhello/version.hxx: ...";   //ru
        //l = "...: fatal error C1083: ...: '\xb0libhello/version.hxx\xa1': ..."; //zh
        //l = "...: fatal error C1083: ...: 'libhello/version.hxx': No such file or directory (c:\\...\\p0prepro.c:1722)";
        p = l.find ("1083") + 1;
        text << l;
#endif

        // Find first leading ':' that's followed by a space (after "C1083:").
        //
        size_t p1 (p + 4); // 1083
        while ((p1 = l.find (':', p1 + 1)) != string::npos && l[p1 + 1] != ' ')
          ;

        // Find first trailing ':' that's followed by a space.
        //
        size_t p2 (l.size ());
        while ((p2 = l.rfind (':', p2 - 1)) != string::npos && l[p2 + 1] != ' ')
          ;

        if (p1 != string::npos &&
            p2 != string::npos &&
            (p2 - p1) > 3 )        // At least ": x:".

        {
          p1 += 2; // Skip leading ": ".

          // Now p1 is the first character of the potentially quoted path
          // while p2 -- one past the last character.
          //
          // We now skip any characters at the beginning and at the end that
          // could be quotes: single/double quotes plus, to handle the mutli-
          // byte case, non-printable ASCII characters (the latter is a bit
          // iffy: a multi-byte sequence could have one of the bytes
          // printable; in Chinese the sequences are \x27\xb0 and \xa1\x27
          // where \x27 is `'`).
          //
          auto quote = [] (char c)
          {
            return c == '\'' || c == '"' || c < 0x20 || c > 0x7e;
          };

          for (; p1 != p2 && quote (l[p1]);     ++p1) ;
          for (; p2 != p1 && quote (l[p2 - 1]); --p2) ;

          if (p1 != p2)
          {
            good_error = true;
            return string (l, p1 , p2 - p1);
          }
        }

        fail << "unable to parse /showIncludes include error line \""
             << l << '"' << endf;
      }
      else
      {
        // Some other error.
        //
        return string ();
      }
    }

    void
    msvc_sanitize_cl (cstrings&); // msvc.cxx

    // GCC module mapper handler.
    //
    // Note that the input stream is non-blocking while output is blocking
    // and this function should be prepared to handle closed input stream.
    // Any unhandled io_error is handled by the caller as a generic module
    // mapper io error. Returning false terminates the communication.
    //
    struct compile_rule::gcc_module_mapper_state
    {
      size_t skip;              // Number of depdb entries to skip.
      size_t header_units = 0;  // Number of header units imported.
      module_imports& imports;  // Unused (potentially duplicate suppression).

      // Include translation (looked up lazily).
      //
      optional<const build2::cc::translatable_headers*> translatable_headers;

      small_vector<string, 2> batch; // Reuse buffers.
      size_t                  batch_n = 0;

      gcc_module_mapper_state (size_t s, module_imports& i)
          : skip (s), imports (i) {}
    };

    // The module mapper is called on one line of input at a time. It should
    // return nullopt if another line is expected (batch), false if the mapper
    // interaction should be terminated, and true if it should be continued.
    //
    optional<bool> compile_rule::
    gcc_module_mapper (gcc_module_mapper_state& st,
                       action a, const scope& bs, file& t, linfo li,
                       const string& l,
                       ofdstream& os,
                       depdb& dd, bool& update, bool& bad_error,
                       optional<prefix_map>& pfx_map, srcout_map& so_map) const
    {
      tracer trace (x, "compile_rule::gcc_module_mapper");

      // While the dynamic mapper is only used during preprocessing, we still
      // need to handle batching (GCC sends batches of imports even in this
      // mode; actually, not for header unit imports and module imports we
      // don't see here). Note that we cannot sidestep batching by handing one
      // request at a time; while this might work to a certain extent (due to
      // pipe buffering), there is no guarantee (see libcody issue #20).

      // Read in the entire batch trying hard to reuse the buffers.
      //
      small_vector<string, 2>& batch (st.batch);
      size_t& batch_n (st.batch_n);

      // Add the next line.
      //
      {
        if (batch.size () == batch_n)
          batch.push_back (l);
        else
          batch[batch_n] = l;

        batch_n++;
      }

      // Check if more is expected in this batch.
      //
      {
        string& r (batch[batch_n - 1]);

        if (r.back () == ';')
        {
          // Strip the trailing `;` word.
          //
          r.pop_back ();
          r.pop_back ();

          return nullopt;
        }
      }

      if (verb >= 3)
      {
        // It doesn't feel like buffering this would be useful.
        //
        // Note that we show `;` in requests/responses so that the result
        // could be replayed.
        //
        // @@ Should we print the pid we are talking to? It gets hard to
        //    follow once things get nested. But if all our diag will include
        //    some kind of id (dependency chain, thread?), then this will not
        //    be strictly necessary.
        //
        diag_record dr (text);
        for (size_t i (0); i != batch_n; ++i)
          dr << (i == 0 ? "  > " : " ;\n    ") << batch[i];
      }

      // Handle each request converting it into a response.
      //
      bool term (false);

      string tmp; // Reuse the buffer.
      for (size_t i (0); i != batch_n; ++i)
      {
        string& r (batch[i]);
        size_t rn (r.size ());

        // The protocol uses a peculiar quoting/escaping scheme that can be
        // summarized as follows (see the libcody documentation for details):
        //
        // - Words are seperated with spaces and/or tabs.
        //
        // - Words need not be quoted if they only containing characters from
        //   the [-+_/%.A-Za-z0-9] set.
        //
        // - Otherwise words need to be single-quoted.
        //
        // - Inside single-quoted words, the \n \t \' and \\ escape sequences
        //   are recognized.
        //
        // Note that we currently don't treat abutted quotes (as in a' 'b) as
        // a single word (it doesn't seem plausible that we will ever receive
        // something like this).
        //
        size_t b (0), e (0), n; bool q; // Next word.

        auto next = [&r, rn, &b, &e, &n, &q] () -> size_t
        {
          if (b != e)
            b = e;

          // Skip leading whitespaces.
          //
          for (; b != rn && (r[b] == ' ' || r[b] == '\t'); ++b) ;

          if (b != rn)
          {
            q = (r[b] == '\'');

            // Find first trailing whitespace or closing quote.
            //
            for (e = b + 1; e != rn; ++e)
            {
              // Note that we deal with invalid quoting/escaping in unquote().
              //
              switch (r[e])
              {
              case ' ':
              case '\t':
                if (q)
                  continue;
                else
                  break;
              case '\'':
                if (q)
                {
                  ++e; // Include closing quote (hopefully).
                  break;
                }
                else
                {
                  assert (false); // Abutted quote.
                  break;
                }
              case '\\':
                if (++e != rn) // Skip next character (hopefully).
                  continue;
                else
                  break;
              default:
                continue;
              }

              break;
            }

            n = e - b;
          }
          else
          {
            q = false;
            e = rn;
            n = 0;
          }

          return n;
        };

        // Unquote into tmp the current word returning false if malformed.
        //
        auto unquote = [&r, &b, &n, &q, &tmp] (bool clear = true) -> bool
        {
          if (q && n > 1)
          {
            size_t e (b + n - 1);

            if (r[b] == '\'' && r[e] == '\'')
            {
              if (clear)
                tmp.clear ();

              size_t i (b + 1);
              for (; i != e; ++i)
              {
                char c (r[i]);
                if (c == '\\')
                {
                  if (++i == e)
                  {
                    i = 0;
                    break;
                  }

                  c = r[i];
                  if      (c == 'n') c = '\n';
                  else if (c == 't') c = '\t';
                }
                tmp += c;
              }

              if (i == e)
                return true;
            }
          }

          return false;
        };

#if 0
#define UNQUOTE(x, y)                     \
        r = x; rn = r.size (); b = e = 0; \
        assert (next () && unquote () && tmp == y)

        UNQUOTE ("'foo bar'", "foo bar");
        UNQUOTE (" 'foo bar' ", "foo bar");
        UNQUOTE ("'foo\\\\bar'", "foo\\bar");
        UNQUOTE ("'\\'foo bar'", "'foo bar");
        UNQUOTE ("'foo bar\\''", "foo bar'");
        UNQUOTE ("'\\'foo\\\\bar\\''", "'foo\\bar'");

        fail << "all good";
#endif

        // Escape if necessary the specified string and append to r.
        //
        auto escape = [&r] (const string& s)
        {
          size_t b (0), e, n (s.size ());
          while (b != n && (e = s.find_first_of ("\\'\n\t", b)) != string::npos)
          {
            r.append (s, b, e - b); // Preceding chunk.

            char c (s[e]);
            r += '\\';
            r += (c == '\n' ? 'n' : c == '\t' ? 't' : c);
            b = e + 1;
          }

          if (b != n)
            r.append (s, b, e); // Final chunk.
        };

        // Quote and escape if necessary the specified string and append to r.
        //
        auto quote = [&r, &escape] (const string& s)
        {
          if (find_if (s.begin (), s.end (),
                       [] (char c)
                       {
                         return !((c >= 'a' && c <= 'z') ||
                                  (c >= '0' && c <= '9') ||
                                  (c >= 'A' && c <= 'Z') ||
                                  c == '-' || c == '_' || c == '/' ||
                                  c == '.' || c == '+' || c == '%');
                       }) == s.end ())
          {
            r += s;
          }
          else
          {
            r += '\'';
            escape (s);
            r += '\'';
          }
        };

#if 0
#define QUOTE(x, y)            \
        r.clear (); quote (x); \
        assert (r == y)

        QUOTE ("foo/Bar-7.h", "foo/Bar-7.h");

        QUOTE ("foo bar", "'foo bar'");
        QUOTE ("foo\\bar", "'foo\\\\bar'");
        QUOTE ("'foo bar", "'\\'foo bar'");
        QUOTE ("foo bar'", "'foo bar\\''");
        QUOTE ("'foo\\bar'", "'\\'foo\\\\bar\\''");

        fail << "all good";
#endif

        next (); // Request name.

        auto name = [&r, b, n, q] (const char* c) -> bool
        {
          // We can reasonably assume a command will never be quoted.
          //
          return (!q                       &&
                  r.compare (b, n, c) == 0 &&
                  (r[n] == ' '  || r[n] == '\t' || r[n] == '\0'));
        };

        // Handle the request by explicitly continuing to the next iteration
        // on success and optionally setting the reason on failure.
        //
        const char* w ("malformed request");

        if (name ("HELLO"))
        {
          // > HELLO <version> <compiler> <ident>
          // < HELLO <version> <mapper> [<flags>]
          //
          //@@ TODO: check protocol version.

          r = "HELLO 1 build2";
          continue;
        }
        else if (name ("MODULE-REPO"))
        {
          // > MODULE-REPO
          // < PATHNAME <repo-dir>

          // Return the current working directory to essentially disable this
          // functionality.
          //
          r = "PATHNAME .";
          continue;
        }
        // Turns out it's easiest to handle header IMPORT together with
        // INCLUDE since it can also trigger a re-search, etc. In a sense,
        // IMPORT is all of the INCLUDE logic (but skipping translation) plus
        // the BMI dependency synthesis. Note that we don't get named module
        // imports here.
        //
        else if (name ("MODULE-IMPORT") || name ("INCLUDE-TRANSLATE"))
        {
          // > MODULE-IMPORT <path> [<flags>]
          // < PATHNAME <bmi-path>
          //
          // > INCLUDE-TRANSLATE <path> [<flags>]
          // < BOOL [TRUE|FALSE]
          // < PATHNAME <bmi-path>

          bool imp (r[b] == 'M'); // import

          if (next ())
          {
            path f;
            if (!q)
              f = path (r, b, n);
            else if (unquote ())
              f = path (tmp);
            else
            {
              r = "ERROR 'malformed quoting/escaping in request'";
              continue;
            }

            bool exists (true);

            // The TU path we pass to the compiler is always absolute so any
            // ""-includes will also be absolute. As a result, the only way to
            // end up with a relative path is by using relative -I which
            // doesn't make much sense in our world (it will be relative to
            // CWD).
            //
            if (exists && f.relative ())
            {
              r = "ERROR 'relative header path ";
              escape (f.string ());
              r += '\'';
              continue;
            }

            // Note also that we may see multiple imports of the same header
            // if it's imported via multiple paths. There is nothing really we
            // can do about it since we have to have each path in the file
            // mapper (see below for details).
            //
            // At least in case of GCC, we don't see multiple imports for the
            // same path nor multiple inclusions, regardless of whether the
            // header uses #pragma once or include guards.

            // The skip_count logic: in a nutshell (and similar to the non-
            // mapper case), we may have "processed" some portion of the
            // headers based on the depdb cache and we need to avoid
            // re-processing them here. See the skip_count discussion for
            // details.
            //
            // Note also that we need to be careful not to decrementing the
            // count for re-searches and include translation.
            //
            bool skip (st.skip != 0);

            // The first part is the same for both include and import: resolve
            // the header path to target, update it, and trigger re-search if
            // necessary.
            //
            const file* ht (nullptr);
            auto& pts (t.prerequisite_targets[a]);

            // Enter, update, and see if we need to re-search this header.
            //
            bool updated (false), remapped;
            try
            {
              pair<const file*, bool> er (
                enter_header (
                  a, bs, t, li,
                  move (f), false /* cache */, false /* normalized */,
                  pfx_map, so_map));

              ht = er.first;
              remapped = er.second;

              if (remapped)
              {
                r = "ERROR 'remapping of headers not supported'";
                continue;
              }

              // If we couldn't enter this header as a target or find a rule
              // to update it, then it most likely means a misspelled header
              // (rather than a broken generated header setup) and our
              // diagnostics won't really add anything to the compiler's. So
              // let's only print it at -V or higher.
              //
              if (ht == nullptr) // f is still valid.
              {
                assert (!exists); // Sanity check.

                if (verb > 2)
                {
                  diag_record dr;
                  dr << error << "header " << f << " not found and no "
                     << "rule to generate it";

                  if (verb < 4)
                    dr << info << "re-run with --verbose=4 for more information";
                }

                throw failed ();
              }

              // Note that we explicitly update even for import (instead of,
              // say, letting the BMI rule do it implicitly) since we may need
              // to cause a re-search (see below).
              //
              if (!skip)
              {
                if (pts.empty () || pts.back () != ht)
                {
                  optional<bool> ir (inject_header (a, t,
                                                    *ht, timestamp_unknown,
                                                    verb > 2 /* fail */));
                  if (!ir)
                    throw failed ();

                  updated = *ir;
                }
                else
                  assert (exists);
              }
              else
                assert (exists && !remapped); // Maybe this should be an error.
            }
            catch (const failed&)
            {
              // If the header does not exist or could not be updated, do we
              // want our diagnostics, the compiler's, or both? We definitely
              // want the compiler's since it points to the exact location.
              // Ours could also be helpful. So while it will look a bit
              // messy, let's keep both (it would have been nicer to print
              // ours after the compiler's but that isn't easy).
              //
              // Note: if ht is NULL, f is still valid.
              //
              r = "ERROR 'unable to update header ";
              escape ((ht != nullptr ? ht->path () : f).string ());
              r += '\'';
              continue;
            }

            if (!imp) // Indirect prerequisite (see above).
              update = updated || update;

            // A mere update is not enough to cause a re-search. It either had
            // to also not exist or be remapped.
            //
            // @@ Currently impossible.
            //
            /*
            if ((updated && !exists) || remapped)
            {
              rs = "SEARCH";
              st.data = move (n); // Followup correlation.
              break;
            }
            */

            // Now handle INCLUDE and IMPORT differences.
            //
            const path& hp (ht->path ());
            const string& hs (hp.string ());

            // Reduce include translation to the import case.
            //
            if (!imp)
            {
              if (!st.translatable_headers)
                st.translatable_headers =
                  cast_null<translatable_headers> (t[x_translate_include]);

              if (*st.translatable_headers != nullptr)
              {
                auto& ths (**st.translatable_headers);

                // First look for the header path in the translatable headers
                // itself.
                //
                auto i (ths.find (hs)), ie (ths.end ());

                // Next look it up in the importable headers and then look up
                // the associated groups in the translatable headers.
                //
                if (i == ie)
                {
                  slock l (importable_headers->mutex);
                  auto& ihs (importable_headers->header_map);

                  auto j (ihs.find (hp)), je (ihs.end ());

                  if (j != je)
                  {
                    // The groups are ordered from the most to least specific.
                    //
                    for (const string& g: j->second)
                      if ((i = ths.find (g)) != ie)
                        break;
                  }

                  // Finally look for the `all` groups.
                  //
                  if (i == ie)
                  {
                    i = ths.find (header_group_all_importable);

                    if (i != ie)
                    {
                      // See if this header is marked as importable.
                      //
                      if (lookup l = (*ht)[c_importable])
                      {
                        if (!cast<bool> (l))
                          i = ie;
                      }
                      else if (j != je)
                      {
                        // See if this is one of ad hoc *-importable groups
                        // (currently only std-importable).
                        //
                        const auto& gs (j->second);
                        if (find (gs.begin (),
                                  gs.end (),
                                  header_group_std_importable) == gs.end ())
                          i = ie;
                      }
                      else
                        i = ie;
                    }

                    if (i == ie)
                      i = ths.find (header_group_all);
                  }
                }

                // Translate if we found an entry and it's not false.
                //
                imp = (i != ie && (!i->second || *i->second));
              }
            }

            if (imp)
            {
              try
              {
                // Synthesize the BMI dependency then update and add the BMI
                // target as a prerequisite.
                //
                const file& bt (make_header_sidebuild (a, bs, t, li, *ht));

                if (!skip)
                {
                  optional<bool> ir (inject_header (a, t,
                                                    bt, timestamp_unknown,
                                                    true /* fail */));
                  assert (ir); // Not from cache.
                  update = *ir || update;
                }

                const string& bp (bt.path ().string ());

                if (skip)
                  st.skip--;
                else
                {
                  // While the header path passed by the compiler is absolute
                  // (see the reason/check above), it is not necessarily
                  // normalized. And that's the path that the compiler will
                  // look for in the static mapping. So we have to write the
                  // original (which we may need to normalize when we read
                  // this mapping in extract_headers()).
                  //
                  // @@ This still breaks if the header path contains spaces.
                  //    GCC bug 110153.
                  //
                  tmp = "@ ";
                  if (!q) tmp.append (r, b, n);
                  else    unquote (false /* clear */); // Can't fail.
                  tmp += ' ';
                  tmp += bp;

                  dd.expect (tmp);
                  st.header_units++;
                }

                r = "PATHNAME ";
                quote (bp);
              }
              catch (const failed&)
              {
                r = "ERROR 'unable to update header unit for ";
                escape (hs);
                r += '\'';
                continue;
              }
            }
            else
            {
              if (skip)
                st.skip--;
              else
                dd.expect (hs);

              // Confusingly, TRUE means include textually and FALSE means we
              // don't know.
              //
              r = "BOOL TRUE";
            }

            continue;
          }
        }
        else
          w = "unexpected request";

        // Truncate the response batch and terminate the communication (see
        // also libcody issue #22).
        //
        tmp.assign (r, b, n); // Request name (unquoted).
        r = "ERROR '"; r += w; r += ' '; r += tmp; r += '\'';
        batch_n = i + 1;
        term = true;
        break;
      }

      if (verb >= 3)
      {
        diag_record dr (text);
        for (size_t i (0); i != batch_n; ++i)
          dr << (i == 0 ? "  < " : " ;\n    ") << batch[i];
      }

      // Write the response batch.
      //
      // @@ It's theoretically possible that we get blocked writing the
      //    response while the compiler gets blocked writing the diagnostics.
      //
      for (size_t i (0);; )
      {
        string& r (batch[i]);

        if (r.compare (0, 6, "ERROR ") == 0)
          bad_error = true;

        os.write (r.c_str (), static_cast<streamsize> (r.size ()));

        if (++i == batch_n)
        {
          os.put ('\n');
          break;
        }
        else
          os.write (" ;\n", 3);
      }

      os.flush ();

      batch_n = 0; // Start a new batch.

      return !term;
    }

    // The original module mapper implementation (c++-modules-ex GCC branch)
    //
    // @@ TMP remove at some point
#if 0
    void compile_rule::
    gcc_module_mapper (module_mapper_state& st,
                       action a, const scope& bs, file& t, linfo li,
                       ifdstream& is,
                       ofdstream& os,
                       depdb& dd, bool& update, bool& bad_error,
                       optional<prefix_map>& pfx_map, srcout_map& so_map) const
    {
      tracer trace (x, "compile_rule::gcc_module_mapper");

      // Read in the request line.
      //
      // Because the dynamic mapper is only used during preprocessing, we
      // can assume there is no batching and expect to see one line at a
      // time.
      //
      string rq;
#if 1
      if (!eof (getline (is, rq)))
      {
        if (rq.empty ())
          rq = "<empty>"; // Not to confuse with EOF.
      }
#else
      for (char buf[4096]; !is.eof (); )
      {
        streamsize n (is.readsome (buf, sizeof (buf) - 1));
        buf[n] = '\0';

        if (char* p = strchr (buf, '\n'))
        {
          *p = '\0';

          if (++p != buf + n)
            fail << "batched module mapper request: '" << p << "'";

          rq += buf;
          break;
        }
        else
          rq += buf;
      }
#endif

      if (rq.empty ()) // EOF
        return;

      // @@ MODHDR: Should we print the pid we are talking to? It gets hard to
      //            follow once things get nested. But if all our diag will
      //            include some kind of id (dependency chain, thread?), then
      //            this will not be strictly necessary.
      //
      if (verb >= 3)
        text << "  > " << rq;

      // Check for a command. If match, remove it and the following space from
      // the request string saving it in cmd (for diagnostics) unless the
      // second argument is false, and return true.
      //
      const char* cmd (nullptr);
      auto command = [&rq, &cmd] (const char* c, bool r = true)
      {
        size_t n (strlen (c));
        bool m (rq.compare (0, n, c) == 0 && rq[n] == ' ');

        if (m && r)
        {
          cmd = c;
          rq.erase (0, n + 1);
        }

        return m;
      };

      string rs;
      for (;;) // Breakout loop.
      {
        // Each command is reponsible for handling its auxiliary data while we
        // just clear it.
        //
        string data (move (st.data));

        if (command ("HELLO"))
        {
          // HELLO <ver> <kind> <ident>
          //
          //@@ MODHDR TODO: check protocol version.

          // We don't use "repository path" (whatever it is) so we pass '.'.
          //
          rs = "HELLO 0 build2 .";
        }
        //
        // Turns out it's easiest to handle IMPORT together with INCLUDE since
        // it can also trigger a re-search, etc. In a sense, IMPORT is all of
        // the INCLUDE logic (skipping translation) plus the BMI dependency
        // synthesis.
        //
        else if (command ("INCLUDE") || command ("IMPORT"))
        {
          // INCLUDE [<"']<name>[>"'] <path>
          // IMPORT [<"']<name>[>"'] <path>
          // IMPORT '<path>'
          //
          // <path> is the resolved path or empty if the header is not found.
          // It can be relative if it is derived from a relative path (either
          // via -I or includer). If <name> is single-quoted, then it cannot
          // be re-searched (e.g., implicitly included stdc-predef.h) and in
          // this case <path> is never empty.
          //
          // In case of re-search or include translation we may have to split
          // handling the same include or import across multiple commands.
          // Here are the scenarios in question:
          //
          // INCLUDE --> SEARCH -?-> INCLUDE
          // IMPORT  --> SEARCH -?-> IMPORT
          // INCLUDE --> IMPORT -?-> IMPORT
          //
          // The problem is we may not necessarily get the "followup" command
          // (the question marks above). We may not get the followup after
          // SEARCH because, for example, the newly found header has already
          // been included/imported using a different style/path. Similarly,
          // the IMPORT response may not be followed up with the IMPORT
          // command because this header has already been imported, for
          // example, using an import declaration. Throw into this #pragma
          // once, include guards, and how exactly the compiler deals with
          // them and things become truly unpredictable and hard to reason
          // about. As a result, for each command we have to keep the build
          // state consistent, specifically, without any "dangling" matched
          // targets (which would lead to skew dependency counts). Note: the
          // include translation is no longer a problem since we respond with
          // an immediate BMI.
          //
          // To keep things simple we are going to always add a target that we
          // matched to our prerequisite_targets. This includes the header
          // target when building the BMI: while not ideal, this should be
          // harmless provided we don't take its state/mtime into account.
          //
          // One thing we do want to handle specially is the "maybe-followup"
          // case discussed above. It is hard to distinguish from an unrelated
          // INCLUDE/IMPORT (we could have saved <name> and maybe correlated
          // based on that). But if we don't, then we will keep matching and
          // adding each target twice. What we can do, however, is check
          // whether this target is already in prerequisite_targets and skip
          // it if that's the case, which is a valid thing to do whether it is
          // a followup or an unrelated command. In fact, for a followup, we
          // only need to check the last element in prerequisite_targets.
          //
          // This approach strikes a reasonable balance between keeping things
          // simple and handling normal cases without too much overhead. Note
          // that we may still end up matching and adding the same targets
          // multiple times for pathological cases, like when the same header
          // is included using a different style/path, etc. We could, however,
          // take care of this by searching the entire prerequisite_targets,
          // which is always an option (and which would probably be required
          // if the compiler were to send the INCLUDE command before checking
          // for #pragma once or include guards, which GCC does not do).
          //
          // One thing that we cannot do without distinguishing followup and
          // unrelated commands is verify the remapped header found by the
          // compiler resolves to the expected target. So we will also do the
          // correlation via <name>.
          //
          bool imp (cmd[1] == 'M');

          path f;          // <path> or <name> if doesn't exist
          string n;        // [<"']<name>[>"']
          bool exists;     // <path> is not empty
          bool searchable; // <name> is not single-quoted
          {
            char q (rq[0]);                // Opening quote.
            q = (q ==  '<' ?  '>' :
                 q ==  '"' ?  '"' :
                 q == '\'' ? '\'' : '\0'); // Closing quote.

            size_t s (rq.size ()), qp; // Quote position.
            if (q == '\0' || (qp = rq.find (q, 1)) == string::npos)
              break; // Malformed command.

            n.assign (rq, 0, qp + 1);

            size_t p (qp + 1);
            if (imp && q == '\'' && p == s) // IMPORT '<path>'
            {
              exists = true;
              // Leave f empty and fall through.
            }
            else
            {
              if (p != s && rq[p++] != ' ') // Skip following space, if any.
                break;

              exists = (p != s);

              if (exists)
              {
                rq.erase (0, p);
                f = path (move (rq));
                assert (!f.empty ());
              }
              //else // Leave f empty and fall through.
            }

            if (f.empty ())
            {
              rq.erase (0, 1);   // Opening quote.
              rq.erase (qp - 1); // Closing quote and trailing space, if any.
              f = path (move (rq));
            }

            // Complete relative paths not to confuse with non-existent.
            //
            if (exists && !f.absolute ())
              f.complete ();

            searchable = (q != '\'');
          }

          // The skip_count logic: in a nutshell (and similar to the non-
          // mapper case), we may have "processed" some portion of the headers
          // based on the depdb cache and we need to avoid re-processing them
          // here. See the skip_count discussion for details.
          //
          // Note also that we need to be careful not to decrementing the
          // count for re-searches and include translation.
          //
          bool skip (st.skip != 0);

          // The first part is the same for both INCLUDE and IMPORT: resolve
          // the header path to target, update it, and trigger re-search if
          // necessary.
          //
          const file* ht (nullptr);
          auto& pts (t.prerequisite_targets[a]);

          // If this is a followup command (or indistinguishable from one),
          // then as a sanity check verify the header found by the compiler
          // resolves to the expected target.
          //
          if (data == n)
          {
            assert (!skip); // We shouldn't be re-searching while skipping.

            if (exists)
            {
              pair<const file*, bool> r (
                enter_header (
                  a, bs, t, li,
                  move (f), false /* cache */, false /* normalized */,
                  pfx_map, so_map));

              if (!r.second) // Shouldn't be remapped.
                ht = r.first;
            }

            if (ht != pts.back ())
            {
              ht = &pts.back ().target->as<file> ();
              rs = "ERROR expected header '" + ht->path ().string () +
                "' to be found instead";
              bad_error = true; // We expect an error from the compiler.
              break;
            }

            // Fall through.
          }
          else
          {
            // Enter, update, and see if we need to re-search this header.
            //
            bool updated (false), remapped;
            try
            {
              pair<const file*, bool> er (
                enter_header (
                  a, bs, t, li,
                  move (f), false /* cache */, false /* normalized */,
                  pfx_map, so_map));

              ht = er.first;
              remapped = er.second;

              if (remapped && !searchable)
              {
                rs = "ERROR remapping non-re-searchable header " + n;
                bad_error = true;
                break;
              }

              // If we couldn't enter this header as a target or find a rule
              // to update it, then it most likely means a misspelled header
              // (rather than a broken generated header setup) and our
              // diagnostics won't really add anything to the compiler's. So
              // let's only print it at -V or higher.
              //
              if (ht == nullptr) // f is still valid.
              {
                assert (!exists); // Sanity check.

                if (verb > 2)
                {
                  diag_record dr;
                  dr << error << "header '" << f << "' not found";

                  if (verb < 4)
                    dr << info << "re-run with --verbose=4 for more information";
                }

                throw failed ();
              }

              // Note that we explicitly update even for IMPORT (instead of,
              // say, letting the BMI rule do it implicitly) since we may need
              // to cause a re-search (see below).
              //
              if (!skip)
              {
                if (pts.empty () || pts.back () != ht)
                {
                  optional<bool> ir (inject_header (a, t,
                                                    *ht, timestamp_unknown,
                                                    verb > 2 /* fail */));
                  if (!ir)
                    throw failed ();

                  updated = *ir;
                }
                else
                  assert (exists);
              }
              else
                assert (exists && !remapped); // Maybe this should be an error.
            }
            catch (const failed&)
            {
              // If the header does not exist or could not be updated, do we
              // want our diagnostics, the compiler's, or both? We definitely
              // want the compiler's since it points to the exact location.
              // Ours could also be helpful. So while it will look a bit
              // messy, let's keep both (it would have been nicer to print
              // ours after the compiler's but that isn't easy).
              //
              // Note: if ht is NULL, f is still valid.
              //
              rs = !exists
                ? string ("INCLUDE")
                : ("ERROR unable to update header '" +
                   (ht != nullptr ? ht->path () : f).string () + '\'');

              bad_error = true;
              break;
            }

            if (!imp) // Indirect prerequisite (see above).
              update = updated || update;

            // A mere update is not enough to cause a re-search. It either had
            // to also not exist or be remapped.
            //
            if ((updated && !exists) || remapped)
            {
              rs = "SEARCH";
              st.data = move (n); // Followup correlation.
              break;
            }

            // Fall through.
          }

          // Now handle INCLUDE and IMPORT differences.
          //
          const string& hp (ht->path ().string ());

          // Reduce include translation to the import case.
          //
          if (!imp && xlate_hdr != nullptr)
          {
            auto i (lower_bound (
                      xlate_hdr->begin (), xlate_hdr->end (),
                      hp,
                      [] (const string& x, const string& y)
                      {
                        return path::traits_type::compare (x, y) < 0;
                      }));

            imp = (i != xlate_hdr->end () && *i == hp);
          }

          if (imp)
          {
            try
            {
              // Synthesize the BMI dependency then update and add the BMI
              // target as a prerequisite.
              //
              const file& bt (make_header_sidebuild (a, bs, t, li, *ht));

              if (!skip)
              {
                optional<bool> ir (inject_header (a, t,
                                                  bt, timestamp_unknown,
                                                  true /* fail */));
                assert (ir); // Not from cache.
                update = *ir || update;
              }

              const string& bp (bt.path ().string ());

              if (!skip)
              {
                // @@ MODHDR: we write normalized path while the compiler will
                //            look for the original. In particular, this means
                //            that paths with `..` won't work. Maybe write
                //            original for mapping and normalized for our use?
                //
                st.headers++;
                dd.expect ("@ '" + hp + "' " + bp);
              }
              else
                st.skip--;

              rs = "IMPORT " + bp;
            }
            catch (const failed&)
            {
              rs = "ERROR unable to update header unit '" + hp + '\'';
              bad_error = true;
              break;
            }
          }
          else
          {
            if (!skip)
              dd.expect (hp);
            else
              st.skip--;

            rs = "INCLUDE";
          }
        }

        break;
      }

      if (rs.empty ())
      {
        rs = "ERROR unexpected command '";

        if (cmd != nullptr)
        {
          rs += cmd; // Add the command back.
          rs += ' ';
        }

        rs += rq;
        rs += "'";

        bad_error = true;
      }

      if (verb >= 3)
        text << "  < " << rs;

      os << rs << endl;
    }
#endif

    //atomic_count cache_hit {0};
    //atomic_count cache_mis {0};
    //atomic_count cache_cls {0};

    // The fp path is only moved from on success.
    //
    // Note: this used to be a lambda inside extract_headers() so refer to the
    // body of that function for the overall picture.
    //
    pair<const file*, bool> compile_rule::
    enter_header (action a, const scope& bs, file& t, linfo li,
                  path&& fp, bool cache, bool norm,
                  optional<prefix_map>& pfx_map,
                  const srcout_map& so_map) const
    {
      tracer trace (x, "compile_rule::enter_header");

      // It's reasonable to expect the same header to be included by multiple
      // translation units, which means we will be re-doing this work over and
      // over again. And it's not exactly cheap, taking up to 50% of an
      // up-to-date check time on some projects. So we are going to cache the
      // header path to target mapping.
      //
      // While we pass quite a bit of specific "context" (target, base scope)
      // to enter_file(), here is the analysis why the result will not depend
      // on this context for the non-absent header (fp is absolute):
      //
      // 1. Let's start with the base scope (bs). Firstly, the base scope
      //    passed to map_extension() is the scope of the header (i.e., it is
      //    the scope of fp.directory()). Other than that, the target base
      //    scope is only passed to build_prefix_map() which is only called
      //    for the absent header (linfo is also only used here).
      //
      // 2. Next is the target (t). It is passed to build_prefix_map() but
      //    that doesn't matter for the same reason as in (1). Other than
      //    that, it is only passed to build2::search() which in turn passes
      //    it to target type-specific prerequisite search callback (see
      //    target_type::search) if one is not NULL. The target type in
      //    question here is one of the headers and we know all of them use
      //    the standard file_search() which ignores the passed target.
      //
      // 3. Finally, so_map could be used for an absolute fp. While we could
      //    simply not cache the result if it was used (second half of the
      //    result pair is true), there doesn't seem to be any harm in caching
      //    the remapped path->target mapping. In fact, if to think about it,
      //    there is no harm in caching the generated file mapping since it
      //    will be immediately generated and any subsequent inclusions we
      //    will "see" with an absolute path, which we can resolve from the
      //    cache.
      //
      // To put it another way, all we need to do is make sure that if we were
      // to not return an existing cache entry, the call to enter_file() would
      // have returned exactly the same path/target.
      //
      // @@ Could it be that the header is re-mapped in one config but not the
      //    other (e.g., when we do both in src and in out builds and we pick
      //    the generated header in src)? If so, that would lead to a
      //    divergence. I.e., we would cache the no-remap case first and then
      //    return it even though the re-map is necessary? Why can't we just
      //    check for re-mapping ourselves? A: the remapping logic in
      //    enter_file() is not exactly trivial.
      //
      //    But on the other hand, I think we can assume that different
      //    configurations will end up with different caches. In other words,
      //    we can assume that for the same "cc amalgamation" we use only a
      //    single "version" of a header. Seems reasonable.
      //
      // Note also that while it would have been nice to have a unified cc
      // cache, the map_extension() call is passed x_incs which is module-
      // specific. In other words, we may end up mapping the same header to
      // two different targets depending on whether it is included from, say,
      // C or C++ translation unit. We could have used a unified cache for
      // headers that were mapped using the fallback target type, which would
      // cover the installed headers. Maybe, one day (it's also possible that
      // separate caches reduce contention).
      //
      // Another related question is where we want to keep the cache: project,
      // strong amalgamation, or weak amalgamation (like module sidebuilds).
      // Some experimentation showed that weak has the best performance (which
      // suggest that a unified cache will probably be a win).
      //
      // Note also that we don't need to clear this cache since we never clear
      // the targets set. In other words, the only time targets are
      // invalidated is when we destroy the build context, which also destroys
      // the cache.
      //
      const config_module& hc (*header_cache_);

      // First check the cache.
      //
      config_module::header_key hk;

      bool e (fp.absolute ());
      if (e)
      {
        if (!norm)
        {
          normalize_external (fp, "header");
          norm = true;
        }

        hk.file = move (fp);
        hk.hash = hash<string> () (hk.file.string ());

        slock l (hc.header_map_mutex);
        auto i (hc.header_map.find (hk));
        if (i != hc.header_map.end ())
        {
          //cache_hit.fetch_add (1, memory_order_relaxed);
          return make_pair (i->second, false);
        }

        fp = move (hk.file);

        //cache_mis.fetch_add (1, memory_order_relaxed);
      }

      struct data
      {
        linfo li;
        optional<prefix_map>& pfx_map;
      } d {li, pfx_map};

      // If it is outside any project, or the project doesn't have such an
      // extension, assume it is a plain old C header.
      //
      auto r (enter_file (
                trace, "header",
                a, bs, t,
                fp, cache, norm,
                [this] (const scope& bs, const string& n, const string& e)
                {
                  return map_extension (bs, n, e, x_incs);
                },
                h::static_type,
                [this, &d] (action a, const scope& bs, const target& t)
                  -> const prefix_map&
                {
                  if (!d.pfx_map)
                    d.pfx_map = build_prefix_map (bs, a, t, d.li);

                  return *d.pfx_map;
                },
                so_map));

      // Cache.
      //
      if (r.first != nullptr)
      {
        hk.file = move (fp);

        // Calculate the hash if we haven't yet and re-calculate it if the
        // path has changed (header has been remapped).
        //
        if (!e || r.second)
          hk.hash = hash<string> () (hk.file.string ());

        const file* f;
        {
          ulock l (hc.header_map_mutex);
          auto p (hc.header_map.emplace (move (hk), r.first));
          f = p.second ? nullptr : p.first->second;
        }

        if (f != nullptr)
        {
          //cache_cls.fetch_add (1, memory_order_relaxed);

          // @@ TMP cleanup.
          //
#if 0
          assert (r.first == f);
#else
          if (r.first != f)
          {
            info   << "inconsistent header cache content" <<
              info << "encountered: " << *f <<
              info << "expected: " << *r.first <<
              info << "please report at "
                   << "https://github.com/build2/build2/issues/390";

            assert (r.first == f);
          }
#endif
        }
      }

      return r;
    }

    // Note: this used to be a lambda inside extract_headers() so refer to the
    // body of that function for the overall picture.
    //
    optional<bool> compile_rule::
    inject_header (action a, file& t,
                   const file& pt, timestamp mt, bool fail) const
    {
      tracer trace (x, "compile_rule::inject_header");

      return inject_file (trace, "header", a, t, pt, mt, fail);
    }

    // Extract and inject header dependencies. Return (in result) the
    // preprocessed source file as well as an indication if it is usable for
    // compilation (see below for details). Note that result is expected to
    // be initialized to {entry (), false}. Not using return type due to
    // GCC bug #107555.
    //
    // This is also the place where we handle header units which are a lot
    // more like auto-generated headers than modules. In particular, if a
    // header unit BMI is out-of-date, then we have to re-preprocess this
    // translation unit.
    //
    void compile_rule::
    extract_headers (action a,
                     const scope& bs,
                     file& t,
                     linfo li,
                     const file& src,
                     match_data& md,
                     depdb& dd,
                     bool& update,
                     timestamp mt,
                     module_imports& imports,
                     pair<file_cache::entry, bool>& result) const
    {
      tracer trace (x, "compile_rule::extract_headers");

      context& ctx (t.ctx);

      otype ot (li.type);

      bool reprocess (cast_false<bool> (t[c_reprocess]));

      file_cache::entry psrc;
      bool puse (true);

      // Preprocessed file extension.
      //
      const char* pext (x_assembler_cpp (src) ? ".Si"      :
                        x_objective (src)     ? x_obj_pext :
                        x_pext);

      // Preprocesor mode that preserves as much information as possible while
      // still performing inclusions. Also serves as a flag indicating whether
      // this (non-MSVC) compiler uses the separate preprocess and compile
      // setup.
      //
      const char* pp (nullptr);

      switch (ctype)
      {
      case compiler_type::gcc:
        {
          // -fdirectives-only is available since GCC 4.3.0.
          //
          if (cmaj > 4 || (cmaj == 4 && cmin >= 3))
          {
            // Note that for assembler-with-cpp GCC currently forces full
            // preprocessing in (what appears to be) an attempt to paper over
            // a deeper issue (see GCC bug 109534). If/when that bug gets
            // fixed, we can enable this on our side. Note that Clang's
            // -frewrite-includes also has issues (see below).
            //
            if (!x_assembler_cpp (src))
              pp = "-fdirectives-only";
          }

          break;
        }
      case compiler_type::clang:
        {
          // -frewrite-includes is available since Clang 3.2.0.
          //
          if (cmaj > 3 || (cmaj == 3 && cmin >= 2))
          {
            // While Clang's -frewrite-includes appears to work, there are
            // some issues with correctly tracking location information
            // (manifests itself as wrong line numbers in debug info, for
            // example). The result also appears to reference the .Si file
            // instead of the original source file for some reason.
            //
            if (!x_assembler_cpp (src))
              pp = "-frewrite-includes";
          }

          break;
        }
      case compiler_type::msvc:
        {
          // Asking MSVC to preserve comments doesn't really buy us anything
          // but does cause some extra buggy behavior.
          //
          //pp = "/C";
          break;
        }
      case compiler_type::icc:
        break;
      }

      // Initialize lazily, only if required.
      //
      environment env;
      cstrings args;
      string out; // Storage.

      // Some compilers in certain modes (e.g., when also producing the
      // preprocessed output) are incapable of writing the dependecy
      // information to stdout. In this case we use a temporary file.
      //
      auto_rmfile drm;

      // Here is the problem: neither GCC nor Clang allow -MG (treat missing
      // header as generated) when we produce any kind of other output (-MD).
      // And that's probably for the best since otherwise the semantics gets
      // pretty hairy (e.g., what is the exit code and state of the output)?
      //
      // One thing to note about generated headers: if we detect one, then,
      // after generating it, we re-run the compiler since we need to get
      // this header's dependencies.
      //
      // So this is how we are going to work around this problem: we first run
      // with -E but without -MG. If there are any errors (maybe because of
      // generated headers maybe not), we restart with -MG and without -E. If
      // this fixes the error (so it was a generated header after all), then
      // we have to restart at which point we go back to -E and no -MG. And we
      // keep yo-yoing like this. Missing generated headers will probably be
      // fairly rare occurrence so this shouldn't be too expensive.
      //
      // Actually, there is another error case we would like to handle: an
      // outdated generated header that is now causing an error (e.g., because
      // of a check that is now triggering #error or some such). So there are
      // actually three error cases: outdated generated header, missing
      // generated header, and some other error. To handle the outdated case
      // we need the compiler to produce the dependency information even in
      // case of an error. Clang does it, for VC we parse diagnostics
      // ourselves, but GCC does not (but a patch has been submitted).
      //
      // So the final plan is then as follows:
      //
      // 1. Start wothout -MG and with suppressed diagnostics.
      // 2. If error but we've updated a header, then repeat step 1.
      // 3. Otherwise, restart with -MG and diagnostics.
      //
      // Note that below we don't even check if the compiler supports the
      // dependency info on error. We just try to use it and if it's not
      // there we ignore the io error since the compiler has failed.
      //
      bool args_gen;     // Current state of args.
      size_t args_i (0); // Start of the -M/-MD "tail".

      // Ok, all good then? Not so fast, the rabbit hole is deeper than it
      // seems: When we run with -E we have to discard diagnostics. This is
      // not a problem for errors since they will be shown on the re-run but
      // it is for (preprocessor) warnings.
      //
      // Clang's -frewrite-includes is nice in that it preserves the warnings
      // so they will be shown during the compilation of the preprocessed
      // source. They are also shown during -E but that we discard. And unlike
      // GCC, in Clang -M does not imply -w (disable warnings) so it would
      // have been shown in -M -MG re-runs but we suppress that with explicit
      // -w. All is good in the Clang land then (even -Werror works nicely).
      //
      // GCC's -fdirective-only, on the other hand, processes all the
      // directives so they are gone from the preprocessed source. Here is
      // what we are going to do to work around this: we will sense if any
      // diagnostics has been written to stderr on the -E run. If that's the
      // case (but the compiler indicated success) then we assume they are
      // warnings and disable the use of the preprocessed output for
      // compilation. This in turn will result in compilation from source
      // which will display the warnings. Note that we may still use the
      // preprocessed output for other things (e.g., C++ module dependency
      // discovery). BTW, another option would be to collect all the
      // diagnostics and then dump it if the run is successful, similar to
      // the VC semantics (and drawbacks) described below.
      //
      // Finally, for VC, things are completely different: there is no -MG
      // equivalent and we handle generated headers by analyzing the
      // diagnostics. This means that unlike in the above two cases, the
      // preprocessor warnings are shown during dependency extraction, not
      // compilation. Not ideal but that's the best we can do. Or is it -- we
      // could implement ad hoc diagnostics sensing... It appears warnings are
      // in the C4000-C4999 code range though there can also be note lines
      // which don't have any C-code.
      //
      // BTW, triggering a warning in the VC preprocessor is not easy; there
      // is no #warning and pragmas are passed through to the compiler. One
      // way to do it is to redefine a macro, for example:
      //
      // hello.cxx(4): warning C4005: 'FOO': macro redefinition
      // hello.cxx(3): note: see previous definition of 'FOO'
      //
      // So seeing that it is hard to trigger a legitimate VC preprocessor
      // warning, for now, we will just treat them as errors by adding /WX.
      // BTW, another example of a plausible preprocessor warnings are C4819
      // and C4828 (character unrepresentable in source charset).
      //
      // Finally, if we are using the module mapper, then all this mess falls
      // away: we only run the compiler once, we let the diagnostics through,
      // we get a compiler error (with location information) if a header is
      // not found, and there is no problem with outdated generated headers
      // since we update/remap them before the compiler has a chance to read
      // them. Overall, this "dependency mapper" approach is how it should
      // have been done from the beginning. Note: that's the ideal world,
      // the reality is that the required mapper extensions are not (yet)
      // in libcody/GCC.

      // Note: diagnostics sensing is currently only supported if dependency
      // info is written to a file (see above).
      //
      bool sense_diag (false);

      // And here is another problem: if we have an already generated header
      // in src and the one in out does not yet exist, then the compiler will
      // pick the one in src and we won't even notice. Note that this is not
      // only an issue with mixing in and out of source builds (which does feel
      // wrong but is oh so convenient): this is also a problem with
      // pre-generated headers, a technique we use to make installing the
      // generator by end-users optional by shipping pre-generated headers.
      //
      // This is a nasty problem that doesn't seem to have a perfect solution
      // (except, perhaps, C++ modules and/or module mapper). So what we are
      // going to do is try to rectify the situation by detecting and
      // automatically remapping such mis-inclusions. It works as follows.
      //
      // First we will build a map of src/out pairs that were specified with
      // -I. Here, for performance and simplicity, we will assume that they
      // always come in pairs with out first and src second. We build this
      // map lazily only if we are running the preprocessor and reuse it
      // between restarts.
      //
      // With the map in hand we can then check each included header for
      // potentially having a doppelganger in the out tree. If this is the
      // case, then we calculate a corresponding header in the out tree and,
      // (this is the most important part), check if there is a target for
      // this header in the out tree. This should be fairly accurate and not
      // require anything explicit from the user.
      //
      // One tricky area in this setup are target groups: if the generated
      // sources are mentioned in the buildfile as a group, then there might
      // be no header target (yet). The way we solve this is by requiring code
      // generator rules to cooperate and create at least the header target as
      // part of the group creation. While not all members of the group may be
      // generated depending on the options (e.g., inline files might be
      // suppressed), headers are usually non-optional.
      //
      srcout_map so_map;

      // Dynamic module mapper.
      //
      bool mod_mapper (false);

      // The gen argument to init_args() is in/out. The caller signals whether
      // to force the generated header support and on return it signals
      // whether this support is enabled. If gen is false, then stderr is
      // expected to be either discarded or merged with sdtout.
      //
      // Return NULL if the dependency information goes to stdout and a
      // pointer to the temporary file path otherwise.
      //
      auto init_args = [a, &t, ot, li, reprocess, pext,
                        &src, &md, &psrc, &sense_diag, &mod_mapper, &bs,
                        pp, &env, &args, &args_gen, &args_i, &out, &drm,
                        &so_map, this]
        (bool& gen) -> const path*
      {
        context& ctx (t.ctx);

        const path* r (nullptr);

        if (args.empty ()) // First call.
        {
          assert (!gen);

          // We use absolute/relative paths in the dependency output to
          // distinguish existing headers from (missing) generated. Which
          // means we have to (a) use absolute paths in -I and (b) pass
          // absolute source path (for ""-includes). That (b) is a problem:
          // if we use an absolute path, then all the #line directives will be
          // absolute and all the diagnostics will have long, noisy paths
          // (actually, we will still have long paths for diagnostics in
          // headers).
          //
          // To work around this we used to pass a relative path to the source
          // file and then check every relative path in the dependency output
          // for existence in the source file's directory. This is not without
          // issues: it is theoretically possible for a generated header that
          // is <>-included and found via -I to exist in the source file's
          // directory. Note, however, that this is a lot more likely to
          // happen with prefix-less inclusion (e.g., <foo>) and in this case
          // we assume the file is in the project anyway. And if there is a
          // conflict with a prefixed include (e.g., <bar/foo>), then, well,
          // we will just have to get rid of quoted includes (which are
          // generally a bad idea, anyway).
          //
          // But then this approach (relative path) fell apart further when we
          // tried to implement precise changed detection: the preprocessed
          // output would change depending from where it was compiled because
          // of #line (which we could work around) and __FILE__/assert()
          // (which we can't really do anything about). So it looks like using
          // the absolute path is the lesser of all the evils (and there are
          // many).
          //
          // Note that we detect and diagnose relative -I directories lazily
          // when building the include prefix map.
          //
          args.push_back (cpath.recall_string ());

          // If we are re-processing the translation unit, then allow the
          // translation unit to detect header/module dependency extraction.
          // This can be used to work around separate preprocessing bugs in
          // the compiler.
          //
          if (reprocess)
            args.push_back ("-D__build2_preprocess");

          append_options (args, t, x_poptions);
          append_options (args, t, c_poptions);

          // Add *.export.poptions from prerequisite libraries.
          //
          append_library_options (args, bs, a, t, li);

          // Populate the src-out with the -I$out_base -I$src_base pairs.
          //
          {
            srcout_builder builder (ctx, so_map);

            // Try to be fast and efficient by reusing buffers as much as
            // possible.
            //
            string ds;

            for (auto i (args.begin ()), e (args.end ()); i != e; ++i)
            {
              const char* o (*i);

              // -I can either be in the "-Ifoo" or "-I foo" form. For VC it
              // can also be /I.
              //
              // Note also that append_library_options() may have translated
              // -I to -isystem or /external:I so we have to recognize those
              // as well.
              //
              {
                bool msvc (cclass == compiler_class::msvc);

                size_t p (0);
                if (o[0] == '-' || (msvc && o[0] == '/'))
                {
                  p = (o[1] == 'I'                                     ?  2 :
                       !msvc && strncmp (o + 1, "isystem",     7) == 0 ?  8 :
                       msvc  && strncmp (o + 1, "external:I", 10) == 0 ? 11 : 0);
                }

                if (p == 0)
                {
                  builder.skip ();
                  continue;
                }

                size_t n (strlen (o));
                if (n == p)
                {
                  if (++i == e)
                    break; // Let the compiler complain.

                  ds = *i;
                }
                else
                  ds.assign (o + p, n - p);
              }

              if (!ds.empty ())
              {
                // Note that we don't normalize the paths since it would be
                // quite expensive and normally the pairs we are inerested in
                // are already normalized (since they are usually specified as
                // -I$src/out_*). We just need to add a trailing directory
                // separator if it's not already there.
                //
                if (!dir_path::traits_type::is_separator (ds.back ()))
                  ds += dir_path::traits_type::directory_separator;

                dir_path d (move (ds), dir_path::exact); // Move the buffer in.

                // Ignore invalid paths (buffer is not moved).
                //
                if (!d.empty ())
                {
                  if (!builder.next (move (d)))
                    ds = move (d).string (); // Move the buffer back out.
                }
                else
                  builder.skip ();
              }
              else
                builder.skip ();
            }
          }

          if (md.symexport)
            append_symexport_options (args, t);

          // Some compile options (e.g., -std, -m) affect the preprocessor.
          //

          // Don't treat warnings as errors.
          //
          const char* werror (nullptr);
          switch (cclass)
          {
          case compiler_class::gcc:  werror = "-Werror"; break;
          case compiler_class::msvc: werror = "/WX";     break;
          }

          bool clang (ctype == compiler_type::clang);

          append_options (args, t, c_coptions, werror);
          append_options (args, t, x_coptions, werror);

          switch (cclass)
          {
          case compiler_class::msvc:
            {
              // /F*: style option availability (see perform_update()).
              //
              bool fc (cmaj >= 18 && cvariant != "clang");

              args.push_back ("/nologo");

              append_options (args, cmode);
              append_sys_hdr_options (args); // Extra system header dirs (last).

              // Note that for MSVC stderr is merged with stdout and is then
              // parsed, so no append_diag_color_options() call.

              // See perform_update() for details on the choice of options.
              //
              // NOTE: see also the predefs rule if adding anything here.
              //
              {
                bool sc (find_option_prefixes (
                           {"/source-charset:", "-source-charset:"}, args));
                bool ec (find_option_prefixes (
                           {"/execution-charset:", "-execution-charset:"}, args));

                if (!sc && !ec)
                  args.push_back ("/utf-8");
                else
                {
                  if (!sc)
                    args.push_back ("/source-charset:UTF-8");

                  if (!ec)
                    args.push_back ("/execution-charset:UTF-8");
                }
              }

              if (cvariant != "clang" && isystem (*this))
              {
                if (find_option_prefixes ({"/external:I", "-external:I"}, args) &&
                    !find_option_prefixes ({"/external:W", "-external:W"}, args))
                  args.push_back ("/external:W0");
              }

              if (x_lang == lang::cxx &&
                  !find_option_prefixes ({"/EH", "-EH"}, args))
                args.push_back ("/EHsc");

              // NOTE: see similar code in search_modules().
              //
              if (!find_option_prefixes ({"/MD", "/MT", "-MD", "-MT"}, args))
                args.push_back ("/MD");

              args.push_back ("/P");            // Preprocess to file.
              args.push_back ("/showIncludes"); // Goes to stdout (with diag).
              if (pp != nullptr)
                args.push_back (pp);            // /C (preserve comments).
              args.push_back ("/WX");           // Warning as error (see above).

              msvc_sanitize_cl (args);

              psrc = ctx.fcache->create (t.path () + pext, !modules);

              if (fc)
              {
                args.push_back ("/Fi:");
                args.push_back (psrc.path ().string ().c_str ());
              }
              else
              {
                out = "/Fi" + psrc.path ().string ();
                args.push_back (out.c_str ());
              }

              append_lang_options (args, md); // Compile as.
              gen = args_gen = true;
              break;
            }
          case compiler_class::gcc:
            {
              append_options (args, cmode);
              append_sys_hdr_options (args); // Extra system header dirs (last).

              // If not gen, then stderr is discarded.
              //
              if (gen)
                append_diag_color_options (args);

              // See perform_update() for details on the choice of options.
              //
              // NOTE: see also the predefs rule if adding anything here.
              //
              if (!find_option_prefix ("-finput-charset=", args))
                args.push_back ("-finput-charset=UTF-8");

              if (ot == otype::s)
              {
                if (tclass == "linux" || tclass == "bsd")
                  args.push_back ("-fPIC");
              }

              if (ctype == compiler_type::clang && tsys == "win32-msvc")
              {
                if (!find_options ({"-nostdlib", "-nostartfiles"}, args))
                {
                  args.push_back ("-D_MT");
                  args.push_back ("-D_DLL");
                }
              }

              if (ctype == compiler_type::clang && cvariant == "emscripten")
              {
                if (x_lang == lang::cxx)
                {
                  if (!find_option_prefix ("DISABLE_EXCEPTION_CATCHING=", args))
                  {
                    args.push_back ("-s");
                    args.push_back ("DISABLE_EXCEPTION_CATCHING=0");
                  }
                }
              }

              // Setup the dynamic module mapper if needed.
              //
              // Note that it's plausible in the future we will use it even if
              // modules are disabled, for example, to implement better -MG.
              // In which case it will have probably be better called a
              // "dependency mapper".
              //
              if (modules)
              {
                if (ctype == compiler_type::gcc)
                {
                  args.push_back ("-fmodule-mapper=<>");
                  mod_mapper = true;
                }
              }

              // Depending on the compiler, decide whether (and how) we can
              // produce preprocessed output as a side effect of dependency
              // extraction.
              //
              // Note: -MM -MG skips missing <>-included.

              // Clang's -M does not imply -w (disable warnings). We also
              // don't need them in the -MD case (see above) so disable for
              // both.
              //
              if (clang)
                args.push_back ("-w");

              append_lang_options (args, md);

              if (pp != nullptr)
              {
                // With the GCC module mapper the dependency information is
                // written directly to depdb by the mapper.
                //
                if (ctype == compiler_type::gcc && mod_mapper)
                {
                  // Note that in this mode we don't have -MG re-runs. In a
                  // sense we are in the -MG mode (or, more precisely, the "no
                  // -MG required" mode) right away.
                  //
                  args.push_back ("-E");
                  args.push_back (pp);
                  gen = args_gen = true;
                  r = &drm.path; // Bogus/hack to force desired process start.
                }
                else
                {
                  // Previously we used '*' as a target name but it gets
                  // expanded to the current directory file names by GCC (4.9)
                  // that comes with MSYS2 (2.4). Yes, this is the (bizarre)
                  // behavior of GCC being executed in the shell with -MQ '*'
                  // option and not just -MQ *.
                  //
                  args.push_back ("-MQ"); // Quoted target name.
                  args.push_back ("^");   // Old versions can't do empty.

                  // Note that the options are carefully laid out to be easy
                  // to override (see below).
                  //
                  args_i = args.size ();

                  args.push_back ("-MD");
                  args.push_back ("-E");
                  args.push_back (pp);

                  // Dependency output.
                  //
                  // GCC until version 8 was not capable of writing the
                  // dependency information to stdout. We also either need to
                  // sense the diagnostics on the -E runs (which we currently
                  // can only do if we don't need to read stdout) or we could
                  // be communicating with the module mapper via stdin/stdout.
                  //
                  if (ctype == compiler_type::gcc)
                  {
                    // Use the .t extension (for "temporary"; .d is taken).
                    //
                    r = &(drm = auto_rmfile (t.path () + ".t")).path;
                  }

                  args.push_back ("-MF");
                  args.push_back (r != nullptr ? r->string ().c_str () : "-");

                  sense_diag = (ctype == compiler_type::gcc);
                  gen = args_gen = false;
                }

                // Preprocessor output.
                //
                psrc = ctx.fcache->create (t.path () + pext, !modules);
                args.push_back ("-o");
                args.push_back (psrc.path ().string ().c_str ());
              }
              else
              {
                args.push_back ("-MQ");
                args.push_back ("^");
                args.push_back ("-M");
                args.push_back ("-MG"); // Treat missing headers as generated.
                gen = args_gen = true;
              }

              break;
            }
          }

          args.push_back (src.path ().string ().c_str ());
          args.push_back (nullptr);

          // Note: only doing it here.
          //
          if (!env.empty ())
            env.push_back (nullptr);
        }
        else
        {
          assert (gen != args_gen && args_i != 0);

          size_t i (args_i);

          if (gen)
          {
            // Overwrite.
            //
            args[i++] = "-M";
            args[i++] = "-MG";
            args[i++] = src.path ().string ().c_str ();
            args[i]   = nullptr;

            if (ctype == compiler_type::gcc)
            {
              sense_diag = false;
            }
          }
          else
          {
            // Restore.
            //
            args[i++] = "-MD";
            args[i++] = "-E";
            args[i++] = pp;
            args[i]   = "-MF";

            if (ctype == compiler_type::gcc)
            {
              r = &drm.path;
              sense_diag = true;
            }
          }

          args_gen = gen;
        }

        return r;
      };

      // Build the prefix map lazily only if we have non-existent files.
      // Also reuse it over restarts since it doesn't change.
      //
      optional<prefix_map> pfx_map;

      // If any prerequisites that we have extracted changed, then we have to
      // redo the whole thing. The reason for this is auto-generated headers:
      // the updated header may now include a yet-non-existent header. Unless
      // we discover this and generate it (which, BTW, will trigger another
      // restart since that header, in turn, can also include auto-generated
      // headers), we will end up with an error during compilation proper.
      //
      // One complication with this restart logic is that we will see a
      // "prefix" of prerequisites that we have already processed (i.e., they
      // are already in our prerequisite_targets list) and we don't want to
      // keep redoing this over and over again. One thing to note, however, is
      // that the prefix that we have seen on the previous run must appear
      // exactly the same in the subsequent run. The reason for this is that
      // none of the files that it can possibly be based on have changed and
      // thus it should be exactly the same. To put it another way, the
      // presence or absence of a file in the dependency output can only
      // depend on the previous files (assuming the compiler outputs them as
      // it encounters them and it is hard to think of a reason why would
      // someone do otherwise). And we have already made sure that all those
      // files are up to date. And here is the way we are going to exploit
      // this: we are going to keep track of how many prerequisites we have
      // processed so far and on restart skip right to the next one.
      //
      // And one more thing: most of the time this list of headers would stay
      // unchanged and extracting them by running the compiler every time is a
      // bit wasteful. So we are going to cache them in the depdb. If the db
      // hasn't been invalidated yet (e.g., because the compiler options have
      // changed), then we start by reading from it. If anything is out of
      // date then we use the same restart and skip logic to switch to the
      // compiler run.
      //
      size_t skip_count (0);

      // Enter as a target, update, and add to the list of prerequisite
      // targets a header file. Depending on the cache flag, the file is
      // assumed to either have come from the depdb cache or from the compiler
      // run. Return true if the extraction process should be restarted and
      // false otherwise. Return nullopt if the header is not found and cannot
      // be generated, the diagnostics has been issued, but the failure has
      // been deferred to the compiler run in order to get better diagnostics.
      //
      auto add = [a, &bs, &t, li,
                  &pfx_map, &so_map,
                  &dd, &skip_count,
                  this] (path hp, bool cache, timestamp mt) -> optional<bool>
      {
        context& ctx (t.ctx);

        // We can only defer the failure if we will be running the compiler.
        //
        // We also used to only do it in the "keep going" mode but that proved
        // to be inconvenient: some users like to re-run a failed build with
        // -s not to get "swamped" with errors.
        //
        auto fail = [&ctx] (const auto& h) -> optional<bool>
        {
          bool df (!ctx.match_only && !ctx.dry_run_option);

          diag_record dr;
          dr << error << "header " << h << " not found and no rule to "
             << "generate it";

          if (df)
            dr << info << "failure deferred to compiler diagnostics";

          if (verb < 4)
            dr << info << "re-run with --verbose=4 for more information";

          if (df)
            return nullopt;
          else
            dr << endf;
        };

        if (const file* ht = enter_header (
              a, bs, t, li,
              move (hp), cache, cache /* normalized */,
              pfx_map, so_map).first)
        {
          // If we are reading the cache, then it is possible the file has
          // since been removed (think of a header in /usr/local/include that
          // has been uninstalled and now we need to use one from
          // /usr/include). This will lead to the match failure which we
          // translate to a restart. And, yes, this case will trip up
          // inject_header(), not enter_header().
          //
          if (optional<bool> u = inject_header (a, t, *ht, mt, false /*fail*/))
          {
            // Verify/add it to the dependency database.
            //
            if (!cache)
              dd.expect (ht->path ());

            skip_count++;
            return *u;
          }
          else if (cache)
          {
            dd.write (); // Invalidate this line.
            return true;
          }
          else
            return fail (*ht);
        }
        else
          return fail (hp); // hp is still valid.
      };

      // As above but for a header unit. Note that currently it is only used
      // for the cached case (the other case is handled by the mapper). We
      // also assume that the path may not be normalized (see below).
      //
      auto add_unit = [a, &bs, &t, li,
                       &pfx_map, &so_map,
                       &dd, &skip_count, &md,
                       this] (path hp, path bp, timestamp mt) -> optional<bool>
      {
        context& ctx (t.ctx);
        bool df (!ctx.match_only && !ctx.dry_run_option);

        const file* ht (
          enter_header (a, bs, t, li,
                        move (hp), true /* cache */, false /* normalized */,
                        pfx_map, so_map).first);

        if (ht == nullptr) // hp is still valid.
        {
          diag_record dr;
          dr << error << "header " << hp << " not found and no rule to "
             << "generate it";

          if (df)
            dr << info << "failure deferred to compiler diagnostics";

          if (verb < 4)
            dr << info << "re-run with --verbose=4 for more information";

          if (df) return nullopt; else dr << endf;
        }

        // Again, looks like we have to update the header explicitly since
        // we want to restart rather than fail if it cannot be updated.
        //
        if (inject_header (a, t, *ht, mt, false /* fail */))
        {
          const file& bt (make_header_sidebuild (a, bs, t, li, *ht));

          // It doesn't look like we need the cache semantics here since given
          // the header, we should be able to build its BMI. In other words, a
          // restart is not going to change anything.
          //
          optional<bool> u (inject_header (a, t, bt, mt, true /* fail */));
          assert (u); // Not from cache.

          if (bt.path () == bp)
          {
            md.header_units++;
            skip_count++;
            return *u;
          }
        }

        dd.write (); // Invalidate this line.
        return true;
      };

      // See init_args() above for details on generated header support.
      //
      bool gen (false);
      optional<bool>   force_gen;
      optional<size_t> force_gen_skip; // Skip count at last force_gen run.

      const path* drmp (nullptr); // Points to drm.path () if active.

      // If things go wrong (and they often do in this area), give the user a
      // bit extra context.
      //
      auto df = make_diag_frame (
        [&src](const diag_record& dr)
        {
          if (verb != 0)
            dr << info << "while extracting header dependencies from " << src;
        });

      // If nothing so far has invalidated the dependency database, then try
      // the cached data before running the compiler.
      //
      bool cache (!update);

      for (bool restart (true); restart; cache = false)
      {
        restart = false;

        if (cache)
        {
          // If any, this is always the first run.
          //
          assert (skip_count == 0);

          // We should always end with a blank line.
          //
          for (;;)
          {
            string* l (dd.read ());

            // If the line is invalid, run the compiler.
            //
            if (l == nullptr)
            {
              restart = true;
              break;
            }

            if (l->empty ()) // Done, nothing changed.
            {
              // If modules are enabled, then we keep the preprocessed output
              // around (see apply() for details). Unless reprocessing was
              // requested.
              //
              if (modules && !reprocess)
              {
                result.first = ctx.fcache->create_existing (t.path () + pext);
                result.second = true;
              }

              return;
            }

            // This can be a header or a header unit (mapping).
            //
            // If this header (unit) came from the depdb, make sure it is no
            // older than the target (if it has changed since the target was
            // updated, then the cached data is stale).
            //
            optional<bool> r;
            if ((*l)[0] == '@')
            {
              // @@ What if the header path contains spaces? How is GCC
              //    handling this?

              size_t p (l->find (' ', 2));

              if (p != string::npos)
              {
                // Note that the header path is absolute and commonly but not
                // necessarily normalized.
                //
                path h (*l, 2, p - 2);
                path b (move (l->erase (0, p + 1)));

                r = add_unit (move (h), move (b), mt);
              }
              else
                r = true; // Corrupt database?
            }
            else
              r = add (path (move (*l)), true /* cache */, mt);

            if (r)
            {
              restart = *r;

              if (restart)
              {
                update = true;
                l6 ([&]{trace << "restarting (cache)";});
                break;
              }
            }
            else
            {
              // Trigger recompilation and mark as expected to fail.
              //
              update = true;
              md.deferred_failure = true;

              // Bail out early if we have deferred a failure.
              //
              return;
            }
          }
        }
        else
        {
          try
          {
            if (force_gen)
              gen = *force_gen;

            if (args.empty () || gen != args_gen)
              drmp = init_args (gen);

            // If we are producing the preprocessed output, get its write
            // handle.
            //
            file_cache::write psrcw (psrc
                                     ? psrc.init_new ()
                                     : file_cache::write ());

            if (verb >= 3)
              print_process (args.data ()); // Disable pipe mode.

            process pr;

            // We use the fdstream_mode::skip mode on stdout (cannot be used
            // on both) and so dbuf must be destroyed (closed) first.
            //
            ifdstream is (ifdstream::badbit);
            diag_buffer dbuf (ctx);

            try
            {
              // Assume the preprocessed output (if produced) is usable
              // until proven otherwise.
              //
              puse = true;

              // Save the timestamp just before we start preprocessing. If
              // we depend on any header that has been updated since, then
              // we should assume we've "seen" the old copy and re-process.
              //
              timestamp pmt (system_clock::now ());

              // In some cases we may need to ignore the error return status.
              // The good_error flag keeps track of that. Similarly, sometimes
              // we expect the error return status based on the output that we
              // see. The bad_error flag is for that.
              //
              bool good_error (false), bad_error (false);

              if (mod_mapper) // Dependency info is implied by mapper requests.
              {
                assert (gen && !sense_diag); // Not used in this mode.

                // Note that here we use the skip mode on the diagnostics
                // stream which means we have to use own instance of stdout
                // stream for the correct destruction order (see below).
                //
                pr = process (cpath,
                              args,
                              -1,
                              -1,
                              diag_buffer::pipe (ctx),
                              nullptr, // CWD
                              env.empty () ? nullptr : env.data ());

                dbuf.open (args[0],
                           move (pr.in_efd),
                           fdstream_mode::non_blocking |
                           fdstream_mode::skip);
                try
                {
                  gcc_module_mapper_state mm_state (skip_count, imports);

                  // Note that while we read both streams until eof in normal
                  // circumstances, we cannot use fdstream_mode::skip for the
                  // exception case on both of them: we may end up being
                  // blocked trying to read one stream while the process may
                  // be blocked writing to the other. So in case of an
                  // exception we only skip the diagnostics and close the
                  // mapper stream hard. The latter (together with closing of
                  // the stdin stream) should happen first so the order of
                  // the following variable is important.
                  //
                  // Note also that we open the stdin stream in the blocking
                  // mode.
                  //
                  ifdstream is (move (pr.in_ofd),
                                fdstream_mode::non_blocking,
                                ifdstream::badbit); // stdout
                  ofdstream os (move (pr.out_fd));  // stdin (badbit|failbit)

                  // Read until we reach EOF on all streams.
                  //
                  // Note that if dbuf is not opened, then we automatically
                  // get an inactive nullfd entry.
                  //
                  fdselect_set fds {is.fd (), dbuf.is.fd ()};
                  fdselect_state& ist (fds[0]);
                  fdselect_state& dst (fds[1]);

                  bool more (false);
                  for (string l; ist.fd != nullfd || dst.fd != nullfd; )
                  {
                    // @@ Currently we will accept a (potentially truncated)
                    //    line that ends with EOF rather than newline.
                    //
                    if (ist.fd != nullfd && getline_non_blocking (is, l))
                    {
                      if (eof (is))
                      {
                        os.close ();
                        is.close ();

                        if (more)
                          throw_generic_ios_failure (EIO, "unexpected EOF");

                        ist.fd = nullfd;
                      }
                      else
                      {
                        optional<bool> r (
                          gcc_module_mapper (mm_state,
                                             a, bs, t, li,
                                             l, os,
                                             dd, update, bad_error,
                                             pfx_map, so_map));

                        more = !r.has_value ();

                        if (more || *r)
                          l.clear ();
                        else
                        {
                          os.close ();
                          is.close ();
                          ist.fd = nullfd;
                        }
                      }

                      continue;
                    }

                    ifdselect (fds);

                    if (dst.ready)
                    {
                      if (!dbuf.read ())
                        dst.fd = nullfd;
                    }
                  }

                  md.header_units += mm_state.header_units;
                }
                catch (const io_error& e)
                {
                  // Note that diag_buffer handles its own io errors so this
                  // is about mapper stdin/stdout.
                  //
                  if (pr.wait ())
                    fail << "io error handling " << x_lang << " compiler "
                         << "module mapper request: " << e;

                  // Fall through.
                }

                // The idea is to reduce this to the stdout case.
                //
                // We now write directly to depdb without generating and then
                // parsing an intermadiate dependency makefile.
                //
                pr.wait ();
                pr.in_ofd = nullfd;
              }
              else
              {
                // If we have no generated header support, then suppress all
                // diagnostics (if things go badly we will restart with this
                // support).
                //
                if (drmp == nullptr) // Dependency info goes to stdout.
                {
                  assert (!sense_diag); // Note: could support if necessary.

                  // For VC with /P the dependency info and diagnostics all go
                  // to stderr so redirect it to stdout.
                  //
                  int err (
                    cclass == compiler_class::msvc ?  1 : // stdout
                    !gen                           ? -2 : // /dev/null
                    diag_buffer::pipe (ctx, sense_diag /* force */));

                  pr = process (
                    cpath,
                    args,
                    0,
                    -1,
                    err,
                    nullptr, // CWD
                    env.empty () ? nullptr : env.data ());

                  if (cclass != compiler_class::msvc && gen)
                  {
                    dbuf.open (args[0],
                               move (pr.in_efd),
                               fdstream_mode::non_blocking); // Skip on stdout.
                  }
                }
                else // Dependency info goes to temporary file.
                {
                  // Since we only need to read from one stream (dbuf) let's
                  // use the simpler blocking setup.
                  //
                  int err (
                    !gen && !sense_diag ? -2 : // /dev/null
                    diag_buffer::pipe (ctx, sense_diag /* force */));

                  pr = process (cpath,
                                args,
                                0,
                                2, // Send stdout to stderr.
                                err,
                                nullptr, // CWD
                                env.empty () ? nullptr : env.data ());

                  if (gen || sense_diag)
                  {
                    dbuf.open (args[0], move (pr.in_efd));
                    dbuf.read (sense_diag /* force */);
                  }

                  if (sense_diag)
                  {
                    if (!dbuf.buf.empty ())
                    {
                      puse = false;
                      dbuf.buf.clear (); // Discard.
                    }
                  }

                  // The idea is to reduce this to the stdout case.
                  //
                  // Note that with -MG we want to read dependency info even
                  // if there is an error (in case an outdated header file
                  // caused it).
                  //
                  pr.wait ();
                  pr.in_ofd = fdopen (*drmp, fdopen_mode::in);
                }
              }

              // Read and process dependency information, if any.
              //
              if (pr.in_ofd != nullfd)
              {
                // We have two cases here: reading from stdout and potentially
                // stderr (dbuf) or reading from file (see the process startup
                // code above for details). If we have to read from two
                // streams, then we have to use the non-blocking setup. But we
                // cannot use the non-blocking setup uniformly because on
                // Windows it's only suppored for pipes. So things are going
                // to get a bit hairy.
                //
                // And there is another twist to this: for MSVC we redirect
                // stderr to stdout since the header dependency information is
                // part of the diagnostics. If, however, there is some real
                // diagnostics, we need to pass it through, potentially with
                // buffering. The way we achieve this is by later opening dbuf
                // in the EOF state and using it to buffer or stream the
                // diagnostics.
                //
                bool nb (dbuf.is.is_open ());

                // We may not read all the output (e.g., due to a restart).
                // Before we used to just close the file descriptor to signal
                // to the other end that we are not interested in the rest.
                // This works fine with GCC but Clang (3.7.0) finds this
                // impolite and complains, loudly (broken pipe). So now we are
                // going to skip until the end.
                //
                // Note that this means we are not using skip on dbuf (see
                // above for the destruction order details).
                //
                {
                  fdstream_mode m (fdstream_mode::text |
                                   fdstream_mode::skip);

                  if (nb)
                    m |= fdstream_mode::non_blocking;

                  is.open (move (pr.in_ofd), m);
                }

                fdselect_set fds;
                if (nb)
                  fds = {is.fd (), dbuf.is.fd ()};

                size_t skip (skip_count);
                string l, l2; // Reuse.
                for (bool first (true), second (false); !restart; )
                {
                  if (nb)
                  {
                    fdselect_state& ist (fds[0]);
                    fdselect_state& dst (fds[1]);

                    // We read until we reach EOF on both streams.
                    //
                    if (ist.fd == nullfd && dst.fd == nullfd)
                      break;

                    if (ist.fd != nullfd && getline_non_blocking (is, l))
                    {
                      if (eof (is))
                      {
                        ist.fd = nullfd;
                        continue;
                      }

                      // Fall through to parse (and clear) the line.
                    }
                    else
                    {
                      ifdselect (fds);

                      if (dst.ready)
                      {
                        if (!dbuf.read ())
                          dst.fd = nullfd;
                      }

                      continue;
                    }
                  }
                  else
                  {
                    if (eof (getline (is, l)))
                    {
                      if (bad_error && !l2.empty ()) // MSVC only (see below).
                        dbuf.write (l2, true /* newline */);

                      break;
                    }
                  }

                  l6 ([&]{trace << "header dependency line '" << l << "'";});

                  // Parse different dependency output formats.
                  //
                  switch (cclass)
                  {
                  case compiler_class::msvc:
                    {
                      // The first line should be the file we are compiling,
                      // unless this is clang-cl.
                      //
                      // If it is not, then we have several possibilities:
                      //
                      // First, it can be a command line warning, for example:
                      //
                      // cl : Command line warning D9025 : overriding '/W3' with '/W4'
                      //
                      // So we try to detect and skip them assuming they will
                      // also show up during the compilation proper.
                      //
                      // Another possibility is a mis-spelled option that is
                      // treated as another file to compile, for example:
                      //
                      // cl junk /nologo /P /showIncluses /TP foo.cxx
                      // junk
                      // foo.cxx
                      // c1xx: fatal error C1083: Cannot open source file: 'junk': No such file or directory
                      //
                      // Yet another possibility is that something went wrong
                      // even before we could compile anything.
                      //
                      // So the plan is to keep going (in the hope of C1083)
                      // but print the last line if there is no more input.
                      //
                      if (first)
                      {
                        if (cvariant != "clang")
                        {
                          if (l != src.path ().leaf ().string ())
                          {
                            // D8XXX are errors while D9XXX are warnings.
                            //
                            size_t p (msvc_sense_diag (l, 'D').first);
                            if (p != string::npos && l[p] == '9')
                              ; // Skip.
                            else
                            {
                              l2 = l;

                              if (!bad_error)
                              {
                                dbuf.open_eof (args[0]);
                                bad_error = true;
                              }
                            }

                            l.clear ();
                            continue;
                          }

                          l2.clear ();

                          // Fall through.
                        }

                        first = false;
                        l.clear ();
                        continue;
                      }

                      string f (next_show (l, good_error));

                      if (f.empty ()) // Some other diagnostics.
                      {
                        if (!bad_error)
                        {
                          dbuf.open_eof (args[0]);
                          bad_error = true;
                        }

                        dbuf.write (l, true /* newline */);
                        break;
                      }

                      // Skip until where we left off.
                      //
                      if (skip != 0)
                      {
                        // We can't be skipping over a non-existent header.
                        //
                        // @@ TMP: but this does seem to happen in some rare,
                        //    hard to reproduce situations.
#if 0
                        assert (!good_error);
#else
                        if (good_error)
                        {
                          info   << "previously existing header '" << f << "'"
                                 << " appears to have disappeared during build" <<
                            info << "line: " << l <<
                            info << "skip: " << skip <<
                            info << "please report at "
                                 << "https://github.com/build2/build2/issues/80";

                          assert (!good_error);
                        }
#endif
                        skip--;
                      }
                      else
                      {
                        if (optional<bool> r = add (path (move (f)),
                                                    false /* cache */,
                                                    pmt))
                        {
                          restart = *r;

                          // If the header does not exist (good_error), then
                          // restart must be true. Except that it is possible
                          // that someone running in parallel has already
                          // updated it. In this case we must force a restart
                          // since we haven't yet seen what's after this
                          // at-that-time-non-existent header.
                          //
                          // We also need to force the target update (normally
                          // done by add()).
                          //
                          if (good_error)
                            restart = true;
                          //
                          // And if we have updated the header (restart is
                          // true), then we may end up in this situation: an
                          // old header got included which caused the
                          // preprocessor to fail down the line. So if we are
                          // restarting, set the good error flag in case the
                          // process fails because of something like this (and
                          // if it is for a valid reason, then we will pick it
                          // up on the next round).
                          //
                          else if (restart)
                            good_error = true;

                          if (restart)
                          {
                            update = true;
                            l6 ([&]{trace << "restarting";});
                          }
                        }
                        else
                        {
                          // Trigger recompilation and mark as expected to
                          // fail.
                          //
                          update = true;
                          md.deferred_failure = true;
                        }
                      }

                      break;
                    }
                  case compiler_class::gcc:
                    {
                      // Make dependency declaration.
                      //
                      size_t pos (0);

                      if (first)
                      {
                        // Empty/invalid output should mean the wait() call
                        // below will return false.
                        //
                        if (l.empty ()  ||
                            l[0] != '^' || l[1] != ':' || l[2] != ' ')
                        {
                          if (!l.empty ())
                            l5 ([&]{trace << "invalid header dependency line '"
                                          << l << "'";});

                          bad_error = true;
                          break;
                        }

                        first = false;
                        second = true;

                        // While normally we would have the source file on the
                        // first line, if too long, it will be moved to the
                        // next line and all we will have on this line is:
                        // "^: \".
                        //
                        if (l.size () == 4 && l[3] == '\\')
                        {
                          l.clear ();
                          continue;
                        }
                        else
                          pos = 3; // Skip "^: ".

                        // Fall through to the 'second' block.
                      }

                      while (pos != l.size ())
                      {
                        string f (
                          make_parser::next (
                            l, pos, make_parser::type::prereq).first);

                        if (pos != l.size () && l[pos] == ':')
                        {
                          l5 ([&]{trace << "invalid header dependency line '"
                                        << l << "'";});
                          bad_error = true;
                          break;
                        }

                        // Skip the source file.
                        //
                        if (second)
                        {
                          second = false;
                          continue;
                        }

                        // Skip until where we left off.
                        //
                        if (skip != 0)
                        {
                          skip--;
                          continue;
                        }

                        if (optional<bool> r = add (path (move (f)),
                                                    false /* cache */,
                                                    pmt))
                        {
                          restart = *r;

                          if (restart)
                          {
                            // The same "preprocessor may fail down the line"
                            // logic as above.
                            //
                            good_error = true;

                            update = true;
                            l6 ([&]{trace << "restarting";});
                            break;
                          }
                        }
                        else
                        {
                          // Trigger recompilation, mark as expected to fail,
                          // and bail out.
                          //
                          update = true;
                          md.deferred_failure = true;
                          break;
                        }
                      }

                      break;
                    }
                  }

                  if (bad_error || md.deferred_failure)
                  {
                    // Note that it may be tempting to finish reading out the
                    // diagnostics before bailing out. But that may end up in
                    // a deadlock if the process gets blocked trying to write
                    // to stdout.
                    //
                    break;
                  }

                  l.clear ();
                }

                // We may bail out early from the above loop in case of a
                // restart or error. Which means the stderr stream (dbuf) may
                // still be open and we need to close it before closing the
                // stdout stream (which may try to skip).
                //
                // In this case we may also end up with incomplete diagnostics
                // so discard it.
                //
                // Generally, it may be tempting to start thinking if we
                // should discard buffered diagnostics in other cases, such as
                // restart. But remember that during serial execution it will
                // go straight to stderr so for consistency (and simplicity)
                // we should just print it unless there are good reasons not
                // to (also remember that in the restartable modes we normally
                // redirect stderr to /dev/null; see the process startup code
                // for details).
                //
                if (dbuf.is.is_open ())
                {
                  dbuf.is.close ();
                  dbuf.buf.clear ();
                }

                // Bail out early if we have deferred a failure.
                //
                // Let's ignore any buffered diagnostics in this case since
                // it would appear after the deferred failure note.
                //
                if (md.deferred_failure)
                {
                  is.close ();
                  return;
                }

                // In case of VC, we are parsing redirected stderr and if
                // things go south, we need to copy the diagnostics for the
                // user to see. Note that we should have already opened dbuf
                // at EOF above.
                //
                if (bad_error && cclass == compiler_class::msvc)
                {
                  // We used to just dump the whole rdbuf but it turns out VC
                  // may continue writing include notes interleaved with the
                  // diagnostics. So we have to filter them out.
                  //
                  for (; !eof (getline (is, l)); )
                  {
                    pair<size_t, size_t> p (msvc_sense_diag (l, 'C'));
                    if (p.first != string::npos             &&
                        l.compare (p.first, 4, "1083") != 0 &&
                        msvc_header_c1083 (l, p))
                    {
                      dbuf.write (l, true /* newline */);
                    }
                  }
                }

                is.close ();

                // This is tricky: it is possible that in parallel someone has
                // generated all our missing headers and we wouldn't restart
                // normally.
                //
                // In this case we also need to force the target update (which
                // is normally done by add()).
                //
                if (force_gen && *force_gen)
                {
                  restart = update = true;
                  force_gen = false;
                }
              }

              if (pr.wait ())
              {
                {
                  diag_record dr;

                  if (bad_error)
                    dr << fail << "expected error exit status from "
                       << x_lang << " compiler";

                  if (dbuf.is_open ())
                    dbuf.close (move (dr)); // Throws if error.
                }

                // Ignore expected successes (we are done).
                //
                if (!restart && psrc)
                  psrcw.close ();

                continue;
              }
              else if (pr.exit->normal ())
              {
                if (good_error) // Ignore expected errors (restart).
                {
                  if (dbuf.is_open ())
                    dbuf.close ();

                  continue;
                }
              }

              // Fall through.
            }
            catch (const io_error& e)
            {
              // Ignore buffered diagnostics (since reading it could be the
              // cause of this failure).
              //
              if (pr.wait ())
                fail << "unable to read " << x_lang << " compiler header "
                     << "dependency output: " << e;

              // Fall through.
            }

            assert (pr.exit && !*pr.exit);
            const process_exit& pe (*pr.exit);

            // For normal exit we assume the child process issued some
            // diagnostics.
            //
            if (pe.normal ())
            {
              // If this run was with the generated header support then it's
              // time to give up.
              //
              if (gen)
              {
                if (dbuf.is_open ())
                  dbuf.close (args, pe, 2 /* verbosity */);

                throw failed ();
              }

              // Just to recap, being here means something is wrong with the
              // source: it can be a missing generated header, it can be an
              // outdated generated header (e.g., some check triggered #error
              // which will go away if only we updated the generated header),
              // or it can be a real error that is not going away.
              //
              // So this is what we are going to do here: if anything got
              // updated on this run (i.e., the compiler has produced valid
              // dependency information even though there were errors and we
              // managed to find and update a header based on this
              // informaion), then we restart in the same mode hoping that
              // this fixes things. Otherwise, we force the generated header
              // support which will either uncover a missing generated header
              // or will issue diagnostics.
              //
              if (restart)
              {
                if (dbuf.is_open ())
                  dbuf.close ();

                l6 ([&]{trace << "trying again without generated headers";});
              }
              else
              {
                // In some pathological situations we may end up switching
                // back and forth indefinitely without making any headway. So
                // we use skip_count to track our progress.
                //
                // Examples that have been encountered so far:
                //
                // - Running out of disk space.
                //
                // - Using __COUNTER__ in #if which is incompatible with the
                //   GCC's -fdirectives-only mode.
                //
                // - A Clang bug: https://bugs.llvm.org/show_bug.cgi?id=35580
                //
                // So let's show the yo-yo'ing command lines and ask the user
                // to investigate.
                //
                // Note: we could restart one more time but this time without
                // suppressing diagnostics. This could be useful since, say,
                // running out of disk space may not reproduce on its own (for
                // example, because we have removed all the partially
                // preprocessed source files).
                //
                {
                  diag_record dr;
                  if (force_gen_skip && *force_gen_skip == skip_count)
                  {
                    dr <<
                      fail << "inconsistent " << x_lang << " compiler behavior" <<
                      info << "run the following two commands to investigate";

                    dr << info;
                    print_process (dr, args.data ()); // No pipes.

                    init_args ((gen = true));
                    dr << info << "";
                    print_process (dr, args.data ()); // No pipes.
                  }

                  if (dbuf.is_open ())
                    dbuf.close (move (dr)); // Throws if error.
                }

                restart = true;
                force_gen = true;
                force_gen_skip = skip_count;
                l6 ([&]{trace << "restarting with forced generated headers";});
              }
              continue;
            }
            else
            {
              if (dbuf.is_open ())
              {
                dbuf.close (args, pe, 2 /* verbosity */);
                throw failed ();
              }
              else
                run_finish (args, pr, 2 /* verbosity */);
            }
          }
          catch (const process_error& e)
          {
            error << "unable to execute " << args[0] << ": " << e;

            // In a multi-threaded program that fork()'ed but did not exec(),
            // it is unwise to try to do any kind of cleanup (like unwinding
            // the stack and running destructors).
            //
            if (e.child)
            {
              drm.cancel ();
              exit (1);
            }

            throw failed ();
          }
        }
      }

      // Add the terminating blank line (we are updating depdb).
      //
      dd.expect ("");

      puse = puse && !reprocess && psrc;

      result.first = move (psrc);
      result.second = puse;
    }

    // Return the translation unit information (last argument) and its
    // checksum (result). If the checksum is empty, then it should not be
    // used.
    //
    string compile_rule::
    parse_unit (action a,
                file& t,
                linfo li,
                const file& src,
                file_cache::entry& psrc,
                const match_data& md,
                const path& dd,
                unit& tu) const
    {
      tracer trace (x, "compile_rule::parse_unit");

      // Scanning .S files with our parser is hazardous since such files
      // sometimes use `#`-style comments. Presumably real compilers just
      // ignore them in some way, but it doesn't seem worth it to bother in
      // our case. Also, the checksum calculation over assembler tokens feels
      // iffy.
      //
      if (x_assembler_cpp (src))
      {
        tu.type = unit_type::non_modular;
        return "";
      }

      otype ot (li.type);

      // If things go wrong give the user a bit extra context. Let's call it
      // "scanning" instead of "parsing" since this has become an established
      // term.
      //
      auto df = make_diag_frame (
        [&src](const diag_record& dr)
        {
          if (verb != 0)
            dr << info << "while scanning " << src;
        });

      // For some compilers (GCC, Clang) the preporcessed output is only
      // partially preprocessed. For others (VC), it is already fully
      // preprocessed (well, almost: it still has comments but we can handle
      // that). Plus, the source file might already be (sufficiently)
      // preprocessed.
      //
      // So the plan is to start the compiler process that writes the fully
      // preprocessed output to stdout and reduce the already preprocessed
      // case to it.
      //
      environment env;
      cstrings args;
      small_vector<string, 2> header_args; // Header unit options storage.

      const path* sp; // Source path.

      // @@ MODHDR: If we are reprocessing, then will need module mapper for
      //            include translation. Hairy... Can't we add support for
      //            include translation in file mapper?
      //
      bool reprocess (cast_false<bool> (t[c_reprocess]));

      bool ps; // True if extracting from psrc.
      if (md.pp < preprocessed::modules)
      {
        // If we were instructed to reprocess the source during compilation,
        // then also reprocess it here. While the preprocessed output may be
        // usable for our needs, to be safe we assume it is not (and later we
        // may extend cc.reprocess to allow specifying where reprocessing is
        // needed).
        //
        ps = psrc && !reprocess;
        sp = &(ps ? psrc.path () : src.path ());

        // VC's preprocessed output, if present, is fully preprocessed.
        //
        if (cclass != compiler_class::msvc || !ps)
        {
          // This should match with how we setup preprocessing and is pretty
          // similar to init_args() from extract_headers().
          //
          args.push_back (cpath.recall_string ());

          if (reprocess)
            args.push_back ("-D__build2_preprocess");

          append_options (args, t, x_poptions);
          append_options (args, t, c_poptions);

          append_library_options (args, t.base_scope (), a, t, li);

          if (md.symexport)
            append_symexport_options (args, t);

          // Make sure we don't fail because of warnings.
          //
          // @@ Can be both -WX and /WX.
          //
          const char* werror (nullptr);
          switch (cclass)
          {
          case compiler_class::gcc:  werror = "-Werror"; break;
          case compiler_class::msvc: werror = "/WX";     break;
          }

          append_options (args, t, c_coptions, werror);
          append_options (args, t, x_coptions, werror);

          append_header_options (env, args, header_args, a, t, md, dd);

          switch (cclass)
          {
          case compiler_class::msvc:
            {
              args.push_back ("/nologo");

              append_options (args, cmode);
              append_sys_hdr_options (args);

              // Note: no append_diag_color_options() call since the
              // diagnostics is discarded.

              // See perform_update() for details on the choice of options.
              //
              {
                bool sc (find_option_prefixes (
                           {"/source-charset:", "-source-charset:"}, args));
                bool ec (find_option_prefixes (
                           {"/execution-charset:", "-execution-charset:"}, args));

                if (!sc && !ec)
                  args.push_back ("/utf-8");
                else
                {
                  if (!sc)
                    args.push_back ("/source-charset:UTF-8");

                  if (!ec)
                    args.push_back ("/execution-charset:UTF-8");
                }
              }

              if (cvariant != "clang" && isystem (*this))
              {
                if (find_option_prefixes ({"/external:I", "-external:I"}, args) &&
                    !find_option_prefixes ({"/external:W", "-external:W"}, args))
                  args.push_back ("/external:W0");
              }

              if (x_lang == lang::cxx &&
                  !find_option_prefixes ({"/EH", "-EH"}, args))
                args.push_back ("/EHsc");

              if (!find_option_prefixes ({"/MD", "/MT", "-MD", "-MT"}, args))
                args.push_back ("/MD");

              args.push_back ("/E");
              // args.push_back ("/C"); // See above.

              msvc_sanitize_cl (args);

              append_lang_options (args, md); // Compile as.

              break;
            }
          case compiler_class::gcc:
            {
              append_options (args, cmode);
              append_sys_hdr_options (args);

              // Note: no append_diag_color_options() call since the
              // diagnostics is discarded.

              // See perform_update() for details on the choice of options.
              //
              if (!find_option_prefix ("-finput-charset=", args))
                args.push_back ("-finput-charset=UTF-8");

              if (ot == otype::s)
              {
                if (tclass == "linux" || tclass == "bsd")
                  args.push_back ("-fPIC");
              }

              if (ctype == compiler_type::clang && tsys == "win32-msvc")
              {
                if (!find_options ({"-nostdlib", "-nostartfiles"}, args))
                {
                  args.push_back ("-D_MT");
                  args.push_back ("-D_DLL");
                }
              }

              if (ctype == compiler_type::clang && cvariant == "emscripten")
              {
                if (x_lang == lang::cxx)
                {
                  if (!find_option_prefix ("DISABLE_EXCEPTION_CATCHING=", args))
                  {
                    args.push_back ("-s");
                    args.push_back ("DISABLE_EXCEPTION_CATCHING=0");
                  }
                }
              }

              args.push_back ("-E");
              append_lang_options (args, md);

              // Options that trigger preprocessing of partially preprocessed
              // output are a bit of a compiler-specific voodoo.
              //
              if (ps)
              {
                switch (ctype)
                {
                case compiler_type::gcc:
                  {
                    // Note that only these two *plus* -x do the trick.
                    //
                    args.push_back ("-fpreprocessed");
                    args.push_back ("-fdirectives-only");
                    break;
                  }
                case compiler_type::clang:
                  {
                    // See below for details.
                    //
                    if (ctype == compiler_type::clang &&
                        cmaj >= (cvariant != "apple" ? 15 : 16))
                    {
                      if (find_options ({"-pedantic",  "-pedantic-errors",
                                         "-Wpedantic", "-Werror=pedantic"},
                                        args))
                      {
                        args.push_back ("-Wno-gnu-line-marker");
                      }
                    }

                    break;
                  }
                case compiler_type::msvc:
                case compiler_type::icc:
                  assert (false);
                }
              }

              break;
            }
          }

          args.push_back (sp->string ().c_str ());
          args.push_back (nullptr);
        }

        if (!env.empty ())
          env.push_back (nullptr);
      }
      else
      {
        // Extracting directly from source.
        //
        ps = false;
        sp = &src.path ();
      }

      // Preprocess and parse.
      //
      for (;;) // Breakout loop.
      try
      {
        // If we are compiling the preprocessed output, get its read handle.
        //
        file_cache::read psrcr (ps ? psrc.open () : file_cache::read ());

        // Temporarily disable the removal of the preprocessed file in case of
        // an error. We re-enable it below.
        //
        bool ptmp (ps && psrc.temporary);
        if (ptmp)
          psrc.temporary = false;

        process pr;

        try
        {
          if (args.empty ())
          {
            pr = process (process_exit (0)); // Successfully exited.
            pr.in_ofd = fdopen (*sp, fdopen_mode::in);
          }
          else
          {
            if (verb >= 3)
              print_process (args);

            // We don't want to see warnings multiple times so ignore all
            // diagnostics (thus no need for diag_buffer).
            //
            pr = process (cpath,
                          args,
                          0, -1, -2,
                          nullptr, // CWD
                          env.empty () ? nullptr : env.data ());
          }

          // Use binary mode to obtain consistent positions.
          //
          ifdstream is (move (pr.in_ofd),
                        fdstream_mode::binary | fdstream_mode::skip);

          parser p;
          p.parse (is, path_name (*sp), tu, cid);

          is.close ();

          if (pr.wait ())
          {
            if (ptmp)
              psrc.temporary = true; // Re-enable.

            unit_type& ut (tu.type);
            module_info& mi (tu.module_info);

            if (!modules)
            {
              if (ut != unit_type::non_modular || !mi.imports.empty ())
                fail << "modules support required by " << src <<
                  info << "consider enabling modules with "
                       << x << ".features.modules=true in root.build";
            }
            else
            {
              // Sanity checks.
              //
              // If we are compiling a module interface or partition, make
              // sure the translation unit has the necessary declarations.
              //
              if (ut != unit_type::module_intf      &&
                  ut != unit_type::module_intf_part &&
                  ut != unit_type::module_impl_part &&
                  src.is_a (*x_mod))
                fail << src << " is not a module interface or partition unit";

              // A header unit should look like a non-modular translation unit.
              //
              if (md.type == unit_type::module_header)
              {
                if (ut != unit_type::non_modular)
                  fail << "module declaration in header unit " << src;

                ut = md.type;
                mi.name = src.path ().string ();
              }
            }

            // If we were forced to reprocess, assume the checksum is not
            // accurate (parts of the translation unit could have been
            // #ifdef'ed out; see __build2_preprocess).
            //
            // Also, don't use the checksum for header units since it ignores
            // preprocessor directives and may therefore cause us to ignore a
            // change to an exported macro. @@ TODO: maybe we should add a
            // flag to the parser not to waste time calculating the checksum
            // in these cases.
            //
            return reprocess || ut == unit_type::module_header
              ? string ()
              : move (p.checksum);
          }

          // Fall through.
        }
        catch (const io_error& e)
        {
          if (pr.wait ())
            fail << "unable to read " << x_lang << " preprocessor output: "
                 << e;

          // Fall through.
        }

        assert (pr.exit && !*pr.exit);
        const process_exit& e (*pr.exit);

        // What should we do with a normal error exit? Remember we suppressed
        // the compiler's diagnostics. We used to issue a warning and continue
        // with the assumption that the compilation step will fail with
        // diagnostics. The problem with this approach is that we may fail
        // before that because the information we return (e.g., module name)
        // is bogus. So looks like failing is the only option.
        //
        if (e.normal ())
        {
          fail << "unable to preprocess " << src <<
            info << "re-run with -s -V to display failing command" <<
            info << "then run failing command to display compiler diagnostics";
        }
        else
          run_finish (args, pr, 2 /* verbosity */); // Throws.
      }
      catch (const process_error& e)
      {
        error << "unable to execute " << args[0] << ": " << e;

        if (e.child)
          exit (1);
      }

      throw failed ();
    }

    // Extract and inject module dependencies.
    //
    void compile_rule::
    extract_modules (action a,
                     const scope& bs,
                     file& t,
                     linfo li,
                     const compile_target_types& tts,
                     const file& src,
                     match_data& md,
                     module_info&& mi,
                     depdb& dd,
                     bool& update) const
    {
      tracer trace (x, "compile_rule::extract_modules");

      // If things go wrong, give the user a bit extra context.
      //
      auto df = make_diag_frame (
        [&src](const diag_record& dr)
        {
          if (verb != 0)
            dr << info << "while extracting module dependencies from " << src;
        });

      unit_type ut (md.type);
      module_imports& is (mi.imports);

      // Search and match all the modules we depend on. If this is a module
      // implementation unit, then treat the module itself as if it was
      // imported (we insert it first since for some compilers we have to
      // differentiate between this special module and real imports). Note
      // that module partitions do not have this implied import semantics.
      // Note also: move.
      //
      if (ut == unit_type::module_impl)
        is.insert (
          is.begin (),
          module_import {import_type::module_intf, move (mi.name), false, 0});

      // The change to the set of imports would have required a change to
      // source code (or options). Changes to the bmi{}s themselves will be
      // detected via the normal prerequisite machinery. However, the same set
      // of imports could be resolved to a different set of bmi{}s (in a sense
      // similar to changing the source file). To detect this we calculate and
      // store a hash of all (not just direct) bmi{}'s paths.
      //
      sha256 cs;

      if (!is.empty ())
        md.modules = search_modules (a, bs, t, li, tts.bmi, src, is, cs);

      if (dd.expect (cs.string ()) != nullptr)
        update = true;

      // Save the module map for compilers that use it.
      //
      switch (ctype)
      {
      case compiler_type::gcc:
        {
          // We don't need to redo this if the above hash hasn't changed and
          // the database is still valid.
          //
          if (dd.writing () || !dd.skip ())
          {
            // Note that for header unit, name will be an absolute and
            // normalized path since that's the TU path we pass to the
            // compiler.
            //
            auto write = [&dd] (const string& name, const path& file)
            {
              dd.write ("@ ", false);
              dd.write (name, false);
              dd.write (' ', false);
              dd.write (file);
            };

            // The output mapping is provided in the same way as input.
            //
            if (ut == unit_type::module_intf      ||
                ut == unit_type::module_intf_part ||
                ut == unit_type::module_impl_part ||
                ut == unit_type::module_header)
              write (mi.name, t.path ());

            if (size_t start = md.modules.start)
            {
              // Note that we map both direct and indirect imports to override
              // any module paths that might be stored in the BMIs (or
              // resolved relative to "repository path", whatever that is).
              //
              const auto& pts (t.prerequisite_targets[a]);
              for (size_t i (start); i != pts.size (); ++i)
              {
                if (const target* m = pts[i])
                {
                  // Save a variable lookup by getting the module name from
                  // the import list (see search_modules()).
                  //
                  // Note: all real modules (not header units).
                  //
                  write (is[i - start].name, m->as<file> ().path ());
                }
              }
            }
          }
          break;
        }
      default:
        break;
      }

      // Set the cc.module_name rule-specific variable if this is an interface
      // or partition unit. Note that it may seem like a good idea to set it
      // on the bmi{} group to avoid duplication. We, however, cannot do it
      // MT-safely since we don't match the group.
      //
      // @@ MODHDR TODO: do we need this for header units? Currently we don't
      //    see header units here.
      //
      if (ut == unit_type::module_intf      ||
          ut == unit_type::module_intf_part ||
          ut == unit_type::module_impl_part
          /*ut == unit_type::module_header*/)
      {
        if (value& v = t.state[a].assign (c_module_name))
          assert (cast<string> (v) == mi.name);
        else
          v = move (mi.name); // Note: move.
      }
    }

    inline bool
    std_module (const string& m)
    {
      size_t n (m.size ());
      return (n >= 3 &&
              m[0] == 's' && m[1] == 't' && m[2] == 'd' &&
              (n == 3 || m[3] == '.'));
    };

    // Resolve imported modules to bmi*{} targets.
    //
    module_positions compile_rule::
    search_modules (action a,
                    const scope& bs,
                    file& t,
                    linfo li,
                    const target_type& btt,
                    const file& src,
                    module_imports& imports,
                    sha256& cs) const
    {
      tracer trace (x, "compile_rule::search_modules");

      context& ctx (bs.ctx);
      const scope& rs (*bs.root_scope ());

      // NOTE: currently we don't see header unit imports (they are handled by
      //       extract_headers() and are not in imports).

      // So we have a list of imports and a list of "potential" module
      // prerequisites. They are potential in the sense that they may or may
      // not be required by this translation unit. In other words, they are
      // the pool where we can resolve actual imports.
      //
      // Because we may not need all of these prerequisites, we cannot just go
      // ahead and match all of them (and they can even have cycles; see rule
      // synthesis). This poses a bit of a problem: the only way to discover
      // the module's actual name (see cc.module_name) is by matching it.
      //
      // One way to solve this would be to make the user specify the module
      // name for each mxx{} explicitly. This will be a major pain, however.
      // Another would be to require encoding of the module name in the
      // interface unit file name. For example, hello.core -> hello-core.mxx.
      // This is better but still too restrictive: some will want to call it
      // hello_core.mxx or HelloCore.mxx (because that's their file naming
      // convention) or place it in a subdirectory, say, hello/core.mxx.
      //
      // In the above examples one common theme about all the file names is
      // that they contain, in one form or another, the "tail" of the module
      // name (`core`). So what we are going to do is require that, within a
      // pool (library, executable), the interface file names contain enough
      // of the module name tail to unambiguously resolve all the module
      // imports. On our side we are going to implement a "fuzzy" module name
      // to file name match. This should be reliable enough since we will
      // always verify our guesses once we match the target and extract the
      // actual module name. Plus, the user will always have the option of
      // resolving any impasses by specifying the module name explicitly.
      //
      // So, the fuzzy match: the idea is that each match gets a score, the
      // number of characters in the module name that got matched. A match
      // with the highest score is used. And we use the (length + 1) for a
      // match against an actual (extracted) module name.
      //
      // Actually, the scoring system is a bit more elaborate than that.
      // Consider module name core.window and two files, window.mxx and
      // abstract-window.mxx: which one is likely to define this module?
      // Clearly the first, but in the above-described scheme they will get
      // the same score. More generally, consider these "obvious" (to the
      // human, that is) situations:
      //
      //   window.mxx          vs  abstract-window.mxx
      //   details/window.mxx  vs  abstract-window.mxx
      //   gtk-window.mxx      vs  gtk-abstract-window.mxx
      //
      // To handle such cases we are going to combine the above primary score
      // with the following secondary scores (in that order):
      //
      // A) Strength of separation between matched and unmatched parts:
      //
      //    '\0' > directory separator > other separator > unseparated
      //
      //    Here '\0' signifies nothing to separate (unmatched part is empty).
      //
      // B) Shortness of the unmatched part.
      //
      // Finally, for the fuzzy match we require a complete match of the last
      // module (or partition) component. Failed that, we will match `format`
      // to `print` because the last character (`t`) is the same.
      //
      // For std.* modules we only accept non-fuzzy matches (think std.compat
      // vs some compat.mxx). And if such a module is unresolved, then we
      // assume it is pre-built and will be found by some other means (e.g.,
      // VC's IFCPATH).
      //
      // Note also that we handle module partitions the same as submodules. In
      // other words, for matching, `.` and `:` are treated the same.
      //
      auto match_max = [] (const string& m) -> size_t
      {
        // The primary and sub-scores are packed in the following decimal
        // representation:
        //
        // PPPPABBBB
        //
        // Where PPPP is the primary score, A is the A) score, and BBBB is
        // the B) score described above. Zero signifies no match.
        //
        // We use decimal instead of binary packing to make it easier for the
        // human to separate fields in the trace messages, during debugging,
        // etc.
        //
        return m.size () * 100000 + 99999; // Maximum match score.
      };

      auto match = [] (const string& f, const string& m) -> size_t
      {
        auto char_sep = [] (char c) -> char
        {
          // Return the character (translating directory seperators to '/') if
          // it is a separator and '\0' otherwise (so can be used as bool).
          //
          return (c == '_' || c == '-' || c == '.'    ? c   :
                  path::traits_type::is_separator (c) ? '/' : '\0');
        };

        auto case_sep = [] (char c1, char c2)
        {
          return (alpha (c1) &&
                  alpha (c2) &&
                  (ucase (c1) == c1) != (ucase (c2) == c2));
        };

        auto mod_sep = [] (char c) {return c == '.' || c == ':';};

        size_t fn (f.size ()), fi (fn);
        size_t mn (m.size ()), mi (mn);

        // True if the previous character was counted as a real (that is,
        // non-case changing) separator.
        //
        bool fsep (false);
        bool msep (false);

        // We require complete match of at least last module component.
        //
        bool match (false);

        // Scan backwards for as long as we match. Keep track of the previous
        // character for case change detection.
        //
        for (char fc, mc, fp ('\0'), mp ('\0');
             fi != 0 && mi != 0;
             fp = fc, mp = mc, --fi, --mi)
        {
          fc = f[fi - 1];
          mc = m[mi - 1];

          if (icasecmp (fc, mc) == 0)
          {
            fsep = msep = false;
            continue;
          }

          // We consider all separators equal and character case change being
          // a separators. Some examples of the latter:
          //
          // foo.bar
          // foo:bar
          //  fooBAR
          //  FOObar
          //
          bool fs (char_sep (fc));
          bool ms (mod_sep (mc) || mc == '_');

          if (fs && ms)
          {
            fsep = msep = true;
            match = match || mod_sep (mc);
            continue;
          }

          // Only if one is a real separator do we consider case change.
          //
          if (fs || ms)
          {
            bool fa (false), ma (false);
            if ((fs || (fa = case_sep (fp, fc))) &&
                (ms || (ma = case_sep (mp, mc))))
            {
              // Stay on this character if imaginary punctuation (note: cannot
              // be both true).
              //
              if (fa) {++fi; msep = true;}
              if (ma) {++mi; fsep = true;}

              match = match || mod_sep (mc);
              continue;
            }
          }

          break; // No match.
        }

        // Deal with edge cases: complete module match and complete file
        // match.
        //
        match = match || mi == 0 || (fi == 0 && mod_sep (m[mi - 1]));

        if (!match)
          return 0;

        // Here is another corner case, the module is async_simple:IOExecutor
        // and the file names are:
        //
        // IOExecutor.mxx
        // SimpleIOExecutor.mxx
        //
        // The above implementation treats the latter as better because
        // `Simple` in SimpleIOExecutor matches `simple` in async_simple. It's
        // unclear what we can do about it without potentially breaking other
        // legitimate cases (think Boost_Simple:IOExecutor). Maybe we could
        // boost the exact partition name match score, similar to the exact
        // module match, as some sort of a heuristics? Let's try.
        //
        if (fi == 0 && mi != 0 && m[mi - 1] == ':')
        {
          // Pretend we matched one short of the next module component. This
          // way AsyncSimpleIOExecutor.mxx would still be a better match.
          //
          while (--mi != 0 && m[mi - 1] != '.')
            ;

          msep = (mi != 0); // For uncount logic below.
          mi++; // One short.
        }

        // "Uncount" real separators.
        //
        if (fsep) fi++;
        if (msep) mi++;

        // Use the number of characters matched in the module name and not
        // in the file (this may not be the same because of the imaginary
        // separators).
        //
        size_t ps (mn - mi);

        // The strength of separation sub-score.
        //
        // Check for case change between the last character that matched and
        // the first character that did not.
        //
        size_t as (0);
        if      (fi == 0)                                 as = 9;
        else if (char c = char_sep (f[fi - 1]))           as = c == '/' ? 8 : 7;
        else if (fi != fn && case_sep (f[fi], f[fi - 1])) as = 7;

        // The length of the unmatched part sub-score.
        //
        size_t bs (9999 - fi);

        return ps * 100000 + as * 10000 + bs;
      };

#if 0
      assert (match ("IOExecutor",       "async_simple:IOExecutor") >
              match ("SimpleIOExecutor", "async_simple:IOExecutor"));

      assert (match ("IOExecutor",            "async_simple:IOExecutor") <
              match ("AsyncSimpleIOExecutor", "async_simple:IOExecutor"));

      assert (match ("IOExecutor",       "x.async_simple:IOExecutor") >
              match ("SimpleIOExecutor", "x.async_simple:IOExecutor"));

      assert (match ("IOExecutor",            "x.async_simple:IOExecutor") <
              match ("AsyncSimpleIOExecutor", "x.async_simple:IOExecutor"));
#endif

      auto& pts (t.prerequisite_targets[a]);
      size_t start (pts.size ()); // Index of the first to be added.

      // We have two parallel vectors: module names/scores in imports and
      // targets in prerequisite_targets (offset with start). Pre-allocate
      // NULL entries in the latter.
      //
      size_t n (imports.size ());
      pts.resize (start + n, nullptr);

      // Oh, yes, there is one "minor" complication. It's the last one, I
      // promise. It has to do with module re-exporting (export import M;).
      // In this case (currently) all implementations simply treat it as a
      // shallow (from the BMI's point of view) reference to the module (or an
      // implicit import, if you will). Do you see where it's going? Nowhere
      // good, that's right. This shallow reference means that the compiler
      // should be able to find BMIs for all the re-exported modules,
      // recursively. The good news is we are actually in a pretty good shape
      // to handle this: after match all our prerequisite BMIs will have their
      // prerequisite BMIs known, recursively. The only bit that is missing is
      // the re-export flag of some sorts. As well as deciding where to handle
      // it: here or in append_module_options(). After some meditation it
      // became clear handling it here will be simpler: we need to weed out
      // duplicates for which we can re-use the imports vector. And we may
      // also need to save this "flattened" list of modules in depdb.
      //
      // Ok, so, here is the plan:
      //
      // 1. There is no good place in prerequisite_targets to store the
      //    exported flag (no, using the marking facility across match/execute
      //    is a bad idea). So what we are going to do is put re-exported
      //    bmi{}s at the back and store (in the target's auxiliary data
      //    storage) the start position. One bad aspect about this part is
      //    that we assume those bmi{}s have been matched by the same
      //    rule. But let's not kid ourselves, there will be no other rule
      //    that matches bmi{}s.
      //
      //    @@ I think now we could use prerequisite_targets::data for this?
      //
      // 2. Once we have matched all the bmi{}s we are importing directly
      //    (with all the re-exported by us at the back), we will go over them
      //    and copy all of their re-exported bmi{}s (using the position we
      //    saved on step #1). The end result will be a recursively-explored
      //    list of imported bmi{}s that append_module_options() can simply
      //    convert to the list of options.
      //
      //    One issue with this approach is that these copied targets will be
      //    executed which means we need to adjust their dependent counts
      //    (which is normally done by match). While this seems conceptually
      //    correct (especially if you view re-exports as implicit imports),
      //    it's just extra overhead (we know they will be updated). So what
      //    we are going to do is save another position, that of the start of
      //    these copied-over targets, and will only execute up to this point.
      //
      // And after implementing this came the reality check: all the current
      // implementations require access to all the imported BMIs, not only
      // re-exported. Some (like Clang) store references to imported BMI files
      // so we actually don't need to pass any extra options (unless things
      // get moved) but they still need access to the BMIs (and things will
      // most likely have to be done differenly for distributed compilation).
      // @@ Note: no longer the case for Clang either.
      //
      // So the revised plan: on the off chance that some implementation will
      // do it differently we will continue maintaing the imported/re-exported
      // split and how much to copy-over can be made compiler specific.
      //
      // As a first sub-step of step #1, move all the re-exported imports to
      // the end of the vector. This will make sure they end up at the end
      // of prerequisite_targets. Note: the special first import, if any,
      // should be unaffected.
      //
      sort (imports.begin (), imports.end (),
            [] (const module_import& x, const module_import& y)
            {
              return !x.exported && y.exported;
            });

      // Go over the prerequisites once.
      //
      // For (direct) library prerequisites, check their prerequisite bmi{}s
      // (which should be searched and matched with module names discovered;
      // see the library metadata protocol for details).
      //
      // For our own bmi{} prerequisites, checking if each (better) matches
      // any of the imports.

      // For fuzzy check if a file name (better) resolves any of our imports
      // and if so make it the new selection. For exact the name is the actual
      // module name and it can only resolve one import (there are no
      // duplicates).
      //
      // Set done to true if all the imports have now been resolved to actual
      // module names (which means we can stop searching). This will happens
      // if all the modules come from libraries. Which will be fairly common
      // (think of all the tests) so it's worth optimizing for.
      //
      bool done (false);

      auto check_fuzzy = [&trace, &imports, &pts, &match, &match_max, start, n]
        (const target* pt, const string& name)
      {
        for (size_t i (0); i != n; ++i)
        {
          module_import& m (imports[i]);

          if (std_module (m.name)) // No fuzzy std.* matches.
            continue;

          if (m.score > match_max (m.name)) // Resolved to module name.
            continue;

          size_t s (match (name, m.name));

          l5 ([&]{trace << name << " ~ " << m.name << ": " << s;});

          if (s > m.score)
          {
            pts[start + i] = pt;
            m.score = s;
          }
        }
      };

      // If resolved, return the "slot" in pts (we don't want to create a
      // side build until we know we match; see below for details).
      //
      auto check_exact = [&trace, &imports, &pts, &match_max, start, n, &done]
        (const string& name) -> const target**
      {
        const target** r (nullptr);
        done = true;

        for (size_t i (0); i != n; ++i)
        {
          module_import& m (imports[i]);

          size_t ms (match_max (m.name));

          if (m.score > ms) // Resolved to module name (no effect on done).
            continue;

          if (r == nullptr)
          {
            size_t s (name == m.name ? ms + 1 : 0);

            l5 ([&]{trace << name << " ~ " << m.name << ": " << s;});

            if (s > m.score)
            {
              r = &pts[start + i].target;
              m.score = s;
              continue; // Scan the rest to detect if all done.
            }
          }
          else
            assert (name != m.name); // No duplicates.

          done = false;
        }

        return r;
      };

      // Find the module in prerequisite targets of a library (recursively)
      // seeing through libu*{}. Note: sets the `done` flag. See similar
      // logic in pkgconfig_save().
      //
      auto find = [a, &bs, this,
                   &check_exact, &done] (const file& l,
                                         const auto& find) -> void
      {
        for (const target* pt: l.prerequisite_targets[a])
        {
          if (pt == nullptr)
            continue;

          // Note that here we (try) to use whatever flavor of bmi*{} is
          // available.
          //
          // @@ MOD: BMI compatibility check.
          //
          if (pt->is_a<bmix> ())
          {
            // If the extraction of the module information for this BMI failed
            // and we have deferred failure to compiler diagnostics, then
            // there will be no module name assigned. It would have been
            // better to make sure that's the cause, but that won't be easy.
            //
            const string* n (cast_null<string> (
                               pt->state[a].vars[c_module_name]));
            if (n != nullptr)
            {
              if (const target** p = check_exact (*n))
                *p = pt;
            }
          }
          else if (pt->is_a (*x_mod))
          {
            // This is an installed library with a list of module sources (the
            // source are specified as prerequisites but the fallback file
            // rule puts them into prerequisite_targets for us).
            //
            // The module names should be specified but if not assume
            // something else is going on (like a deferred failure) and
            // ignore.
            //
            // Note also that besides modules, prerequisite_targets may
            // contain libraries which are interface dependencies of this
            // library and which may be called to resolve its module
            // dependencies.
            //
            const string* n (cast_null<string> (pt->vars[c_module_name]));

            if (n == nullptr)
              continue;

            if (const target** p = check_exact (*n))
            {
              // It seems natural to build a BMI type that corresponds to the
              // library type. After all, this is where the object file part
              // of the BMI is going to come from (unless it's a module
              // interface-only library).
              //
              *p = &this->make_module_sidebuild (
                a, bs, &l, link_type (l).type, *pt, *n).first; // GCC 4.9
            }
          }
          // Note that in prerequisite targets we will have the libux{}
          // members, not the group.
          //
          else if (const libux* pl = pt->is_a<libux> ())
            find (*pl, find);
          else
            continue;

          if (done)
            break;
        }
      };

      // Pre-resolve standard library modules (std and std.compat) in an ad
      // hoc way.
      //

      // Similar logic to check_exact() above.
      //
      done = true;

      for (size_t i (0); i != n; ++i)
      {
        module_import& m (imports[i]);

        if (m.name == "std" || m.name == "std.compat")
        {
          otype ot (otype::e);
          const target* mt (nullptr);

          switch (ctype)
          {
          case compiler_type::clang:
            {
              // @@ TODO: cache x_stdlib value.
              //
              if (cast<string> (rs[x_stdlib]) != "libc++")
                fail << "standard library module '" << m.name << "' is "
                     << "currently only supported in libc++" <<
                  info << "try adding -stdlib=libc++ as compiler mode option";

              if (cmaj < 18)
                fail << "standard library module '" << m.name << "' is "
                     << "only supported in Clang 18 or later";

              // Find or insert std*.cppm (similar code to pkgconfig.cxx).
              //
              // Note: build_install_data is absolute and normalized.
              //
              mt = &ctx.targets.insert_locked (
                *x_mod,
                (dir_path (build_install_data) /= "libbuild2") /= "cc",
                dir_path (),
                m.name,
                string ("cppm"), // For C++14 during bootstrap.
                target_decl::implied,
                trace).first;

              // Which output type should we use, static or shared? The
              // correct way would be to detect whether static or shared
              // version of libc++ is to be linked and use the corresponding
              // type. And we could do that by looking for -static-libstdc++
              // in loption (and no, it's not -static-libc++).
              //
              // But, looking at the object file produced from std*.cppm, they
              // only contain one symbol, the static object initializer. And
              // this is unlikely to change since all other non-inline or
              // template symbols should be in libc++. So feels like it's not
              // worth the trouble and one variant should be good enough for
              // both cases. Let's use the shared one for less surprising
              // diagnostics (as in, "why are you linking obje{} to a shared
              // library?")
              //
              // (Of course, theoretically, std*.cppm could detect via a macro
              // whether they are being compiled with -fPIC or not and do
              // things differently, but this seems far-fetched).
              //
              ot = otype::s;

              break;
            }
          case compiler_type::msvc:
            {
              // For MSVC, the source files std.ixx and std.compat.ixx are
              // found in the modules/ subdirectory which is a sibling of
              // include/ in the MSVC toolset (and "that is a contract with
              // customers" to quote one of the developers).
              //
              // The problem of course is that there are multiple system
              // header search directories (for example, as specified in the
              // INCLUDE environment variable) and which one of them is for
              // the MSVC toolset is not specified. So what we are going to do
              // is search for one of the well-known standard C++ headers and
              // assume that the directory where we found it is the one we are
              // looking for. Or we could look for something MSVC-specific
              // like vcruntime.h.
              //
              dir_path modules;
              if (optional<path> p = find_system_header (path ("vcruntime.h")))
              {
                p->make_directory (); // Strip vcruntime.h.
                if (p->leaf () == path ("include")) // Sanity check.
                {
                  modules = path_cast<dir_path> (move (p->make_directory ()));
                  modules /= "modules";
                }
              }

              if (modules.empty ())
                fail << "unable to locate MSVC standard modules directory";

              mt = &ctx.targets.insert_locked (
                *x_mod,
                move (modules),
                dir_path (),
                m.name,
                string ("ixx"), // For C++14 during bootstrap.
                target_decl::implied,
                trace).first;

              // For MSVC it's easier to detect the runtime being used since
              // it's specified with the compile options (/MT[d], /MD[d]).
              //
              // Similar semantics as in extract_headers() except here we use
              // options visible from the root scope. Note that
              // find_option_prefixes() looks in reverse, so look in the
              // cmode, x_coptions, c_coptions order.
              //
              initializer_list<const char*> os {"/MD", "/MT", "-MD", "-MT"};

              const string* o;
              if ((o = find_option_prefixes (os, cmode))          != nullptr ||
                  (o = find_option_prefixes (os, rs, x_coptions)) != nullptr ||
                  (o = find_option_prefixes (os, rs, c_coptions)) != nullptr)
              {
                ot = (*o)[2] == 'D' ? otype::s : otype::a;
              }
              else
                ot = otype::s; // The default is /MD.

              break;
            }
          case compiler_type::gcc:
          case compiler_type::icc:
            {
              fail << "standard library module '" << m.name << "' is "
                   << "not yet supported in this compiler";
            }
          };

          pair<target&, ulock> tl (
            this->make_module_sidebuild ( // GCC 4.9
              a, bs, nullptr, ot, *mt, m.name));

          if (tl.second.owns_lock ())
          {
            // Special compile options for the std modules.
            //
            if (ctype == compiler_type::clang)
            {
              value& v (tl.first.append_locked (x_coptions));

              if (v.null)
                v = strings {};

              strings& cops (v.as<strings> ());

              switch (ctype)
              {
              case compiler_type::clang:
                {
                  cops.push_back ("-Wno-reserved-module-identifier");
                  break;
                }
              case compiler_type::msvc:
                // It appears nothing special is needed to compile MSVC
                // standard modules.
              case compiler_type::gcc:
              case compiler_type::icc:
                assert (false);
              };
            }

            tl.second.unlock ();
          }

          pts[start + i].target = &tl.first;
          m.score = match_max (m.name) + 1;
          continue; // Scan the rest to detect if all done.
        }

        done = false;
      }

      // Go over prerequisites and try to resolve imported modules with them.
      //
      if (!done)
      {
        for (prerequisite_member p: group_prerequisite_members (a, t))
        {
          if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
            continue;

          const target* pt (p.load ()); // Should be cached for libraries.

          if (pt != nullptr)
          {
            const file* lt (nullptr);

            if (const libx* l = pt->is_a<libx> ())
              lt = link_member (*l, a, li);
            else if (pt->is_a<liba> () ||
                     pt->is_a<libs> () ||
                     pt->is_a<libux> ())
              lt = &pt->as<file> ();

            // If this is a library, check its bmi{}s and mxx{}s.
            //
            if (lt != nullptr)
            {
              find (*lt, find);

              if (done)
                break;

              continue;
            }

            // Fall through.
          }

          // While it would have been even better not to search for a target,
          // we need to get hold of the corresponding mxx{} (unlikely but
          // possible for bmi{} to have a different name).
          //
          // While we want to use group_prerequisite_members() below, we
          // cannot call resolve_group() since we will be doing it
          // "speculatively" for modules that we may use but also for modules
          // that may use us. This quickly leads to deadlocks. So instead we
          // are going to perform an ad hoc group resolution.
          //
          const target* pg;
          if (p.is_a<bmi> ())
          {
            pg = pt != nullptr ? pt : &p.search (t);
            pt = &search (t, btt, p.key ()); // Same logic as in picking obj*{}.
          }
          else if (p.is_a (btt))
          {
            pg = &search (t, bmi::static_type, p.key ());
            if (pt == nullptr) pt = &p.search (t);
          }
          else
            continue;

          // Find the mxx{} prerequisite and extract its "file name" for the
          // fuzzy match unless the user specified the module name explicitly.
          //
          for (prerequisite_member p:
                 prerequisite_members (a, t, group_prerequisites (*pt, pg)))
          {
            if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
              continue;

            if (p.is_a (*x_mod))
            {
              // Check for an explicit module name. Only look for an existing
              // target (which means the name can only be specified on the
              // target itself, not target type/pattern-spec).
              //
              const target* mt (p.search_existing ());
              const string* n (mt != nullptr
                               ? cast_null<string> (mt->vars[c_module_name])
                               : nullptr);
              if (n != nullptr)
              {
                if (const target** p = check_exact (*n))
                  *p = pt;
              }
              else
              {
                // Fuzzy match.
                //
                string f;

                // Add the directory part if it is relative. The idea is to
                // include it into the module match, say hello.core vs
                // hello/mxx{core}.
                //
                // @@ MOD: Why not for absolute? Good question. What if it
                // contains special components, say, ../mxx{core}?
                //
                const dir_path& d (p.dir ());

                if (!d.empty () && d.relative ())
                  f = d.representation (); // Includes trailing slash.

                f += p.name ();
                check_fuzzy (pt, f);
              }
              break;
            }
          }

          if (done)
            break;
        }
      }

      // Diagnose unresolved modules.
      //
      if (!done)
      {
        for (size_t i (0); i != n; ++i)
        {
          if (pts[start + i] == nullptr && !std_module (imports[i].name))
          {
            // It would have been nice to print the location of the import
            // declaration. And we could save it during parsing at the expense
            // of a few paths (that can be pooled). The question is what to do
            // when we re-create this information from depdb? We could have
            // saved the location information there but the relative paths
            // (e.g., from the #line directives) could end up being wrong if
            // the we re-run from a different working directory.
            //
            // It seems the only workable approach is to extract full location
            // info during parse, not save it in depdb, when re-creating,
            // fallback to just src path without any line/column information.
            // This will probably cover the majority of case (most of the time
            // it will be a misspelled module name, not a removal of module
            // from buildfile).
            //
            // But at this stage this doesn't seem worth the trouble.
            //
            fail (relative (src))
              << "unable to resolve module " << imports[i].name <<
              info << "verify module interface is listed as a prerequisite, "
              << "otherwise" <<
              info << "consider adjusting module interface file names or" <<
              info << "consider specifying module name with " << x
              << ".module_name";
          }
        }
      }

      // Match in parallel and wait for completion.
      //
      match_members (a, t, pts, start);

      // Post-process the list of our (direct) imports. While at it, calculate
      // the checksum of all (direct and indirect) bmi{} paths.
      //
      size_t exported (n);
      size_t copied (pts.size ());

      for (size_t i (0); i != n; ++i)
      {
        const module_import& m (imports[i]);

        // Determine the position of the first re-exported bmi{}.
        //
        if (m.exported && exported == n)
          exported = i;

        const target* bt (pts[start + i]);

        if (bt == nullptr)
          continue; // Unresolved (std.*).

        // Verify our guesses against extracted module names but don't waste
        // time if it was a match against the actual module name.
        //
        const string& in (m.name);

        if (m.score <= match_max (in))
        {
          // As above (deffered failure).
          //
          const string* mn (
            cast_null<string> (bt->state[a].vars[c_module_name]));

          if (mn != nullptr && in != *mn)
          {
            // Note: matched, so the group should be resolved.
            //
            for (prerequisite_member p: group_prerequisite_members (a, *bt))
            {
              if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
                continue;

              if (p.is_a (*x_mod)) // Got to be there.
              {
                fail (relative (src))
                  << "failed to correctly guess module name from " << p <<
                  info << "guessed: " << in <<
                  info << "actual:  " << *mn <<
                  info << "consider adjusting module interface file names or" <<
                  info << "consider specifying module name with " << x
                  << ".module_name";
              }
            }
          }
        }

        // Hash (we know it's a file).
        //
        cs.append (bt->as<file> ().path ().string ());

        // Copy over bmi{}s from our prerequisites weeding out duplicates.
        //
        if (size_t j = bt->data<match_data> (a).modules.start)
        {
          // Hard to say whether we should reserve or not. We will probably
          // get quite a bit of duplications.
          //
          auto& bpts (bt->prerequisite_targets[a]);
          for (size_t m (bpts.size ()); j != m; ++j)
          {
            const target* et (bpts[j]);

            if (et == nullptr)
              continue; // Unresolved (std.*).

            // As above (deferred failure).
            //
            const string* mn (cast_null<string> (et->state[a].vars[c_module_name]));

            if (mn != nullptr &&
                find_if (imports.begin (), imports.end (),
                         [mn] (const module_import& i)
                         {
                           return i.name == *mn;
                         }) == imports.end ())
            {
              pts.push_back (et);
              cs.append (et->as<file> ().path ().string ());

              // Add to the list of imports for further duplicate suppression.
              // We could have stored reference to the name (e.g., in score)
              // but it's probably not worth it if we have a small string
              // optimization.
              //
              import_type t (mn->find (':') != string::npos
                             ? import_type::module_part
                             : import_type::module_intf);
              imports.push_back (module_import {t, *mn, true, 0});
            }
          }
        }
      }

      if (copied == pts.size ()) // No copied tail.
        copied = 0;

      if (exported == n) // No (own) re-exported imports.
        exported = copied;
      else
        exported += start; // Rebase.

      return module_positions {start, exported, copied};
    }

    // Find or create a modules sidebuild subproject returning its root
    // directory.
    //
    // @@ Could we omit creating a subproject if the sidebuild scope is the
    //    project scope itself? This would speed up simple examples (and
    //    potentially direct compilation that we may support).
    //
    pair<dir_path, const scope&> compile_rule::
    find_modules_sidebuild (const scope& rs) const
    {
      context& ctx (rs.ctx);

      // First figure out where we are going to build. We want to avoid
      // multiple sidebuilds so the outermost scope that has loaded the
      // cc.config module and that is within our amalgmantion seems like a
      // good place.
      //
      // @@ TODO: maybe we should cache this in compile_rule ctor like we
      //          do for the header cache?
      //
      const scope* as (&rs);
      {
        const scope* ws (as->weak_scope ());
        if (as != ws)
        {
          const scope* s (as);
          do
          {
            s = s->parent_scope ()->root_scope ();

            // Use cc.core.vars as a proxy for {c,cxx}.config (a bit smelly).
            //
            // This is also the module that registers the scope operation
            // callback that cleans up the subproject.
            //
            if (cast_false<bool> (s->vars["cc.core.vars.loaded"]))
              as = s;

          } while (s != ws);
        }
      }

      // We build modules in a subproject (since there might be no full
      // language support loaded in the amalgamation, only *.config). So the
      // first step is to check if the project has already been created and/or
      // loaded and if not, then to go ahead and do so.
      //
      dir_path pd (as->out_path () /
                   as->root_extra->build_dir /
                   module_build_modules_dir /=
                   x);

      const scope* ps (&ctx.scopes.find_out (pd));

      if (ps->out_path () != pd)
      {
        // Switch the phase to load then create and load the subproject.
        //
        phase_switch phs (ctx, run_phase::load);

        // Re-test again now that we are in exclusive phase (another thread
        // could have already created and loaded the subproject).
        //
        ps = &ctx.scopes.find_out (pd);

        if (ps->out_path () != pd)
        {
          // The project might already be created in which case we just need
          // to load it.
          //
          optional<bool> altn (false); // Standard naming scheme.
          if (!is_src_root (pd, altn))
          {
            // Copy our standard and force modules.
            //
            string extra;

            // @@ What happens if different projects used different standards?
            //    Specifically, how do we detect this and what can the user do
            //    about it? For the latter question, forcing the same standard
            //    with config.cxx.std seems like the only sensible option. For
            //    the former, we could read the value of cxx.std using our
            //    buildfile first-line peeking mechanism. But doing that for
            //    every module interface feels inefficient so we will probably
            //    need to cache it on the per-project basis. Maybe/later.
            //
            if (const string* std = cast_null<string> (rs[x_std]))
              extra += string (x) + ".std = " + *std + '\n';

            extra += string (x) + ".features.modules = true";

            create_project (
              pd,
              as->out_path ().relative (pd),  /* amalgamation */
              {},                             /* boot_modules */
              extra,                          /* root_pre */
              {string (x) + '.'},             /* root_modules */
              "",                             /* root_post */
              nullopt,                        /* config_module */
              nullopt,                        /* config_file */
              false,                          /* buildfile */
              "the cc module",
              2);                             /* verbosity */
          }

          ps = &load_project (ctx, pd, pd, false /* forwarded */);
        }
      }

      // Some sanity checks.
      //
#ifndef NDEBUG
      assert (ps->root ());
      const module* m (ps->find_module<module> (x));
      assert (m != nullptr && m->modules);
#endif

      return pair<dir_path, const scope&> (move (pd), *as);
    }

    // Synthesize a dependency for building a module binary interface of a
    // library on the side. If library is missing, then assume it's some
    // ad hoc/system library case (in which case we assume it's binless,
    // for now).
    //
    // The return value semantics is as in target_set::insert_locked().
    //
    pair<target&, ulock> compile_rule::
    make_module_sidebuild (action a,
                           const scope& bs,
                           const file* lt,
                           otype ot,
                           const target& mt,
                           const string& mn) const
    {
      tracer trace (x, "compile_rule::make_module_sidebuild");

      // Note: see also make_header_sidebuild() below.

      dir_path pd (find_modules_sidebuild (*bs.root_scope ()).first);

      // We need to come up with a file/target name that will be unique enough
      // not to conflict with other modules. If we assume that within an
      // amalgamation there is only one "version" of each module, then the
      // module name itself seems like a good fit. We just replace '.' with
      // '-' and ':' with '+'.
      //
      string mf;
      transform (mn.begin (), mn.end (),
                 back_inserter (mf),
                 [] (char c) {return c == '.' ? '-' : c == ':' ? '+' : c;});

      const target_type& tt (compile_types (ot).bmi);

      // Store the BMI target in the subproject root. If the target already
      // exists then we assume all this is already done (otherwise why would
      // someone have created such a target).
      //
      if (const target* bt = bs.ctx.targets.find (
            tt,
            pd,
            dir_path (), // Always in the out tree.
            mf,
            nullopt,     // Use default extension.
            trace))
        return pair<target&, ulock> (const_cast<target&> (*bt), ulock ());

      prerequisites ps;
      ps.push_back (prerequisite (mt));

      // We've added the mxx{} but it may import other modules from this
      // library. Or from (direct) dependencies of this library. We add them
      // all as prerequisites so that the standard module search logic can
      // sort things out. This is pretty similar to what we do in link when
      // synthesizing dependencies for bmi{}'s.
      //
      // Note: lt is matched and so the group is resolved.
      //
      if (lt != nullptr)
      {
        ps.push_back (prerequisite (*lt));
        for (prerequisite_member p: group_prerequisite_members (a, *lt))
        {
          // Ignore update=match.
          //
          lookup l;
          if (include (a, *lt, p, &l) != include_type::normal) // Excluded/ad hoc.
            continue;

          if (p.is_a<libx> () ||
              p.is_a<liba> () || p.is_a<libs> () || p.is_a<libux> ())
          {
            ps.push_back (p.as_prerequisite ());
          }
        }
      }

      auto p (bs.ctx.targets.insert_locked (
                tt,
                move (pd),
                dir_path (), // Always in the out tree.
                move (mf),
                nullopt,     // Use default extension.
                target_decl::implied,
                trace,
                true /* skip_find */));

      // Note that this is racy and someone might have created this target
      // while we were preparing the prerequisite list.
      //
      if (p.second)
      {
        p.first.prerequisites (move (ps));

        // Unless this is a binless library, we don't need the object file
        // (see config_data::b_binless for details).
        //
        p.first.vars.assign (b_binless) = (lt == nullptr ||
                                           lt->mtime () == timestamp_unreal);
      }

      return p;
    }

    // Synthesize a dependency for building a header unit binary interface on
    // the side.
    //
    const file& compile_rule::
    make_header_sidebuild (action a,
                           const scope& bs,
                           const file& t,
                           linfo li,
                           const file& ht) const
    {
      tracer trace (x, "compile_rule::make_header_sidebuild");

      // Note: similar to make_module_sidebuild() above.

      auto sb (find_modules_sidebuild (*bs.root_scope ()));
      dir_path pd (move (sb.first));
      const scope& as (sb.second);

      // Determine if this header belongs to one of the libraries we depend
      // on.
      //
      // Note that because libraries are not in prerequisite_targets, we have
      // to go through prerequisites, similar to append_library_options().
      //
      const target* lt (nullptr); // Can be lib{}.
      {
        // Note that any such library would necessarily be an interface
        // dependency so we never need to go into implementations.
        //
        auto imp = [] (const target&, bool) { return false; };

        // The same logic as in append_libraries().
        //
        appended_libraries ls;
        struct data
        {
          action              a;
          const file&         ht;
          const target*&      lt;
          appended_libraries& ls;
        } d {a, ht, lt, ls};

        auto lib = [&d] (
          const target* const* lc,
          const small_vector<reference_wrapper<const string>, 2>&,
          lflags,
          const string*,
          bool)
        {
          // Prune any further traversal if we already found it.
          //
          if (d.lt != nullptr)
            return false;

          const target* l (lc != nullptr ? *lc : nullptr); // Can be lib{}.

          if (l == nullptr)
            return true;

          // Suppress duplicates.
          //
          if (find (d.ls.begin (), d.ls.end (), l) != d.ls.end ())
            return false;

          // Feels like we should only consider non-utility libraries with
          // utilities being treated as "direct" use.
          //
          if (l->is_a<libux> ())
            return true;

          // Since the library is searched and matched, all the headers should
          // be in prerequisite_targets.
          //
          const auto& pts (l->prerequisite_targets[d.a]);
          if (find (pts.begin (), pts.end (), &d.ht) != pts.end ())
          {
            d.lt = l;
            return false;
          }

          d.ls.push_back (l);
          return true;
        };

        library_cache lib_cache;
        for (prerequisite_member p: group_prerequisite_members (a, t))
        {
          if (include (a, t, p) != include_type::normal) // Excluded/ad hoc.
            continue;

          // Should be already searched and matched for libraries.
          //
          if (const target* pt = p.load ())
          {
            if (const libx* l = pt->is_a<libx> ())
              pt = link_member (*l, a, li);

            bool la;
            const file* f;
            if ((la = (f = pt->is_a<liba> ()))  ||
                (la = (f = pt->is_a<libux> ())) ||
                (     (f = pt->is_a<libs> ())))
            {
              // Note that we are requesting process_libraries() to not pick
              // the liba/libs{} member of the installed libraries and return
              // the lib{} group itself instead. This is because, for the
              // installed case, the library prerequisites (both headers and
              // interface dependency libraries) are matched by file_rule
              // which won't pick the liba/libs{} member (naturally) but will
              // just match the lib{} group.
              //
              process_libraries (a, bs, nullopt, sys_lib_dirs,
                                 *f, la, 0, // lflags unused.
                                 imp, lib, nullptr,
                                 true /* self */,
                                 false /* proc_opt_group */,
                                 &lib_cache);

              if (lt != nullptr)
                break;
            }
          }
        }
      }

      // What should we use as a file/target name? On one hand we want it
      // unique enough so that <stdio.h> and <custom/stdio.h> don't end up
      // with the same BMI. On the other, we need the same headers resolving
      // to the same target, regardless of how they were imported. So it feels
      // like the name should be the absolute and normalized (actualized on
      // case-insensitive filesystems) header path. We could try to come up
      // with something by sanitizing certain characters, etc. But then the
      // names will be very long and ugly, they will run into path length
      // limits, etc. So instead we will use the file name plus an abbreviated
      // hash of the whole path, something like stdio-211321fe6de7.
      //
      string mf;
      {
        // @@ MODHDR: Can we assume the path is actualized since the header
        //            target came from enter_header()? No, not anymore: it
        //            is now normally just normalized.
        //
        const path& hp (ht.path ());
        mf = hp.leaf ().make_base ().string ();
        mf += '-';
        mf += sha256 (hp.string ()).abbreviated_string (12);
      }

      // If the header comes from the library, use its hbmi?{} type to
      // maximize reuse.
      //
      const target_type& tt (
        compile_types (
          lt != nullptr && !lt->is_a<lib> ()
          ? link_type (*lt).type
          : li.type).hbmi);

      if (const file* bt = bs.ctx.targets.find<file> (
            tt,
            pd,
            dir_path (), // Always in the out tree.
            mf,
            nullopt,     // Use default extension.
            trace))
        return *bt;

      prerequisites ps;
      ps.push_back (prerequisite (ht));

      // Similar story as for modules: the header may need poptions from its
      // library (e.g., -I to find other headers that it includes).
      //
      if (lt != nullptr)
        ps.push_back (prerequisite (*lt));
      else
      {
        // If the header does not belong to a library then this is a "direct"
        // use, for example, by an exe{} target. In this case we need to add
        // all the prerequisite libraries as well as scope p/coptions (in a
        // sense, we are trying to approximate how all the sources that would
        // typically include such a header are build).
        //
        // Note that this is also the case when we build the library's own
        // sources (in a way it would have been cleaner to always build
        // library's headers with only its "interface" options/prerequisites
        // but that won't be easy to achieve).
        //
        // Note also that at first it might seem like a good idea to
        // incorporate this information into the hash we use to form the BMI
        // name. But that would reduce sharing of the BMI. For example, that
        // would mean we will build the library header twice, once with the
        // implementation options/prerequisites and once -- with interface.
        // On the other hand, importable headers are expected to be "modular"
        // and should probably not depend on any of the implementation
        // options/prerequisites (though one could conceivably build a
        // "richer" BMI if it is also to be used to build the library
        // implementation -- interesting idea).
        //
        for (prerequisite_member p: group_prerequisite_members (a, t))
        {
          // Ignore update=match.
          //
          lookup l;
          if (include (a, t, p, &l) != include_type::normal) // Excluded/ad hoc.
            continue;

          if (p.is_a<libx> () ||
              p.is_a<liba> () || p.is_a<libs> () || p.is_a<libux> ())
          {
            ps.push_back (p.as_prerequisite ());
          }
        }
      }

      auto p (bs.ctx.targets.insert_locked (
                tt,
                move (pd),
                dir_path (), // Always in the out tree.
                move (mf),
                nullopt,     // Use default extension.
                target_decl::implied,
                trace,
                true /* skip_find */));
      file& bt (p.first.as<file> ());

      // Note that this is racy and someone might have created this target
      // while we were preparing the prerequisite list.
      //
      if (p.second)
      {
        bt.prerequisites (move (ps));

        // Add the p/coptions from our scope in case of a "direct" use. Take
        // into account hbmi{} target-type/pattern values to allow specifying
        // hbmi-specific options.
        //
        if (lt == nullptr)
        {
          auto set = [&bs, &as, &tt, &bt] (const variable& var)
          {
            // Avoid duplicating the options if they are from the same
            // amalgamation as the sidebuild.
            //
            lookup l (bs.lookup (var, tt, bt.name, hbmi::static_type, bt.name));
            if (l.defined () && !l.belongs (as))
              bt.assign (var) = *l;
          };

          set (c_poptions);
          set (x_poptions);
          set (c_coptions);
          set (x_coptions);
        }
      }

      return bt;
    }

    // Filter cl.exe noise (msvc.cxx).
    //
    void
    msvc_filter_cl (diag_buffer&, const path& src);

    // Append header unit-related options.
    //
    // Note that this function is called for both full preprocessing and
    // compilation proper and in the latter case it is followed by a call
    // to append_module_options().
    //
    void compile_rule::
    append_header_options (environment&,
                           cstrings& args,
                           small_vector<string, 2>& stor,
                           action,
                           const file&,
                           const match_data& md,
                           const path& dd) const
    {
      switch (ctype)
      {
      case compiler_type::gcc:
        {
          if (md.header_units != 0)
          {
            string s (relative (dd).string ());
            s.insert (0, "-fmodule-mapper=");
            s += "?@"; // Significant line prefix.
            stor.push_back (move (s));
          }

          break;
        }
      case compiler_type::clang:
      case compiler_type::msvc:
      case compiler_type::icc:
        break;
      }

      // Shallow-copy storage to args. Why not do it as we go along pushing
      // into storage? Because of potential reallocations.
      //
      for (const string& a: stor)
        args.push_back (a.c_str ());
    }

    // Append module-related options.
    //
    // Note that this function is only called for the compilation proper and
    // after a call to append_header_options() (so watch out for duplicate
    // options).
    //
    void compile_rule::
    append_module_options (environment&,
                           cstrings& args,
                           small_vector<string, 2>& stor,
                           action a,
                           const file& t,
                           const match_data& md,
                           const path& dd) const
    {
      unit_type ut (md.type);
      const module_positions& ms (md.modules);

      switch (ctype)
      {
      case compiler_type::gcc:
        {
          // Use the module map stored in depdb.
          //
          // Note that it is also used to specify the output BMI file.
          //
          if (md.header_units == 0 && // In append_header_options()?
              (ms.start != 0                     ||
               ut == unit_type::module_intf      ||
               ut == unit_type::module_intf_part ||
               ut == unit_type::module_impl_part ||
               ut == unit_type::module_header))
          {
            string s (relative (dd).string ());
            s.insert (0, "-fmodule-mapper=");
            s += "?@"; // Cookie (aka line prefix).
            stor.push_back (move (s));
          }

          break;
        }
      case compiler_type::clang:
        {
          if (ms.start == 0)
            return;

          // If/when we get the ability to specify the mapping in a file.
          //
#if 0
          // In Clang the module implementation's unit .pcm is special and
          // must be "loaded". Note: not anymore, not from Clang 16 and is
          // deprecated in 17.
          //
          if (ut == unit_type::module_impl)
          {
            const file& f (pts[ms.start]->as<file> ());
            string s (relative (f.path ()).string ());
            s.insert (0, "-fmodule-file=");
            stor.push_back (move (s));
          }

          // Use the module map stored in depdb for others.
          //
          string s (relative (dd).string ());
          s.insert (0, "-fmodule-file-map=@=");
          stor.push_back (move (s));
#else
          auto& pts (t.prerequisite_targets[a]);
          for (size_t i (ms.start), n (pts.size ()); i != n; ++i)
          {
            const target* pt (pts[i]);

            if (pt == nullptr)
              continue;

            // Here we use whatever bmi type has been added. And we know all
            // of these are bmi's.
            //
            const file& f (pt->as<file> ());
            string s (relative (f.path ()).string ());

            s.insert (0, 1, '=');
            s.insert (0, cast<string> (f.state[a].vars[c_module_name]));
            s.insert (0, "-fmodule-file=");

            stor.push_back (move (s));
          }
#endif
          break;
        }
      case compiler_type::msvc:
        {
          if (ms.start == 0)
            return;

          // MSVC requires a transitive set of interfaces, including
          // implementation partitions.
          //
          auto& pts (t.prerequisite_targets[a]);
          for (size_t i (ms.start), n (pts.size ()); i != n; ++i)
          {
            const target* pt (pts[i]);

            if (pt == nullptr)
              continue;

            // Here we use whatever bmi type has been added. And we know all
            // of these are bmi's.
            //
            const file& f (pt->as<file> ());
            string s (relative (f.path ()).string ());

            s.insert (0, 1, '=');
            s.insert (0, cast<string> (f.state[a].vars[c_module_name]));

            stor.push_back (move (s));
          }

          break;
        }
      case compiler_type::icc:
        break;
      }

      // Shallow-copy storage to args. Why not do it as we go along pushing
      // into storage? Because of potential reallocations.
      //
      for (const string& a: stor)
      {
        if (ctype == compiler_type::msvc)
          args.push_back ("/reference");

        args.push_back (a.c_str ());
      }
    }

    target_state compile_rule::
    perform_update (action a, const target& xt, match_data& md) const
    {
      const file& t (xt.as<file> ());
      const path& tp (t.path ());

      unit_type ut (md.type);

      context& ctx (t.ctx);

      // While all our prerequisites are already up-to-date, we still have to
      // execute them to keep the dependency counts straight. Actually, no, we
      // may also have to update the modules.
      //
      // Note that this also takes care of forcing update on any ad hoc
      // prerequisite change.
      //
      auto pr (
        execute_prerequisites<file> (
          md.src.type (),
          a, t,
          md.mt,
          [s = md.modules.start] (const target&, size_t i)
          {
            return s != 0 && i >= s; // Only compare timestamps for modules.
          },
          md.modules.copied)); // See search_modules() for details.

      // Force recompilation in case of a deferred failure even if nothing
      // changed.
      //
      if (pr.first && !md.deferred_failure)
      {
        if (md.touch)
        {
          touch (ctx, tp, false, 2);
          t.mtime (system_clock::now ());
          ctx.skip_count.fetch_add (1, memory_order_relaxed);
        }
        // Note: else mtime should be cached.

        return *pr.first;
      }

      const file& s (pr.second);
      const path* sp (&s.path ());

      // Make sure depdb is no older than any of our prerequisites (see md.mt
      // logic description above for details). Also save the sequence start
      // time if doing mtime checks (see the depdb::check_mtime() call below).
      //
      timestamp start (!ctx.dry_run && depdb::mtime_check ()
                       ? system_clock::now ()
                       : timestamp_unknown);

      touch (ctx, md.dd, false, verb_never);

      const scope& bs (t.base_scope ());

      otype ot (compile_type (t, ut));
      linfo li (link_info (bs, ot));
      compile_target_types tts (compile_types (ot));

      environment env;
      cstrings args {cpath.recall_string ()};

      // If we are building a module interface or partition, then the target
      // is bmi*{} and it may have an ad hoc obj*{} member. For header units
      // there is no obj*{} (see the corresponding add_adhoc_member() call in
      // apply()). For named modules there may be no obj*{} if this is a
      // sidebuild (obj*{} is already in the library binary).
      //
      path relm;
      path relo;
      switch (ut)
      {
      case unit_type::module_header:
        break;
      case unit_type::module_intf:
      case unit_type::module_intf_part:
      case unit_type::module_impl_part:
        {
          if (const file* o = find_adhoc_member<file> (t, tts.obj))
            relo = relative (o->path ());

          break;
        }
      default:
        relo = relative (tp);
      }

      // Build the command line.
      //
      if (md.pp != preprocessed::all)
      {
        // Note that these come in the reverse order of coptions since the
        // header search paths are examined in the order specified (in
        // contrast to the "last value wins" semantics that we assume for
        // coptions).
        //
        append_options (args, t, x_poptions);
        append_options (args, t, c_poptions);

        // Add *.export.poptions from prerequisite libraries.
        //
        append_library_options (args, bs, a, t, li);

        if (md.symexport)
          append_symexport_options (args, t);
      }

      append_options (args, t, c_coptions);
      append_options (args, t, x_coptions);

      string out, out1;                    // Output options storage.
      small_vector<string, 2> header_args; // Header unit options storage.
      small_vector<string, 2> module_args; // Module options storage.

      switch (cclass)
      {
      case compiler_class::msvc:
        {
          // The /F*: option variants with separate names only became
          // available in VS2013/12.0. Why do we bother? Because the command
          // line suddenly becomes readable.
          //
          // Also, clang-cl does not yet support them, at least not in 8 or 9.
          //
          bool fc (cmaj >= 18 && cvariant != "clang");

          args.push_back ("/nologo");

          append_options (args, cmode);

          if (md.pp != preprocessed::all)
            append_sys_hdr_options (args); // Extra system header dirs (last).

          // Note: could be overridden in mode.
          //
          append_diag_color_options (args);

          // Set source/execution charsets to UTF-8 unless a custom charset
          // is specified.
          //
          // Note that clang-cl supports /utf-8 and /*-charset.
          //
          {
            bool sc (find_option_prefixes (
                       {"/source-charset:", "-source-charset:"}, args));
            bool ec (find_option_prefixes (
                       {"/execution-charset:", "-execution-charset:"}, args));

            if (!sc && !ec)
              args.push_back ("/utf-8");
            else
            {
              if (!sc)
                args.push_back ("/source-charset:UTF-8");

              if (!ec)
                args.push_back ("/execution-charset:UTF-8");
            }
          }

          // If we have any /external:I options but no /external:Wn, then add
          // /external:W0 to emulate the -isystem semantics.
          //
          if (cvariant != "clang" && isystem (*this))
          {
            if (find_option_prefixes ({"/external:I", "-external:I"}, args) &&
                !find_option_prefixes ({"/external:W", "-external:W"}, args))
              args.push_back ("/external:W0");
          }

          // While we want to keep the low-level build as "pure" as possible,
          // the two misguided defaults, C++ exceptions and runtime, just have
          // to be fixed. Otherwise the default build is pretty much unusable.
          // But we also make sure that the user can easily disable our
          // defaults: if we see any relevant options explicitly specified, we
          // take our hands off.
          //
          // For C looks like no /EH* (exceptions supported but no C++ objects
          // destroyed) is a reasonable default.
          //

          if (x_lang == lang::cxx &&
              !find_option_prefixes ({"/EH", "-EH"}, args))
            args.push_back ("/EHsc");

          // The runtime is a bit more interesting. At first it may seem like
          // a good idea to be a bit clever and use the static runtime if we
          // are building obja{}. And for obje{} we could decide which runtime
          // to use based on the library link order: if it is static-only,
          // then we could assume the static runtime. But it is indeed too
          // clever: when building liba{} we have no idea who is going to use
          // it. It could be an exe{} that links both static and shared
          // libraries (and is therefore built with the shared runtime). And
          // to safely use the static runtime, everything must be built with
          // /MT and there should be no DLLs in the picture. So we are going
          // to play it safe and always default to the shared runtime.
          //
          // In a similar vein, it would seem reasonable to use the debug
          // runtime if we are compiling with debug. But, again, there will be
          // fireworks if we have some projects built with debug and some
          // without and then we try to link them together (which is not an
          // unreasonable thing to do). So by default we will always use the
          // release runtime.
          //
          if (!find_option_prefixes ({"/MD", "/MT", "-MD", "-MT"}, args))
            args.push_back ("/MD");

          msvc_sanitize_cl (args);

          append_header_options (env, args, header_args, a, t, md, md.dd);
          append_module_options (env, args, module_args, a, t, md, md.dd);

          // The presence of /Zi or /ZI causes the compiler to write debug
          // info to the .pdb file. By default it is a shared file called
          // vcNN.pdb (where NN is the VC version) created (wait for it) in
          // the current working directory (and not the directory of the .obj
          // file). Also, because it is shared, there is a special Windows
          // service that serializes access. We, of course, want none of that
          // so we will create a .pdb per object file.
          //
          // Note that this also changes the name of the .idb file (used for
          // minimal rebuild and incremental compilation): cl.exe take the /Fd
          // value and replaces the .pdb extension with .idb.
          //
          // Note also that what we are doing here appears to be incompatible
          // with PCH (/Y* options) and /Gm (minimal rebuild).
          //
          if (!relo.empty () &&
              find_options ({"/Zi", "/ZI", "-Zi", "-ZI"}, args))
          {
            if (fc)
              args.push_back ("/Fd:");
            else
              out1 = "/Fd";

            out1 += relo.string ();
            out1 += ".pdb";

            args.push_back (out1.c_str ());
          }

          if (ut == unit_type::module_intf      ||
              ut == unit_type::module_intf_part ||
              ut == unit_type::module_impl_part ||
              ut == unit_type::module_header)
          {
            assert (ut != unit_type::module_header); // @@ MODHDR

            relm = relative (tp);

            args.push_back ("/ifcOutput");
            args.push_back (relm.string ().c_str ());

            if (relo.empty ())
              args.push_back ("/ifcOnly");
            else
            {
              args.push_back ("/Fo:");
              args.push_back (relo.string ().c_str ());
            }
          }
          else
          {
            if (fc)
            {
              args.push_back ("/Fo:");
              args.push_back (relo.string ().c_str ());
            }
            else
            {
              out = "/Fo" + relo.string ();
              args.push_back (out.c_str ());
            }
          }

          // Note: no way to indicate that the source if already preprocessed.

          args.push_back ("/c");                   // Compile only.
          append_lang_options (args, md);          // Compile as.
          args.push_back (sp->string ().c_str ()); // Note: relied on being last.

          break;
        }
      case compiler_class::gcc:
        {
          append_options (args, cmode);

          // Clang 15 introduced the unqualified-std-cast-call warning which
          // warns about unqualified calls to std::move() and std::forward()
          // (because they can be "hijacked" via ADL). Surprisingly, this
          // warning is enabled by default, as opposed to with -Wextra or at
          // least -Wall. It has also proven to be quite disruptive, causing a
          // large number of warnings in a large number of packages. So we are
          // going to "remap" it to -Wextra for now and in the future may
          // "relax" it to -Wall and potentially to being enabled by default.
          // See GitHub issue #259 for background and details.
          //
          if (x_lang == lang::cxx           &&
              ctype == compiler_type::clang &&
              cmaj >= 15)
          {
            bool w (false);       // Seen -W[no-]unqualified-std-cast-call
            optional<bool> extra; // Seen -W[no-]extra

            for (const char* s: reverse_iterate (args))
            {
              if (s != nullptr)
              {
                if (strcmp (s, "-Wunqualified-std-cast-call") == 0 ||
                    strcmp (s, "-Wno-unqualified-std-cast-call") == 0)
                {
                  w = true;
                  break;
                }

                if (!extra) // Last seen option wins.
                {
                  if      (strcmp (s, "-Wextra") == 0) extra = true;
                  else if (strcmp (s, "-Wno-extra") == 0) extra = false;
                }
              }
            }

            if (!w && (!extra || !*extra))
              args.push_back ("-Wno-unqualified-std-cast-call");
          }

          if (md.pp != preprocessed::all)
            append_sys_hdr_options (args); // Extra system header dirs (last).

          // Note: could be overridden in mode.
          //
          append_diag_color_options (args);

          // Set the input charset to UTF-8 unless a custom one is specified.
          //
          // Note that the execution charset (-fexec-charset) is UTF-8 by
          // default.
          //
          // Note that early versions of Clang only recognize uppercase UTF-8.
          //
          if (!find_option_prefix ("-finput-charset=", args))
            args.push_back ("-finput-charset=UTF-8");

          if (ot == otype::s)
          {
            // On Darwin, Win32 -fPIC is the default.
            //
            if (tclass == "linux" || tclass == "bsd")
              args.push_back ("-fPIC");
          }

          if (tsys == "win32-msvc")
          {
            switch (ctype)
            {
            case compiler_type::clang:
              {
                // Default to the /EHsc exceptions support for C++, similar to
                // the the MSVC case above.
                //
                // Note that both vanilla clang++ and clang-cl drivers add
                // -fexceptions and -fcxx-exceptions by default. However,
                // clang-cl also adds -fexternc-nounwind, which implements the
                // 'c' part in /EHsc. Note that adding this option is not a
                // mere optimization, as we have discovered through some
                // painful experience; see Clang bug #45021.
                //
                // Let's also omit this option if -f[no]-exceptions is
                // specified explicitly.
                //
                if (x_lang == lang::cxx)
                {
                  if (!find_options ({"-fexceptions", "-fno-exceptions"}, args))
                  {
                    args.push_back ("-Xclang");
                    args.push_back ("-fexternc-nounwind");
                  }
                }

                // Default to the multi-threaded DLL runtime (/MD), similar to
                // the MSVC case above.
                //
                // Clang's MSVC.cpp will not link the default runtime if
                // either -nostdlib or -nostartfiles is specified. Let's do
                // the same.
                //
                if (!find_options ({"-nostdlib", "-nostartfiles"}, args))
                {
                  args.push_back ("-D_MT");
                  args.push_back ("-D_DLL");

                  // All these -Xclang --dependent-lib=... add quite a bit of
                  // noise to the command line. The alternative is to use the
                  // /DEFAULTLIB option during linking. The drawback of that
                  // approach is that now we can theoretically build the
                  // object file for one runtime but try to link it with
                  // something else.
                  //
                  // For example, an installed static library was built for a
                  // non-debug runtime while a project that links it uses
                  // debug. With the --dependent-lib approach we will try to
                  // link multiple runtimes while with /DEFAULTLIB we may end
                  // up with unresolved symbols (but things might also work
                  // out fine, unless the runtimes have incompatible ABIs).
                  //
                  // Let's start with /DEFAULTLIB and see how it goes (see the
                  // link rule).
                  //
#if 0
                  args.push_back ("-Xclang");
                  args.push_back ("--dependent-lib=msvcrt");

                  // This provides POSIX compatibility (map open() to _open(),
                  // etc).
                  //
                  args.push_back ("-Xclang");
                  args.push_back ("--dependent-lib=oldnames");
#endif
                }

                break;
              }
            case compiler_type::gcc:
            case compiler_type::msvc:
            case compiler_type::icc:
              assert (false);
            }
          }

          // For now Emscripten defaults to partial C++ exceptions support
          // (you can throw but not catch). We enable full support unless it
          // was explicitly disabled by the user.
          //
          if (ctype == compiler_type::clang && cvariant == "emscripten")
          {
            if (x_lang == lang::cxx)
            {
              if (!find_option_prefix ("DISABLE_EXCEPTION_CATCHING=", args))
              {
                args.push_back ("-s");
                args.push_back ("DISABLE_EXCEPTION_CATCHING=0");
              }
            }
          }

          append_header_options (env, args, header_args, a, t, md, md.dd);
          append_module_options (env, args, module_args, a, t, md, md.dd);

          if (ut == unit_type::module_intf      ||
              ut == unit_type::module_intf_part ||
              ut == unit_type::module_impl_part ||
              ut == unit_type::module_header)
          {
            switch (ctype)
            {
            case compiler_type::gcc:
              {
                // Output module file is specified in the mapping file, the
                // same as input.
                //
                if (ut == unit_type::module_header) // No obj, -c implied.
                  break;

                if (!relo.empty ())
                {
                  args.push_back ("-o");
                  args.push_back (relo.string ().c_str ());
                }
                else if (ut != unit_type::module_header)
                {
                  // Should this be specified in append_lang_options() like
                  // -fmodule-header (which, BTW, implies -fmodule-only)?
                  // While it's plausible that -fmodule-header has some
                  // semantic differences that should be in effect during
                  // preprocessing, -fmodule-only seems to only mean "don't
                  // write the object file" so for now we specify it only
                  // here.
                  //
                  args.push_back ("-fmodule-only");
                }

                args.push_back ("-c");
                break;
              }
            case compiler_type::clang:
              {
                assert (ut != unit_type::module_header); // @@ MODHDR

                relm = relative (tp);

                // Without this option Clang's .pcm will reference source
                // files. In our case this file may be transient (.ii). Plus,
                // it won't play nice with distributed compilation.
                //
                // Note that this sort of appears to be the default from Clang
                // 17, but not quite, see llvm-project issued #72383.
                //
                args.push_back ("-Xclang");
                args.push_back ("-fmodules-embed-all-files");

                if (relo.empty ())
                {
                  args.push_back ("-o");
                  args.push_back (relm.string ().c_str ());
                  args.push_back ("--precompile");
                }
                else
                {
                  out1 = "-fmodule-output=" + relm.string ();
                  args.push_back (out1.c_str ());
                  args.push_back ("-o");
                  args.push_back (relo.string ().c_str ());
                  args.push_back ("-c");
                }

                break;
              }
            case compiler_type::msvc:
            case compiler_type::icc:
              assert (false);
            }
          }
          else
          {
            args.push_back ("-o");
            args.push_back (relo.string ().c_str ());
            args.push_back ("-c");
          }

          append_lang_options (args, md);

          if (md.pp == preprocessed::all)
          {
            // Note that the mode we select must still handle comments and
            // line continuations. So some more compiler-specific voodoo.
            //
            switch (ctype)
            {
            case compiler_type::gcc:
              {
                // -fdirectives-only is available since GCC 4.3.0.
                //
                if (cmaj > 4 || (cmaj == 4 && cmin >= 3))
                {
                  args.push_back ("-fpreprocessed");
                  args.push_back ("-fdirectives-only");
                }
                break;
              }
            case compiler_type::clang:
              {
                // Clang handles comments and line continuations in the
                // preprocessed source (it does not have -fpreprocessed).
                //
                break;
              }
            case compiler_type::icc:
              break; // Compile as normal source for now.
            case compiler_type::msvc:
              assert (false);
            }
          }

          args.push_back (sp->string ().c_str ());

          break;
        }
      }

      args.push_back (nullptr);

      if (!env.empty ())
        env.push_back (nullptr);

      // We have no choice but to serialize early if we want the command line
      // printed shortly before actually executing the compiler. Failed that,
      // it may look like we are still executing in parallel.
      //
      scheduler::alloc_guard jobs_ag;
      if (!ctx.dry_run && cast_false<bool> (t[c_serialize]))
        jobs_ag = scheduler::alloc_guard (*ctx.sched, phase_unlock (nullptr));

      // With verbosity level 2 print the command line as if we are compiling
      // the source file, not its preprocessed version (so that it's easy to
      // copy and re-run, etc). Only at level 3 and above print the real deal.
      //
      // @@ TODO: why don't we print env (here and/or below)? Also link rule.
      //
      if (verb == 1)
      {
        const char* name (x_assembler_cpp (s) ? "as-cpp"   :
                          x_objective (s)     ? x_obj_name :
                          x_name);

        print_diag (name, s, t);
      }
      else if (verb == 2)
        print_process (args);

      // If we have the (partially) preprocessed output, switch to that.
      //
      // But we remember the original source/position to restore later.
      //
      bool psrc (md.psrc); // Note: false if cc.reprocess.
      bool ptmp (psrc && md.psrc.temporary);
      pair<size_t, const char*> osrc;
      if (psrc)
      {
        args.pop_back (); // nullptr
        osrc.second = args.back ();
        args.pop_back (); // sp
        osrc.first = args.size ();

        sp = &md.psrc.path ();

        // This should match with how we setup preprocessing.
        //
        switch (ctype)
        {
        case compiler_type::gcc:
          {
            // -fpreprocessed is implied by .i/.ii unless compiling a header
            // unit (there is no .hi/.hii). Also, we would need to pop -x
            // since it takes precedence over the extension, which would mess
            // up our osrc logic. So in the end it feels like always passing
            // explicit -fpreprocessed is the way to go.
            //
            // Also note that similarly there is no .Si for .S files.
            //
            args.push_back ("-fpreprocessed");
            args.push_back ("-fdirectives-only");
            break;
          }
        case compiler_type::clang:
          {
            // Clang 15 and later with -pedantic warns about GNU-style line
            // markers that it wrote itself in the -frewrite-includes output
            // (llvm-project issue 63284). So we suppress this warning unless
            // compiling from source.
            //
            // In Apple Clang this warning/option are absent in 14.0.3 (which
            // is said to be based on vanilla Clang 15.0.5) for some reason
            // (let's hope it's because they patched it out rather than due to
            // a misleading _LIBCPP_VERSION value).
            //
            if (ctype == compiler_type::clang &&
                cmaj >= (cvariant != "apple" ? 15 : 16))
            {
              if (find_options ({"-pedantic",  "-pedantic-errors",
                                 "-Wpedantic", "-Werror=pedantic"}, args))
              {
                args.push_back ("-Wno-gnu-line-marker");
              }
            }

            // Note that without -x Clang will treat .i/.ii as fully
            // preprocessed.
            //
            break;
          }
        case compiler_type::msvc:
          {
            // Nothing to do (/TP or /TC already there).
            //
            break;
          }
        case compiler_type::icc:
          assert (false);
        }

        args.push_back (sp->string ().c_str ());
        args.push_back (nullptr);

        // Let's keep the preprocessed file in case of an error but only at
        // verbosity level 3 and up (when one actually sees it mentioned on
        // the command line). We also have to re-enable on success (see
        // below).
        //
        if (ptmp && verb >= 3)
          md.psrc.temporary = false;
      }

      if (verb >= 3)
        print_process (args);

      // @@ DRYRUN: Currently we discard the (partially) preprocessed file on
      // dry-run which is a waste. Even if we keep the file around (like we do
      // for the error case; see above), we currently have no support for
      // re-using the previously preprocessed output. However, everything
      // points towards us needing this in the near future since with modules
      // we may be out of date but not needing to re-preprocess the
      // translation unit (i.e., one of the imported module's BMIs has
      // changed).
      //
      if (!ctx.dry_run)
      {
        try
        {
          // If we are compiling the preprocessed output, get its read handle.
          //
          file_cache::read psrcr (psrc ? md.psrc.open () : file_cache::read ());

          // VC cl.exe sends diagnostics to stdout. It also prints the file
          // name being compiled as the first line. So for cl.exe we filter
          // that noise out.
          //
          // For other compilers also redirect stdout to stderr, in case any
          // of them tries to pull off something similar. For sane compilers
          // this should be harmless.
          //
          bool filter (ctype == compiler_type::msvc);

          process pr (cpath,
                      args,
                      0, 2, diag_buffer::pipe (ctx, filter /* force */),
                      nullptr, // CWD
                      env.empty () ? nullptr : env.data ());

          diag_buffer dbuf (ctx, args[0], pr);

          if (filter)
            msvc_filter_cl (dbuf, *sp);

          dbuf.read ();

          // Restore the original source if we switched to preprocessed.
          //
          if (psrc)
          {
            args.resize (osrc.first);
            args.push_back (osrc.second);
            args.push_back (nullptr);
          }

          run_finish (dbuf, args, pr, 1 /* verbosity */);
        }
        catch (const process_error& e)
        {
          error << "unable to execute " << args[0] << ": " << e;

          if (e.child)
            exit (1);

          throw failed ();
        }

        jobs_ag.deallocate ();

        if (md.deferred_failure)
          fail << "expected error exit status from " << x_lang << " compiler";
      }

      // Remove preprocessed file (see above).
      //
      if (ptmp && verb >= 3)
        md.psrc.temporary = true;

      timestamp now (system_clock::now ());

      if (!ctx.dry_run)
        depdb::check_mtime (start, md.dd, tp, now);

      // Should we go to the filesystem and get the new mtime? We know the
      // file has been modified, so instead just use the current clock time.
      // It has the advantage of having the subseconds precision. Plus, in
      // case of dry-run, the file won't be modified.
      //
      t.mtime (now);
      return target_state::changed;
    }

    target_state compile_rule::
    perform_clean (action a, const target& xt, const target_type& srct) const
    {
      const file& t (xt.as<file> ());

      // Preprocessed file extension.
      //
      const char* pext (x_assembler_cpp (srct) ? ".Si"      :
                        x_objective (srct)     ? x_obj_pext :
                        x_pext);

      // Compressed preprocessed file extension.
      //
      string cpext (t.ctx.fcache->compressed_extension (pext));

      clean_extras extras;
      switch (ctype)
      {
      case compiler_type::gcc:   extras = {".d", pext, cpext.c_str (), ".t"};           break;
      case compiler_type::clang: extras = {".d", pext, cpext.c_str ()};                 break;
      case compiler_type::msvc:  extras = {".d", pext, cpext.c_str (), ".idb", ".pdb"}; break;
      case compiler_type::icc:   extras = {".d"};                                       break;
      }

      return perform_clean_extra (a, t, extras);
    }
  }
}