summaryrefslogtreecommitdiffstats
path: root/src/librustc/session/config.rs
blob: 755b4af1a3aed064f5199c739e8b93d8da6f4ccb (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
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Contains infrastructure for configuring the compiler, including parsing
//! command line options.

pub use self::EntryFnType::*;
pub use self::CrateType::*;
pub use self::Passes::*;
pub use self::DebugInfoLevel::*;

use std::str::FromStr;

use session::{early_error, early_warn, Session};
use session::search_paths::SearchPaths;

use ich::StableHashingContext;
use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
use rustc_target::spec::{Target, TargetTriple};
use rustc_data_structures::stable_hasher::ToStableHashKey;
use lint;
use middle::cstore;

use syntax::ast::{self, IntTy, UintTy};
use syntax::codemap::{FileName, FilePathMapping};
use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
use syntax::parse::token;
use syntax::parse;
use syntax::symbol::Symbol;
use syntax::feature_gate::UnstableFeatures;

use errors::{ColorConfig, FatalError, Handler};

use getopts;
use std::collections::{BTreeMap, BTreeSet};
use std::collections::btree_map::Iter as BTreeMapIter;
use std::collections::btree_map::Keys as BTreeMapKeysIter;
use std::collections::btree_map::Values as BTreeMapValuesIter;

use std::{fmt, str};
use std::hash::Hasher;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};

pub struct Config {
    pub target: Target,
    pub isize_ty: IntTy,
    pub usize_ty: UintTy,
}

#[derive(Clone, Hash, Debug)]
pub enum Sanitizer {
    Address,
    Leak,
    Memory,
    Thread,
}

#[derive(Clone, Copy, PartialEq, Hash)]
pub enum OptLevel {
    No,         // -O0
    Less,       // -O1
    Default,    // -O2
    Aggressive, // -O3
    Size,       // -Os
    SizeMin,    // -Oz
}

#[derive(Clone, Copy, PartialEq, Hash)]
pub enum Lto {
    /// Don't do any LTO whatsoever
    No,

    /// Do a full crate graph LTO. The flavor is determined by the compiler
    /// (currently the default is "fat").
    Yes,

    /// Do a full crate graph LTO with ThinLTO
    Thin,

    /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
    /// units).
    ThinLocal,

    /// Do a full crate graph LTO with "fat" LTO
    Fat,
}

#[derive(Clone, PartialEq, Hash)]
pub enum CrossLangLto {
    LinkerPlugin(PathBuf),
    NoLink,
    Disabled
}

impl CrossLangLto {
    pub fn embed_bitcode(&self) -> bool {
        match *self {
            CrossLangLto::LinkerPlugin(_) |
            CrossLangLto::NoLink => true,
            CrossLangLto::Disabled => false,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Hash)]
pub enum DebugInfoLevel {
    NoDebugInfo,
    LimitedDebugInfo,
    FullDebugInfo,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
pub enum OutputType {
    Bitcode,
    Assembly,
    LlvmAssembly,
    Mir,
    Metadata,
    Object,
    Exe,
    DepInfo,
}


impl_stable_hash_for!(enum self::OutputType {
    Bitcode,
    Assembly,
    LlvmAssembly,
    Mir,
    Metadata,
    Object,
    Exe,
    DepInfo
});

impl<'a, 'tcx> ToStableHashKey<StableHashingContext<'a>> for OutputType {
    type KeyType = OutputType;
    #[inline]
    fn to_stable_hash_key(&self, _: &StableHashingContext<'a>) -> Self::KeyType {
        *self
    }
}

impl OutputType {
    fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
        match *self {
            OutputType::Exe | OutputType::DepInfo => true,
            OutputType::Bitcode
            | OutputType::Assembly
            | OutputType::LlvmAssembly
            | OutputType::Mir
            | OutputType::Object
            | OutputType::Metadata => false,
        }
    }

    fn shorthand(&self) -> &'static str {
        match *self {
            OutputType::Bitcode => "llvm-bc",
            OutputType::Assembly => "asm",
            OutputType::LlvmAssembly => "llvm-ir",
            OutputType::Mir => "mir",
            OutputType::Object => "obj",
            OutputType::Metadata => "metadata",
            OutputType::Exe => "link",
            OutputType::DepInfo => "dep-info",
        }
    }

    fn from_shorthand(shorthand: &str) -> Option<Self> {
        Some(match shorthand {
            "asm" => OutputType::Assembly,
            "llvm-ir" => OutputType::LlvmAssembly,
            "mir" => OutputType::Mir,
            "llvm-bc" => OutputType::Bitcode,
            "obj" => OutputType::Object,
            "metadata" => OutputType::Metadata,
            "link" => OutputType::Exe,
            "dep-info" => OutputType::DepInfo,
            _ => return None,
        })
    }

    fn shorthands_display() -> String {
        format!(
            "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
            OutputType::Bitcode.shorthand(),
            OutputType::Assembly.shorthand(),
            OutputType::LlvmAssembly.shorthand(),
            OutputType::Mir.shorthand(),
            OutputType::Object.shorthand(),
            OutputType::Metadata.shorthand(),
            OutputType::Exe.shorthand(),
            OutputType::DepInfo.shorthand(),
        )
    }

    pub fn extension(&self) -> &'static str {
        match *self {
            OutputType::Bitcode => "bc",
            OutputType::Assembly => "s",
            OutputType::LlvmAssembly => "ll",
            OutputType::Mir => "mir",
            OutputType::Object => "o",
            OutputType::Metadata => "rmeta",
            OutputType::DepInfo => "d",
            OutputType::Exe => "",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorOutputType {
    HumanReadable(ColorConfig),
    Json(bool),
    Short(ColorConfig),
}

impl Default for ErrorOutputType {
    fn default() -> ErrorOutputType {
        ErrorOutputType::HumanReadable(ColorConfig::Auto)
    }
}

// Use tree-based collections to cheaply get a deterministic Hash implementation.
// DO NOT switch BTreeMap out for an unsorted container type! That would break
// dependency tracking for commandline arguments.
#[derive(Clone, Hash)]
pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);

impl_stable_hash_for!(tuple_struct self::OutputTypes {
    map
});

impl OutputTypes {
    pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
        OutputTypes(BTreeMap::from_iter(
            entries.iter().map(|&(k, ref v)| (k, v.clone())),
        ))
    }

    pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
        self.0.get(key)
    }

    pub fn contains_key(&self, key: &OutputType) -> bool {
        self.0.contains_key(key)
    }

    pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
        self.0.keys()
    }

    pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
        self.0.values()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    // True if any of the output types require codegen or linking.
    pub fn should_codegen(&self) -> bool {
        self.0.keys().any(|k| match *k {
            OutputType::Bitcode
            | OutputType::Assembly
            | OutputType::LlvmAssembly
            | OutputType::Mir
            | OutputType::Object
            | OutputType::Exe => true,
            OutputType::Metadata | OutputType::DepInfo => false,
        })
    }
}

// Use tree-based collections to cheaply get a deterministic Hash implementation.
// DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
// would break dependency tracking for commandline arguments.
#[derive(Clone, Hash)]
pub struct Externs(BTreeMap<String, BTreeSet<String>>);

impl Externs {
    pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
        Externs(data)
    }

    pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
        self.0.get(key)
    }

    pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
        self.0.iter()
    }
}

macro_rules! hash_option {
    ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
    ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
        if $sub_hashes.insert(stringify!($opt_name),
                              $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
            bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
        }
    });
    ($opt_name:ident,
     $opt_expr:expr,
     $sub_hashes:expr,
     [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
        if *$opt_expr == $warn_val {
            early_warn($error_format, $warn_text)
        }
    });
}

macro_rules! top_level_options {
    (pub struct Options { $(
        $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
    )* } ) => (
        #[derive(Clone)]
        pub struct Options {
            $(pub $opt: $t),*
        }

        impl Options {
            pub fn dep_tracking_hash(&self) -> u64 {
                let mut sub_hashes = BTreeMap::new();
                $({
                    hash_option!($opt,
                                 &self.$opt,
                                 &mut sub_hashes,
                                 [$dep_tracking_marker $($warn_val,
                                                         $warn_text,
                                                         self.error_format)*]);
                })*
                let mut hasher = DefaultHasher::new();
                dep_tracking::stable_hash(sub_hashes,
                                          &mut hasher,
                                          self.error_format);
                hasher.finish()
            }
        }
    );
}

// The top-level commandline options struct
//
// For each option, one has to specify how it behaves with regard to the
// dependency tracking system of incremental compilation. This is done via the
// square-bracketed directive after the field type. The options are:
//
// [TRACKED]
// A change in the given field will cause the compiler to completely clear the
// incremental compilation cache before proceeding.
//
// [UNTRACKED]
// Incremental compilation is not influenced by this option.
//
// [UNTRACKED_WITH_WARNING(val, warning)]
// The option is incompatible with incremental compilation in some way. If it
// has the value `val`, the string `warning` is emitted as a warning.
//
// If you add a new option to this struct or one of the sub-structs like
// CodegenOptions, think about how it influences incremental compilation. If in
// doubt, specify [TRACKED], which is always "correct" but might lead to
// unnecessary re-compilation.
top_level_options!(
    pub struct Options {
        // The crate config requested for the session, which may be combined
        // with additional crate configurations during the compile process
        crate_types: Vec<CrateType> [TRACKED],
        optimize: OptLevel [TRACKED],
        // Include the debug_assertions flag into dependency tracking, since it
        // can influence whether overflow checks are done or not.
        debug_assertions: bool [TRACKED],
        debuginfo: DebugInfoLevel [TRACKED],
        lint_opts: Vec<(String, lint::Level)> [TRACKED],
        lint_cap: Option<lint::Level> [TRACKED],
        describe_lints: bool [UNTRACKED],
        output_types: OutputTypes [TRACKED],
        search_paths: SearchPaths [UNTRACKED],
        libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
        maybe_sysroot: Option<PathBuf> [TRACKED],

        target_triple: TargetTriple [TRACKED],

        test: bool [TRACKED],
        error_format: ErrorOutputType [UNTRACKED],

        // if Some, enable incremental compilation, using the given
        // directory to store intermediate results
        incremental: Option<PathBuf> [UNTRACKED],

        debugging_opts: DebuggingOptions [TRACKED],
        prints: Vec<PrintRequest> [UNTRACKED],
        // Determines which borrow checker(s) to run. This is the parsed, sanitized
        // version of `debugging_opts.borrowck`, which is just a plain string.
        borrowck_mode: BorrowckMode [UNTRACKED],
        cg: CodegenOptions [TRACKED],
        externs: Externs [UNTRACKED],
        crate_name: Option<String> [TRACKED],
        // An optional name to use as the crate for std during std injection,
        // written `extern crate name as std`. Defaults to `std`. Used by
        // out-of-tree drivers.
        alt_std_name: Option<String> [TRACKED],
        // Indicates how the compiler should treat unstable features
        unstable_features: UnstableFeatures [TRACKED],

        // Indicates whether this run of the compiler is actually rustdoc. This
        // is currently just a hack and will be removed eventually, so please
        // try to not rely on this too much.
        actually_rustdoc: bool [TRACKED],

        // Specifications of codegen units / ThinLTO which are forced as a
        // result of parsing command line options. These are not necessarily
        // what rustc was invoked with, but massaged a bit to agree with
        // commands like `--emit llvm-ir` which they're often incompatible with
        // if we otherwise use the defaults of rustc.
        cli_forced_codegen_units: Option<usize> [UNTRACKED],
        cli_forced_thinlto_off: bool [UNTRACKED],

        // Remap source path prefixes in all output (messages, object files, debug, etc)
        remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],

        edition: Edition [TRACKED],
    }
);

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PrintRequest {
    FileNames,
    Sysroot,
    CrateName,
    Cfg,
    TargetList,
    TargetCPUs,
    TargetFeatures,
    RelocationModels,
    CodeModels,
    TlsModels,
    TargetSpec,
    NativeStaticLibs,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BorrowckMode {
    Ast,
    Mir,
    Compare,
}

impl BorrowckMode {
    /// Should we emit the AST-based borrow checker errors?
    pub fn use_ast(self) -> bool {
        match self {
            BorrowckMode::Ast => true,
            BorrowckMode::Compare => true,
            BorrowckMode::Mir => false,
        }
    }
    /// Should we emit the MIR-based borrow checker errors?
    pub fn use_mir(self) -> bool {
        match self {
            BorrowckMode::Ast => false,
            BorrowckMode::Compare => true,
            BorrowckMode::Mir => true,
        }
    }
}

pub enum Input {
    /// Load source from file
    File(PathBuf),
    Str {
        /// String that is shown in place of a filename
        name: FileName,
        /// Anonymous source string
        input: String,
    },
}

impl Input {
    pub fn filestem(&self) -> String {
        match *self {
            Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
            Input::Str { .. } => "rust_out".to_string(),
        }
    }
}

#[derive(Clone)]
pub struct OutputFilenames {
    pub out_directory: PathBuf,
    pub out_filestem: String,
    pub single_output_file: Option<PathBuf>,
    pub extra: String,
    pub outputs: OutputTypes,
}

impl_stable_hash_for!(struct self::OutputFilenames {
    out_directory,
    out_filestem,
    single_output_file,
    extra,
    outputs
});

pub const RUST_CGU_EXT: &str = "rcgu";

impl OutputFilenames {
    pub fn path(&self, flavor: OutputType) -> PathBuf {
        self.outputs
            .get(&flavor)
            .and_then(|p| p.to_owned())
            .or_else(|| self.single_output_file.clone())
            .unwrap_or_else(|| self.temp_path(flavor, None))
    }

    /// Get the path where a compilation artifact of the given type for the
    /// given codegen unit should be placed on disk. If codegen_unit_name is
    /// None, a path distinct from those of any codegen unit will be generated.
    pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
        let extension = flavor.extension();
        self.temp_path_ext(extension, codegen_unit_name)
    }

    /// Like temp_path, but also supports things where there is no corresponding
    /// OutputType, like no-opt-bitcode or lto-bitcode.
    pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
        let base = self.out_directory.join(&self.filestem());

        let mut extension = String::new();

        if let Some(codegen_unit_name) = codegen_unit_name {
            extension.push_str(codegen_unit_name);
        }

        if !ext.is_empty() {
            if !extension.is_empty() {
                extension.push_str(".");
                extension.push_str(RUST_CGU_EXT);
                extension.push_str(".");
            }

            extension.push_str(ext);
        }

        let path = base.with_extension(&extension[..]);
        path
    }

    pub fn with_extension(&self, extension: &str) -> PathBuf {
        self.out_directory
            .join(&self.filestem())
            .with_extension(extension)
    }

    pub fn filestem(&self) -> String {
        format!("{}{}", self.out_filestem, self.extra)
    }
}

pub fn host_triple() -> &'static str {
    // Get the host triple out of the build environment. This ensures that our
    // idea of the host triple is the same as for the set of libraries we've
    // actually built.  We can't just take LLVM's host triple because they
    // normalize all ix86 architectures to i386.
    //
    // Instead of grabbing the host triple (for the current host), we grab (at
    // compile time) the target triple that this rustc is built with and
    // calling that (at runtime) the host triple.
    (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
}

/// Some reasonable defaults
pub fn basic_options() -> Options {
    Options {
        crate_types: Vec::new(),
        optimize: OptLevel::No,
        debuginfo: NoDebugInfo,
        lint_opts: Vec::new(),
        lint_cap: None,
        describe_lints: false,
        output_types: OutputTypes(BTreeMap::new()),
        search_paths: SearchPaths::new(),
        maybe_sysroot: None,
        target_triple: TargetTriple::from_triple(host_triple()),
        test: false,
        incremental: None,
        debugging_opts: basic_debugging_options(),
        prints: Vec::new(),
        borrowck_mode: BorrowckMode::Ast,
        cg: basic_codegen_options(),
        error_format: ErrorOutputType::default(),
        externs: Externs(BTreeMap::new()),
        crate_name: None,
        alt_std_name: None,
        libs: Vec::new(),
        unstable_features: UnstableFeatures::Disallow,
        debug_assertions: true,
        actually_rustdoc: false,
        cli_forced_codegen_units: None,
        cli_forced_thinlto_off: false,
        remap_path_prefix: Vec::new(),
        edition: DEFAULT_EDITION,
    }
}

impl Options {
    /// True if there is a reason to build the dep graph.
    pub fn build_dep_graph(&self) -> bool {
        self.incremental.is_some() || self.debugging_opts.dump_dep_graph
            || self.debugging_opts.query_dep_graph
    }

    #[inline(always)]
    pub fn enable_dep_node_debug_strs(&self) -> bool {
        cfg!(debug_assertions)
            && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
    }

    pub fn file_path_mapping(&self) -> FilePathMapping {
        FilePathMapping::new(self.remap_path_prefix.clone())
    }

    /// True if there will be an output file generated
    pub fn will_create_output_file(&self) -> bool {
        !self.debugging_opts.parse_only && // The file is just being parsed
            !self.debugging_opts.ls // The file is just being queried
    }
}

// The type of entry function, so
// users can have their own entry
// functions
#[derive(Copy, Clone, PartialEq)]
pub enum EntryFnType {
    EntryMain,
    EntryStart,
}

#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
pub enum CrateType {
    CrateTypeExecutable,
    CrateTypeDylib,
    CrateTypeRlib,
    CrateTypeStaticlib,
    CrateTypeCdylib,
    CrateTypeProcMacro,
}

#[derive(Clone, Hash)]
pub enum Passes {
    SomePasses(Vec<String>),
    AllPasses,
}

impl Passes {
    pub fn is_empty(&self) -> bool {
        match *self {
            SomePasses(ref v) => v.is_empty(),
            AllPasses => false,
        }
    }
}

/// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
/// at once. The goal of this macro is to define an interface that can be
/// programmatically used by the option parser in order to initialize the struct
/// without hardcoding field names all over the place.
///
/// The goal is to invoke this macro once with the correct fields, and then this
/// macro generates all necessary code. The main gotcha of this macro is the
/// cgsetters module which is a bunch of generated code to parse an option into
/// its respective field in the struct. There are a few hand-written parsers for
/// parsing specific types of values in this module.
macro_rules! options {
    ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
     $buildfn:ident, $prefix:expr, $outputname:expr,
     $stat:ident, $mod_desc:ident, $mod_set:ident,
     $($opt:ident : $t:ty = (
        $init:expr,
        $parse:ident,
        [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
        $desc:expr)
     ),* ,) =>
(
    #[derive(Clone)]
    pub struct $struct_name { $(pub $opt: $t),* }

    pub fn $defaultfn() -> $struct_name {
        $struct_name { $($opt: $init),* }
    }

    pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
    {
        let mut op = $defaultfn();
        for option in matches.opt_strs($prefix) {
            let mut iter = option.splitn(2, '=');
            let key = iter.next().unwrap();
            let value = iter.next();
            let option_to_lookup = key.replace("-", "_");
            let mut found = false;
            for &(candidate, setter, opt_type_desc, _) in $stat {
                if option_to_lookup != candidate { continue }
                if !setter(&mut op, value) {
                    match (value, opt_type_desc) {
                        (Some(..), None) => {
                            early_error(error_format, &format!("{} option `{}` takes no \
                                                              value", $outputname, key))
                        }
                        (None, Some(type_desc)) => {
                            early_error(error_format, &format!("{0} option `{1}` requires \
                                                              {2} ({3} {1}=<value>)",
                                                             $outputname, key,
                                                             type_desc, $prefix))
                        }
                        (Some(value), Some(type_desc)) => {
                            early_error(error_format, &format!("incorrect value `{}` for {} \
                                                              option `{}` - {} was expected",
                                                             value, $outputname,
                                                             key, type_desc))
                        }
                        (None, None) => bug!()
                    }
                }
                found = true;
                break;
            }
            if !found {
                early_error(error_format, &format!("unknown {} option: `{}`",
                                                 $outputname, key));
            }
        }
        return op;
    }

    impl<'a> dep_tracking::DepTrackingHash for $struct_name {

        fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
            let mut sub_hashes = BTreeMap::new();
            $({
                hash_option!($opt,
                             &self.$opt,
                             &mut sub_hashes,
                             [$dep_tracking_marker $($dep_warn_val,
                                                     $dep_warn_text,
                                                     error_format)*]);
            })*
            dep_tracking::stable_hash(sub_hashes, hasher, error_format);
        }
    }

    pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
    pub const $stat: &'static [(&'static str, $setter_name,
                                     Option<&'static str>, &'static str)] =
        &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];

    #[allow(non_upper_case_globals, dead_code)]
    mod $mod_desc {
        pub const parse_bool: Option<&'static str> = None;
        pub const parse_opt_bool: Option<&'static str> =
            Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
        pub const parse_string: Option<&'static str> = Some("a string");
        pub const parse_string_push: Option<&'static str> = Some("a string");
        pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
        pub const parse_opt_string: Option<&'static str> = Some("a string");
        pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
        pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
        pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
        pub const parse_uint: Option<&'static str> = Some("a number");
        pub const parse_passes: Option<&'static str> =
            Some("a space-separated list of passes, or `all`");
        pub const parse_opt_uint: Option<&'static str> =
            Some("a number");
        pub const parse_panic_strategy: Option<&'static str> =
            Some("either `panic` or `abort`");
        pub const parse_relro_level: Option<&'static str> =
            Some("one of: `full`, `partial`, or `off`");
        pub const parse_sanitizer: Option<&'static str> =
            Some("one of: `address`, `leak`, `memory` or `thread`");
        pub const parse_linker_flavor: Option<&'static str> =
            Some(::rustc_target::spec::LinkerFlavor::one_of());
        pub const parse_optimization_fuel: Option<&'static str> =
            Some("crate=integer");
        pub const parse_unpretty: Option<&'static str> =
            Some("`string` or `string=string`");
        pub const parse_lto: Option<&'static str> =
            Some("one of `thin`, `fat`, or omitted");
        pub const parse_cross_lang_lto: Option<&'static str> =
            Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `no-link`, \
                  or the path to the linker plugin");
    }

    #[allow(dead_code)]
    mod $mod_set {
        use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer, Lto,
                    CrossLangLto};
        use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
        use std::path::PathBuf;

        $(
            pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
                $parse(&mut cg.$opt, v)
            }
        )*

        fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
            match v {
                Some(..) => false,
                None => { *slot = true; true }
            }
        }

        fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
            match v {
                Some(s) => {
                    match s {
                        "n" | "no" | "off" => {
                            *slot = Some(false);
                        }
                        "y" | "yes" | "on" => {
                            *slot = Some(true);
                        }
                        _ => { return false; }
                    }

                    true
                },
                None => { *slot = Some(true); true }
            }
        }

        fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = Some(s.to_string()); true },
                None => false,
            }
        }

        fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = Some(PathBuf::from(s)); true },
                None => false,
            }
        }

        fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = s.to_string(); true },
                None => false,
            }
        }

        fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { slot.push(s.to_string()); true },
                None => false,
            }
        }

        fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { slot.push(PathBuf::from(s)); true },
                None => false,
            }
        }

        fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
                      -> bool {
            match v {
                Some(s) => {
                    for s in s.split_whitespace() {
                        slot.push(s.to_string());
                    }
                    true
                },
                None => false,
            }
        }

        fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
                      -> bool {
            match v {
                Some(s) => {
                    let v = s.split_whitespace().map(|s| s.to_string()).collect();
                    *slot = Some(v);
                    true
                },
                None => false,
            }
        }

        fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
            match v.and_then(|s| s.parse().ok()) {
                Some(i) => { *slot = i; true },
                None => false
            }
        }

        fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
            match v {
                Some(s) => { *slot = s.parse().ok(); slot.is_some() }
                None => { *slot = None; false }
            }
        }

        fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
            match v {
                Some("all") => {
                    *slot = AllPasses;
                    true
                }
                v => {
                    let mut passes = vec![];
                    if parse_list(&mut passes, v) {
                        *slot = SomePasses(passes);
                        true
                    } else {
                        false
                    }
                }
            }
        }

        fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
            match v {
                Some("unwind") => *slot = Some(PanicStrategy::Unwind),
                Some("abort") => *slot = Some(PanicStrategy::Abort),
                _ => return false
            }
            true
        }

        fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
            match v {
                Some(s) => {
                    match s.parse::<RelroLevel>() {
                        Ok(level) => *slot = Some(level),
                        _ => return false
                    }
                },
                _ => return false
            }
            true
        }

        fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
            match v {
                Some("address") => *slote = Some(Sanitizer::Address),
                Some("leak") => *slote = Some(Sanitizer::Leak),
                Some("memory") => *slote = Some(Sanitizer::Memory),
                Some("thread") => *slote = Some(Sanitizer::Thread),
                _ => return false,
            }
            true
        }

        fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
            match v.and_then(LinkerFlavor::from_str) {
                Some(lf) => *slote = Some(lf),
                _ => return false,
            }
            true
        }

        fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
            match v {
                None => false,
                Some(s) => {
                    let parts = s.split('=').collect::<Vec<_>>();
                    if parts.len() != 2 { return false; }
                    let crate_name = parts[0].to_string();
                    let fuel = parts[1].parse::<u64>();
                    if fuel.is_err() { return false; }
                    *slot = Some((crate_name, fuel.unwrap()));
                    true
                }
            }
        }

        fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
            match v {
                None => false,
                Some(s) if s.split('=').count() <= 2 => {
                    *slot = Some(s.to_string());
                    true
                }
                _ => false,
            }
        }

        fn parse_lto(slot: &mut Lto, v: Option<&str>) -> bool {
            *slot = match v {
                None => Lto::Yes,
                Some("thin") => Lto::Thin,
                Some("fat") => Lto::Fat,
                Some(_) => return false,
            };
            true
        }

        fn parse_cross_lang_lto(slot: &mut CrossLangLto, v: Option<&str>) -> bool {
            if v.is_some() {
                let mut bool_arg = None;
                if parse_opt_bool(&mut bool_arg, v) {
                    *slot = if bool_arg.unwrap() {
                        CrossLangLto::NoLink
                    } else {
                        CrossLangLto::Disabled
                    };
                    return true
                }
            }

            *slot = match v {
                None |
                Some("no-link") => CrossLangLto::NoLink,
                Some(path) => CrossLangLto::LinkerPlugin(PathBuf::from(path)),
            };
            true
        }
    }
) }

options! {CodegenOptions, CodegenSetter, basic_codegen_options,
         build_codegen_options, "C", "codegen",
         CG_OPTIONS, cg_type_desc, cgsetters,
    ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
        "this option is deprecated and does nothing"),
    linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
        "system linker to link outputs with"),
    link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
        "a single extra argument to append to the linker invocation (can be used several times)"),
    link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
        "extra arguments to append to the linker invocation (space separated)"),
    link_dead_code: bool = (false, parse_bool, [UNTRACKED],
        "don't let linker strip dead code (turning it on can be used for code coverage)"),
    lto: Lto = (Lto::No, parse_lto, [TRACKED],
        "perform LLVM link-time optimizations"),
    target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
        "select target processor (rustc --print target-cpus for details)"),
    target_feature: String = ("".to_string(), parse_string, [TRACKED],
        "target specific attributes (rustc --print target-features for details)"),
    passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
        "a list of extra LLVM passes to run (space separated)"),
    llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
        "a list of arguments to pass to llvm (space separated)"),
    save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
        "`-C save-temps` might not produce all requested temporary products \
         when incremental compilation is enabled.")],
        "save all temporary output files during compilation"),
    rpath: bool = (false, parse_bool, [UNTRACKED],
        "set rpath values in libs/exes"),
    overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "use overflow checks for integer arithmetic"),
    no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
        "don't pre-populate the pass manager with a list of passes"),
    no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
        "don't run the loop vectorization optimization passes"),
    no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
        "don't run LLVM's SLP vectorization pass"),
    soft_float: bool = (false, parse_bool, [TRACKED],
        "use soft float ABI (*eabihf targets only)"),
    prefer_dynamic: bool = (false, parse_bool, [TRACKED],
        "prefer dynamic linking to static linking"),
    no_integrated_as: bool = (false, parse_bool, [TRACKED],
        "use an external assembler rather than LLVM's integrated one"),
    no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "disable the use of the redzone"),
    relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
         "choose the relocation model to use (rustc --print relocation-models for details)"),
    code_model: Option<String> = (None, parse_opt_string, [TRACKED],
         "choose the code model to use (rustc --print code-models for details)"),
    metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
         "metadata to mangle symbol names with"),
    extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
         "extra data to put in each output filename"),
    codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
        "divide crate into N units to optimize in parallel"),
    remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
        "print remarks for these optimization passes (space separated, or \"all\")"),
    no_stack_check: bool = (false, parse_bool, [UNTRACKED],
        "the --no-stack-check flag is deprecated and does nothing"),
    debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
        "debug info emission level, 0 = no debug info, 1 = line tables only, \
         2 = full debug info with variable and type information"),
    opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
        "optimize with possible levels 0-3, s, or z"),
    force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "force use of the frame pointers"),
    debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "explicitly enable the cfg(debug_assertions) directive"),
    inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
        "set the threshold for inlining a function (default: 225)"),
    panic: Option<PanicStrategy> = (None, parse_panic_strategy,
        [TRACKED], "panic strategy to compile crate with"),
    incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
          "enable incremental compilation"),
}

options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
         build_debugging_options, "Z", "debugging",
         DB_OPTIONS, db_type_desc, dbsetters,
    codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
        "the backend to use"),
    verbose: bool = (false, parse_bool, [UNTRACKED],
        "in general, enable more debug printouts"),
    span_free_formats: bool = (false, parse_bool, [UNTRACKED],
        "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
    identify_regions: bool = (false, parse_bool, [UNTRACKED],
        "make unnamed regions display as '# (where # is some non-ident unique id)"),
    emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
        "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
    borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
        "select which borrowck is used (`ast`, `mir`, or `compare`)"),
    two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
        "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
    two_phase_beyond_autoref: bool = (false, parse_bool, [UNTRACKED],
        "when using two-phase-borrows, allow two phases even for non-autoref `&mut` borrows"),
    time_passes: bool = (false, parse_bool, [UNTRACKED],
        "measure time of each rustc pass"),
    count_llvm_insns: bool = (false, parse_bool,
        [UNTRACKED_WITH_WARNING(true,
        "The output generated by `-Z count_llvm_insns` might not be reliable \
         when used with incremental compilation")],
        "count where LLVM instrs originate"),
    time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
        "The output of `-Z time-llvm-passes` will only reflect timings of \
         re-codegened modules when used with incremental compilation" )],
        "measure time of each LLVM pass"),
    input_stats: bool = (false, parse_bool, [UNTRACKED],
        "gather statistics about the input"),
    codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
        "The output of `-Z codegen-stats` might not be accurate when incremental \
         compilation is enabled")],
        "gather codegen statistics"),
    asm_comments: bool = (false, parse_bool, [TRACKED],
        "generate comments into the assembly (may change behavior)"),
    no_verify: bool = (false, parse_bool, [TRACKED],
        "skip LLVM verification"),
    borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
        "gather borrowck statistics"),
    no_landing_pads: bool = (false, parse_bool, [TRACKED],
        "omit landing pads for unwinding"),
    fewer_names: bool = (false, parse_bool, [TRACKED],
        "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
    meta_stats: bool = (false, parse_bool, [UNTRACKED],
        "gather metadata statistics"),
    print_link_args: bool = (false, parse_bool, [UNTRACKED],
        "print the arguments passed to the linker"),
    print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
        "prints the llvm optimization passes being run"),
    ast_json: bool = (false, parse_bool, [UNTRACKED],
        "print the AST as JSON and halt"),
    query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
        "execute queries on a thread pool with N threads"),
    ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
        "print the pre-expansion AST as JSON and halt"),
    ls: bool = (false, parse_bool, [UNTRACKED],
        "list the symbols defined by a library crate"),
    save_analysis: bool = (false, parse_bool, [UNTRACKED],
        "write syntax and type analysis (in JSON format) information, in \
         addition to normal output"),
    flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
        "include loan analysis data in -Z unpretty flowgraph output"),
    flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
        "include move analysis data in -Z unpretty flowgraph output"),
    flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
        "include assignment analysis data in -Z unpretty flowgraph output"),
    flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
        "include all dataflow analysis data in -Z unpretty flowgraph output"),
    print_region_graph: bool = (false, parse_bool, [UNTRACKED],
         "prints region inference graph. \
          Use with RUST_REGION_GRAPH=help for more info"),
    parse_only: bool = (false, parse_bool, [UNTRACKED],
          "parse only; do not compile, assemble, or link"),
    no_codegen: bool = (false, parse_bool, [TRACKED],
          "run all passes except codegen; no output"),
    treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
          "treat all errors that occur as bugs"),
    external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
          "show macro backtraces even for non-local macros"),
    teach: bool = (false, parse_bool, [TRACKED],
          "show extended diagnostic help"),
    continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
          "attempt to recover from parse errors (experimental)"),
    incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
          "enable incremental compilation (experimental)"),
    incremental_queries: bool = (true, parse_bool, [UNTRACKED],
          "enable incremental compilation support for queries (experimental)"),
    incremental_info: bool = (false, parse_bool, [UNTRACKED],
        "print high-level information about incremental reuse (or the lack thereof)"),
    incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
        "dump hash information in textual format to stdout"),
    incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
        "verify incr. comp. hashes of green query instances"),
    incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
        "ignore spans during ICH computation -- used for testing"),
    dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
          "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
    query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
          "enable queries of the dependency graph for regression testing"),
    profile_queries: bool = (false, parse_bool, [UNTRACKED],
          "trace and profile the queries of the incremental compilation framework"),
    profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
          "trace and profile the queries and keys of the incremental compilation framework"),
    no_analysis: bool = (false, parse_bool, [UNTRACKED],
          "parse and expand the source, but run no analysis"),
    extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
        "load extra plugins"),
    unstable_options: bool = (false, parse_bool, [UNTRACKED],
          "adds unstable command line options to rustc interface"),
    force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
          "force overflow checks on or off"),
    trace_macros: bool = (false, parse_bool, [UNTRACKED],
          "for every macro invocation, print its name and arguments"),
    debug_macros: bool = (false, parse_bool, [TRACKED],
          "emit line numbers debug info inside macros"),
    enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
          "force nonzeroing move optimization on"),
    keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
          "don't clear the hygiene data after analysis"),
    keep_ast: bool = (false, parse_bool, [UNTRACKED],
          "keep the AST after lowering it to HIR"),
    show_span: Option<String> = (None, parse_opt_string, [TRACKED],
          "show spans for compiler debugging (expr|pat|ty)"),
    print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
          "print layout information for each type encountered"),
    print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
          "print the result of the monomorphization collection pass"),
    mir_opt_level: usize = (1, parse_uint, [TRACKED],
          "set the MIR optimization level (0-3, default: 1)"),
    mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
          "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
    arg_align_attributes: bool = (false, parse_bool, [TRACKED],
          "emit align metadata for reference arguments"),
    dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
          "dump MIR state at various points in transforms"),
    dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
          "the directory the MIR is dumped into"),
    dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
          "in addition to `.mir` files, create graphviz `.dot` files"),
    dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
          "if set, exclude the pass number when dumping MIR (used in tests)"),
    mir_emit_validate: usize = (0, parse_uint, [TRACKED],
          "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
           contains unsafe block, only validate arguments; 2: always emit full validation)"),
    perf_stats: bool = (false, parse_bool, [UNTRACKED],
          "print some performance-related statistics"),
    hir_stats: bool = (false, parse_bool, [UNTRACKED],
          "print some statistics about AST and HIR"),
    mir_stats: bool = (false, parse_bool, [UNTRACKED],
          "print some statistics about MIR"),
    always_encode_mir: bool = (false, parse_bool, [TRACKED],
          "encode MIR of all functions into the crate metadata"),
    osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
          "pass `-install_name @rpath/...` to the macOS linker"),
    sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
                                   "Use a sanitizer"),
    linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
                                           "Linker flavor"),
    fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
        "set the optimization fuel quota for a crate"),
    print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
        "make Rustc print the total optimization fuel used by a crate"),
    force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
        "force all crates to be `rustc_private` unstable"),
    pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
        "a single extra argument to prepend the linker invocation (can be used several times)"),
    pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
        "extra arguments to prepend to the linker invocation (space separated)"),
    profile: bool = (false, parse_bool, [TRACKED],
                     "insert profiling code"),
    pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
        "Generate PGO profile data, to a given file, or to the default \
         location if it's empty."),
    pgo_use: String = (String::new(), parse_string, [TRACKED],
        "Use PGO profile data from the given profile file."),
    disable_instrumentation_preinliner: bool =
        (false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \
        useful for profiling / PGO."),
    relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
        "choose which RELRO level to use"),
    nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED],
        "when tracking region error causes, accept subminimal results for faster execution."),
    nll_facts: bool = (false, parse_bool, [UNTRACKED],
                       "dump facts from NLL analysis into side files"),
    disable_nll_user_type_assert: bool = (false, parse_bool, [UNTRACKED],
        "disable user provided type assertion in NLL"),
    polonius: bool = (false, parse_bool, [UNTRACKED],
        "enable polonius-based borrow-checker"),
    codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
        "generate a graphical HTML report of time spent in codegen and LLVM"),
    thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "enable ThinLTO when possible"),
    inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "control whether #[inline] functions are in all cgus"),
    tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
         "choose the TLS model to use (rustc --print tls-models for details)"),
    saturating_float_casts: bool = (false, parse_bool, [TRACKED],
        "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
         the max/min integer respectively, and NaN is mapped to 0"),
    lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "rewrite operators on i128 and u128 into lang item calls (typically provided \
         by compiler-builtins) so codegen doesn't need to support them,
         overriding the default for the current target"),
    human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
        "generate human-readable, predictable names for codegen units"),
    dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
        "in dep-info output, omit targets for tracking dependencies of the dep-info files \
         themselves"),
    unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
        "Present the input source, unstable (and less-pretty) variants;
        valid types are any of the types for `--pretty`, as well as:
        `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
        `everybody_loops` (all function bodies replaced with `loop {}`),
        `hir` (the HIR), `hir,identified`, or
        `hir,typed` (HIR with types for each node)."),
    run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
          "run `dsymutil` and delete intermediate object files"),
    ui_testing: bool = (false, parse_bool, [UNTRACKED],
          "format compiler diagnostics in a way that's better suitable for UI testing"),
    embed_bitcode: bool = (false, parse_bool, [TRACKED],
          "embed LLVM bitcode in object files"),
    strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
        "tell the linker to strip debuginfo when building without debuginfo enabled."),
    share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
          "make the current crate share its generic instantiations"),
    chalk: bool = (false, parse_bool, [TRACKED],
          "enable the experimental Chalk-based trait solving engine"),
    cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED],
          "generate build artifacts that are compatible with linker-based LTO."),
    no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
          "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
}

pub fn default_lib_output() -> CrateType {
    CrateTypeRlib
}

pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
    let end = &sess.target.target.target_endian;
    let arch = &sess.target.target.arch;
    let wordsz = &sess.target.target.target_pointer_width;
    let os = &sess.target.target.target_os;
    let env = &sess.target.target.target_env;
    let vendor = &sess.target.target.target_vendor;
    let min_atomic_width = sess.target.target.min_atomic_width();
    let max_atomic_width = sess.target.target.max_atomic_width();

    let mut ret = HashSet::new();
    // Target bindings.
    ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
    if let Some(ref fam) = sess.target.target.options.target_family {
        ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
        if fam == "windows" || fam == "unix" {
            ret.insert((Symbol::intern(fam), None));
        }
    }
    ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
    ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
    ret.insert((
        Symbol::intern("target_pointer_width"),
        Some(Symbol::intern(wordsz)),
    ));
    ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
    ret.insert((
        Symbol::intern("target_vendor"),
        Some(Symbol::intern(vendor)),
    ));
    if sess.target.target.options.has_elf_tls {
        ret.insert((Symbol::intern("target_thread_local"), None));
    }
    for &i in &[8, 16, 32, 64, 128] {
        if i >= min_atomic_width && i <= max_atomic_width {
            let s = i.to_string();
            ret.insert((
                Symbol::intern("target_has_atomic"),
                Some(Symbol::intern(&s)),
            ));
            if &s == wordsz {
                ret.insert((
                    Symbol::intern("target_has_atomic"),
                    Some(Symbol::intern("ptr")),
                ));
            }
        }
    }
    if sess.opts.debug_assertions {
        ret.insert((Symbol::intern("debug_assertions"), None));
    }
    if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
        ret.insert((Symbol::intern("proc_macro"), None));
    }
    return ret;
}

pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
    // Combine the configuration requested by the session (command line) with
    // some default and generated configuration items
    let default_cfg = default_configuration(sess);
    // If the user wants a test runner, then add the test cfg
    if sess.opts.test {
        user_cfg.insert((Symbol::intern("test"), None));
    }
    user_cfg.extend(default_cfg.iter().cloned());
    user_cfg
}

pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
    let target = match Target::search(&opts.target_triple) {
        Ok(t) => t,
        Err(e) => {
            sp.struct_fatal(&format!("Error loading target specification: {}", e))
                .help("Use `--print target-list` for a list of built-in targets")
                .emit();
            FatalError.raise();
        }
    };

    let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
        "16" => (ast::IntTy::I16, ast::UintTy::U16),
        "32" => (ast::IntTy::I32, ast::UintTy::U32),
        "64" => (ast::IntTy::I64, ast::UintTy::U64),
        w => sp.fatal(&format!(
            "target specification was invalid: \
             unrecognized target-pointer-width {}",
            w
        )).raise(),
    };

    Config {
        target,
        isize_ty,
        usize_ty,
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum OptionStability {
    Stable,

    Unstable,
}

pub struct RustcOptGroup {
    pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
    pub name: &'static str,
    pub stability: OptionStability,
}

impl RustcOptGroup {
    pub fn is_stable(&self) -> bool {
        self.stability == OptionStability::Stable
    }

    pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
    where
        F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
    {
        RustcOptGroup {
            name,
            apply: Box::new(f),
            stability: OptionStability::Stable,
        }
    }

    pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
    where
        F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
    {
        RustcOptGroup {
            name,
            apply: Box::new(f),
            stability: OptionStability::Unstable,
        }
    }
}

// The `opt` local module holds wrappers around the `getopts` API that
// adds extra rustc-specific metadata to each option; such metadata
// is exposed by .  The public
// functions below ending with `_u` are the functions that return
// *unstable* options, i.e. options that are only enabled when the
// user also passes the `-Z unstable-options` debugging flag.
mod opt {
    // The `fn opt_u` etc below are written so that we can use them
    // in the future; do not warn about them not being used right now.
    #![allow(dead_code)]

    use getopts;
    use super::RustcOptGroup;

    pub type R = RustcOptGroup;
    pub type S = &'static str;

    fn stable<F>(name: S, f: F) -> R
    where
        F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
    {
        RustcOptGroup::stable(name, f)
    }

    fn unstable<F>(name: S, f: F) -> R
    where
        F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
    {
        RustcOptGroup::unstable(name, f)
    }

    fn longer(a: S, b: S) -> S {
        if a.len() > b.len() {
            a
        } else {
            b
        }
    }

    pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
        stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
    }
    pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
        stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
    }
    pub fn flag_s(a: S, b: S, c: S) -> R {
        stable(longer(a, b), move |opts| opts.optflag(a, b, c))
    }
    pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
        stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
    }
    pub fn flagmulti_s(a: S, b: S, c: S) -> R {
        stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
    }

    pub fn opt(a: S, b: S, c: S, d: S) -> R {
        unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
    }
    pub fn multi(a: S, b: S, c: S, d: S) -> R {
        unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
    }
    pub fn flag(a: S, b: S, c: S) -> R {
        unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
    }
    pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
        unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
    }
    pub fn flagmulti(a: S, b: S, c: S) -> R {
        unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
    }
}

/// Returns the "short" subset of the rustc command line options,
/// including metadata for each option, such as whether the option is
/// part of the stable long-term interface for rustc.
pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
    vec![
        opt::flag_s("h", "help", "Display this message"),
        opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
        opt::multi_s(
            "L",
            "",
            "Add a directory to the library search path. The
                             optional KIND can be one of dependency, crate, native,
                             framework or all (the default).",
            "[KIND=]PATH",
        ),
        opt::multi_s(
            "l",
            "",
            "Link the generated crate(s) to the specified native
                             library NAME. The optional KIND can be one of
                             static, dylib, or framework. If omitted, dylib is
                             assumed.",
            "[KIND=]NAME",
        ),
        opt::multi_s(
            "",
            "crate-type",
            "Comma separated list of types of crates
                                    for the compiler to emit",
            "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
        ),
        opt::opt_s(
            "",
            "crate-name",
            "Specify the name of the crate being built",
            "NAME",
        ),
        opt::multi_s(
            "",
            "emit",
            "Comma separated list of types of output for \
             the compiler to emit",
            "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
        ),
        opt::multi_s(
            "",
            "print",
            "Comma separated list of compiler information to \
             print on stdout",
            "[crate-name|file-names|sysroot|cfg|target-list|\
             target-cpus|target-features|relocation-models|\
             code-models|tls-models|target-spec-json|native-static-libs]",
        ),
        opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
        opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
        opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
        opt::opt_s(
            "",
            "out-dir",
            "Write output to compiler-chosen filename \
             in <dir>",
            "DIR",
        ),
        opt::opt_s(
            "",
            "explain",
            "Provide a detailed explanation of an error \
             message",
            "OPT",
        ),
        opt::flag_s("", "test", "Build a test harness"),
        opt::opt_s(
            "",
            "target",
            "Target triple for which the code is compiled",
            "TARGET",
        ),
        opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
        opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
        opt::multi_s("D", "deny", "Set lint denied", "OPT"),
        opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
        opt::multi_s(
            "",
            "cap-lints",
            "Set the most restrictive lint level. \
             More restrictive lints are capped at this \
             level",
            "LEVEL",
        ),
        opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
        opt::flag_s("V", "version", "Print version info and exit"),
        opt::flag_s("v", "verbose", "Use verbose output"),
    ]
}

/// Returns all rustc command line options, including metadata for
/// each option, such as whether the option is part of the stable
/// long-term interface for rustc.
pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
    let mut opts = rustc_short_optgroups();
    opts.extend(vec![
        opt::multi_s(
            "",
            "extern",
            "Specify where an external rust library is located",
            "NAME=PATH",
        ),
        opt::opt_s("", "sysroot", "Override the system root", "PATH"),
        opt::multi("Z", "", "Set internal debugging options", "FLAG"),
        opt::opt_s(
            "",
            "error-format",
            "How errors and other messages are produced",
            "human|json|short",
        ),
        opt::opt_s(
            "",
            "color",
            "Configure coloring of output:
                                 auto   = colorize, if output goes to a tty (default);
                                 always = always colorize output;
                                 never  = never colorize output",
            "auto|always|never",
        ),
        opt::opt(
            "",
            "pretty",
            "Pretty-print the input instead of compiling;
                  valid types are: `normal` (un-annotated source),
                  `expanded` (crates expanded), or
                  `expanded,identified` (fully parenthesized, AST nodes with IDs).",
            "TYPE",
        ),
        opt::opt_s(
            "",
            "edition",
            "Specify which edition of the compiler to use when compiling code.",
            EDITION_NAME_LIST,
        ),
        opt::multi_s(
            "",
            "remap-path-prefix",
            "Remap source names in all output (compiler messages and output files)",
            "FROM=TO",
        ),
    ]);
    opts
}

// Convert strings provided as --cfg [cfgspec] into a crate_cfg
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
    cfgspecs
        .into_iter()
        .map(|s| {
            let sess = parse::ParseSess::new(FilePathMapping::empty());
            let mut parser =
                parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());

            let meta_item = panictry!(parser.parse_meta_item());

            if parser.token != token::Eof {
                early_error(
                    ErrorOutputType::default(),
                    &format!("invalid --cfg argument: {}", s),
                )
            } else if meta_item.is_meta_item_list() {
                let msg = format!(
                    "invalid predicate in --cfg command line argument: `{}`",
                    meta_item.ident
                );
                early_error(ErrorOutputType::default(), &msg)
            }

            (meta_item.name(), meta_item.value_str())
        })
        .collect::<ast::CrateConfig>()
}

pub fn build_session_options_and_crate_config(
    matches: &getopts::Matches,
) -> (Options, ast::CrateConfig) {
    let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
        Some("auto") => ColorConfig::Auto,
        Some("always") => ColorConfig::Always,
        Some("never") => ColorConfig::Never,

        None => ColorConfig::Auto,

        Some(arg) => early_error(
            ErrorOutputType::default(),
            &format!(
                "argument for --color must be auto, \
                 always or never (instead was `{}`)",
                arg
            ),
        ),
    };

    let edition = match matches.opt_str("edition") {
        Some(arg) => match Edition::from_str(&arg){
            Ok(edition) => edition,
            Err(_) => early_error(
                ErrorOutputType::default(),
                &format!(
                    "argument for --edition must be one of: \
                    {}. (instead was `{}`)",
                    EDITION_NAME_LIST,
                    arg
                ),
            ),
        }
        None => DEFAULT_EDITION,
    };

    if !edition.is_stable() && !nightly_options::is_nightly_build() {
        early_error(
                ErrorOutputType::default(),
                &format!(
                    "Edition {} is unstable an only\
                    available for nightly builds of rustc.",
                    edition,
                )
        )
    }


    // We need the opts_present check because the driver will send us Matches
    // with only stable options if no unstable options are used. Since error-format
    // is unstable, it will not be present. We have to use opts_present not
    // opt_present because the latter will panic.
    let error_format = if matches.opts_present(&["error-format".to_owned()]) {
        match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
            Some("human") => ErrorOutputType::HumanReadable(color),
            Some("json") => ErrorOutputType::Json(false),
            Some("pretty-json") => ErrorOutputType::Json(true),
            Some("short") => {
                if nightly_options::is_unstable_enabled(matches) {
                    ErrorOutputType::Short(color)
                } else {
                    early_error(
                        ErrorOutputType::default(),
                        &format!(
                            "the `-Z unstable-options` flag must also be passed to \
                             enable the short error message option"
                        ),
                    );
                }
            }
            None => ErrorOutputType::HumanReadable(color),

            Some(arg) => early_error(
                ErrorOutputType::HumanReadable(color),
                &format!(
                    "argument for --error-format must be `human`, `json` or \
                     `short` (instead was `{}`)",
                    arg
                ),
            ),
        }
    } else {
        ErrorOutputType::HumanReadable(color)
    };

    let unparsed_crate_types = matches.opt_strs("crate-type");
    let crate_types = parse_crate_types_from_list(unparsed_crate_types)
        .unwrap_or_else(|e| early_error(error_format, &e[..]));

    let mut lint_opts = vec![];
    let mut describe_lints = false;

    for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
        for lint_name in matches.opt_strs(level.as_str()) {
            if lint_name == "help" {
                describe_lints = true;
            } else {
                lint_opts.push((lint_name.replace("-", "_"), level));
            }
        }
    }

    let lint_cap = matches.opt_str("cap-lints").map(|cap| {
        lint::Level::from_str(&cap)
            .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
    });

    let mut debugging_opts = build_debugging_options(matches, error_format);

    if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
        early_error(
            ErrorOutputType::Json(false),
            "--error-format=pretty-json is unstable",
        );
    }

    if debugging_opts.pgo_gen.is_some() && !debugging_opts.pgo_use.is_empty() {
        early_error(
            error_format,
            "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
        );
    }

    let mut output_types = BTreeMap::new();
    if !debugging_opts.parse_only {
        for list in matches.opt_strs("emit") {
            for output_type in list.split(',') {
                let mut parts = output_type.splitn(2, '=');
                let shorthand = parts.next().unwrap();
                let output_type = match OutputType::from_shorthand(shorthand) {
                    Some(output_type) => output_type,
                    None => early_error(
                        error_format,
                        &format!(
                            "unknown emission type: `{}` - expected one of: {}",
                            shorthand,
                            OutputType::shorthands_display(),
                        ),
                    ),
                };
                let path = parts.next().map(PathBuf::from);
                output_types.insert(output_type, path);
            }
        }
    };
    if output_types.is_empty() {
        output_types.insert(OutputType::Exe, None);
    }

    let mut cg = build_codegen_options(matches, error_format);
    let mut codegen_units = cg.codegen_units;
    let mut disable_thinlto = false;

    // Issue #30063: if user requests llvm-related output to one
    // particular path, disable codegen-units.
    let incompatible: Vec<_> = output_types
        .iter()
        .map(|ot_path| ot_path.0)
        .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
        .map(|ot| ot.shorthand())
        .collect();
    if !incompatible.is_empty() {
        match codegen_units {
            Some(n) if n > 1 => {
                if matches.opt_present("o") {
                    for ot in &incompatible {
                        early_warn(
                            error_format,
                            &format!(
                                "--emit={} with -o incompatible with \
                                 -C codegen-units=N for N > 1",
                                ot
                            ),
                        );
                    }
                    early_warn(error_format, "resetting to default -C codegen-units=1");
                    codegen_units = Some(1);
                    disable_thinlto = true;
                }
            }
            _ => {
                codegen_units = Some(1);
                disable_thinlto = true;
            }
        }
    }

    if debugging_opts.query_threads == Some(0) {
        early_error(
            error_format,
            "Value for query threads must be a positive nonzero integer",
        );
    }

    if debugging_opts.query_threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
        early_error(
            error_format,
            "Optimization fuel is incompatible with multiple query threads",
        );
    }

    if codegen_units == Some(0) {
        early_error(
            error_format,
            "Value for codegen units must be a positive nonzero integer",
        );
    }

    let incremental = match (&debugging_opts.incremental, &cg.incremental) {
        (&Some(ref path1), &Some(ref path2)) => {
            if path1 != path2 {
                early_error(
                    error_format,
                    &format!(
                        "conflicting paths for `-Z incremental` and \
                         `-C incremental` specified: {} versus {}",
                        path1, path2
                    ),
                );
            } else {
                Some(path1)
            }
        }
        (&Some(ref path), &None) => Some(path),
        (&None, &Some(ref path)) => Some(path),
        (&None, &None) => None,
    }.map(|m| PathBuf::from(m));

    if cg.lto != Lto::No && incremental.is_some() {
        early_error(
            error_format,
            "can't perform LTO when compiling incrementally",
        );
    }

    let mut prints = Vec::<PrintRequest>::new();
    if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
        prints.push(PrintRequest::TargetCPUs);
        cg.target_cpu = None;
    };
    if cg.target_feature == "help" {
        prints.push(PrintRequest::TargetFeatures);
        cg.target_feature = "".to_string();
    }
    if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
        prints.push(PrintRequest::RelocationModels);
        cg.relocation_model = None;
    }
    if cg.code_model.as_ref().map_or(false, |s| s == "help") {
        prints.push(PrintRequest::CodeModels);
        cg.code_model = None;
    }
    if debugging_opts
        .tls_model
        .as_ref()
        .map_or(false, |s| s == "help")
    {
        prints.push(PrintRequest::TlsModels);
        debugging_opts.tls_model = None;
    }

    let cg = cg;

    let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
    let target_triple = if let Some(target) = matches.opt_str("target") {
        if target.ends_with(".json") {
            let path = Path::new(&target);
            match TargetTriple::from_path(&path) {
                Ok(triple) => triple,
                Err(_) => {
                    early_error(error_format, &format!("target file {:?} does not exist", path))
                }
            }
        } else {
            TargetTriple::TargetTriple(target)
        }
    } else {
        TargetTriple::from_triple(host_triple())
    };
    let opt_level = {
        if matches.opt_present("O") {
            if cg.opt_level.is_some() {
                early_error(error_format, "-O and -C opt-level both provided");
            }
            OptLevel::Default
        } else {
            match cg.opt_level.as_ref().map(String::as_ref) {
                None => OptLevel::No,
                Some("0") => OptLevel::No,
                Some("1") => OptLevel::Less,
                Some("2") => OptLevel::Default,
                Some("3") => OptLevel::Aggressive,
                Some("s") => OptLevel::Size,
                Some("z") => OptLevel::SizeMin,
                Some(arg) => {
                    early_error(
                        error_format,
                        &format!(
                            "optimization level needs to be \
                             between 0-3 (instead was `{}`)",
                            arg
                        ),
                    );
                }
            }
        }
    };
    let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
    let debuginfo = if matches.opt_present("g") {
        if cg.debuginfo.is_some() {
            early_error(error_format, "-g and -C debuginfo both provided");
        }
        FullDebugInfo
    } else {
        match cg.debuginfo {
            None | Some(0) => NoDebugInfo,
            Some(1) => LimitedDebugInfo,
            Some(2) => FullDebugInfo,
            Some(arg) => {
                early_error(
                    error_format,
                    &format!(
                        "debug info level needs to be between \
                         0-2 (instead was `{}`)",
                        arg
                    ),
                );
            }
        }
    };

    let mut search_paths = SearchPaths::new();
    for s in &matches.opt_strs("L") {
        search_paths.add_path(&s[..], error_format);
    }

    let libs = matches
        .opt_strs("l")
        .into_iter()
        .map(|s| {
            // Parse string of the form "[KIND=]lib[:new_name]",
            // where KIND is one of "dylib", "framework", "static".
            let mut parts = s.splitn(2, '=');
            let kind = parts.next().unwrap();
            let (name, kind) = match (parts.next(), kind) {
                (None, name) => (name, None),
                (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
                (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
                (Some(name), "static") => (name, Some(cstore::NativeStatic)),
                (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
                (_, s) => {
                    early_error(
                        error_format,
                        &format!(
                            "unknown library kind `{}`, expected \
                             one of dylib, framework, or static",
                            s
                        ),
                    );
                }
            };
            if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
                early_error(
                    error_format,
                    &format!(
                        "the library kind 'static-nobundle' is only \
                         accepted on the nightly compiler"
                    ),
                );
            }
            let mut name_parts = name.splitn(2, ':');
            let name = name_parts.next().unwrap();
            let new_name = name_parts.next();
            (name.to_string(), new_name.map(|n| n.to_string()), kind)
        })
        .collect();

    let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
    let test = matches.opt_present("test");

    prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
        "crate-name" => PrintRequest::CrateName,
        "file-names" => PrintRequest::FileNames,
        "sysroot" => PrintRequest::Sysroot,
        "cfg" => PrintRequest::Cfg,
        "target-list" => PrintRequest::TargetList,
        "target-cpus" => PrintRequest::TargetCPUs,
        "target-features" => PrintRequest::TargetFeatures,
        "relocation-models" => PrintRequest::RelocationModels,
        "code-models" => PrintRequest::CodeModels,
        "tls-models" => PrintRequest::TlsModels,
        "native-static-libs" => PrintRequest::NativeStaticLibs,
        "target-spec-json" => {
            if nightly_options::is_unstable_enabled(matches) {
                PrintRequest::TargetSpec
            } else {
                early_error(
                    error_format,
                    &format!(
                        "the `-Z unstable-options` flag must also be passed to \
                         enable the target-spec-json print option"
                    ),
                );
            }
        }
        req => early_error(error_format, &format!("unknown print request `{}`", req)),
    }));

    let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
        None | Some("ast") => BorrowckMode::Ast,
        Some("mir") => BorrowckMode::Mir,
        Some("compare") => BorrowckMode::Compare,
        Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
    };

    if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
        early_warn(
            error_format,
            "-C remark will not show source locations without \
             --debuginfo",
        );
    }

    let mut externs = BTreeMap::new();
    for arg in &matches.opt_strs("extern") {
        let mut parts = arg.splitn(2, '=');
        let name = match parts.next() {
            Some(s) => s,
            None => early_error(error_format, "--extern value must not be empty"),
        };
        let location = match parts.next() {
            Some(s) => s,
            None => early_error(
                error_format,
                "--extern value must be of the format `foo=bar`",
            ),
        };

        externs
            .entry(name.to_string())
            .or_insert_with(BTreeSet::new)
            .insert(location.to_string());
    }

    let crate_name = matches.opt_str("crate-name");

    let remap_path_prefix = matches
        .opt_strs("remap-path-prefix")
        .into_iter()
        .map(|remap| {
            let mut parts = remap.rsplitn(2, '='); // reverse iterator
            let to = parts.next();
            let from = parts.next();
            match (from, to) {
                (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
                _ => early_error(
                    error_format,
                    "--remap-path-prefix must contain '=' between FROM and TO",
                ),
            }
        })
        .collect();

    (
        Options {
            crate_types,
            optimize: opt_level,
            debuginfo,
            lint_opts,
            lint_cap,
            describe_lints,
            output_types: OutputTypes(output_types),
            search_paths,
            maybe_sysroot: sysroot_opt,
            target_triple,
            test,
            incremental,
            debugging_opts,
            prints,
            borrowck_mode,
            cg,
            error_format,
            externs: Externs(externs),
            crate_name,
            alt_std_name: None,
            libs,
            unstable_features: UnstableFeatures::from_environment(),
            debug_assertions,
            actually_rustdoc: false,
            cli_forced_codegen_units: codegen_units,
            cli_forced_thinlto_off: disable_thinlto,
            remap_path_prefix,
            edition,
        },
        cfg,
    )
}

pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
    let mut crate_types: Vec<CrateType> = Vec::new();
    for unparsed_crate_type in &list_list {
        for part in unparsed_crate_type.split(',') {
            let new_part = match part {
                "lib" => default_lib_output(),
                "rlib" => CrateTypeRlib,
                "staticlib" => CrateTypeStaticlib,
                "dylib" => CrateTypeDylib,
                "cdylib" => CrateTypeCdylib,
                "bin" => CrateTypeExecutable,
                "proc-macro" => CrateTypeProcMacro,
                _ => {
                    return Err(format!("unknown crate type: `{}`", part));
                }
            };
            if !crate_types.contains(&new_part) {
                crate_types.push(new_part)
            }
        }
    }

    Ok(crate_types)
}

pub mod nightly_options {
    use getopts;
    use syntax::feature_gate::UnstableFeatures;
    use super::{ErrorOutputType, OptionStability, RustcOptGroup};
    use session::early_error;

    pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
        is_nightly_build()
            && matches
                .opt_strs("Z")
                .iter()
                .any(|x| *x == "unstable-options")
    }

    pub fn is_nightly_build() -> bool {
        UnstableFeatures::from_environment().is_nightly_build()
    }

    pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
        let has_z_unstable_option = matches
            .opt_strs("Z")
            .iter()
            .any(|x| *x == "unstable-options");
        let really_allows_unstable_options =
            UnstableFeatures::from_environment().is_nightly_build();

        for opt in flags.iter() {
            if opt.stability == OptionStability::Stable {
                continue;
            }
            if !matches.opt_present(opt.name) {
                continue;
            }
            if opt.name != "Z" && !has_z_unstable_option {
                early_error(
                    ErrorOutputType::default(),
                    &format!(
                        "the `-Z unstable-options` flag must also be passed to enable \
                         the flag `{}`",
                        opt.name
                    ),
                );
            }
            if really_allows_unstable_options {
                continue;
            }
            match opt.stability {
                OptionStability::Unstable => {
                    let msg = format!(
                        "the option `{}` is only accepted on the \
                         nightly compiler",
                        opt.name
                    );
                    early_error(ErrorOutputType::default(), &msg);
                }
                OptionStability::Stable => {}
            }
        }
    }
}

impl fmt::Display for CrateType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CrateTypeExecutable => "bin".fmt(f),
            CrateTypeDylib => "dylib".fmt(f),
            CrateTypeRlib => "rlib".fmt(f),
            CrateTypeStaticlib => "staticlib".fmt(f),
            CrateTypeCdylib => "cdylib".fmt(f),
            CrateTypeProcMacro => "proc-macro".fmt(f),
        }
    }
}

/// Commandline arguments passed to the compiler have to be incorporated with
/// the dependency tracking system for incremental compilation. This module
/// provides some utilities to make this more convenient.
///
/// The values of all commandline arguments that are relevant for dependency
/// tracking are hashed into a single value that determines whether the
/// incremental compilation cache can be re-used or not. This hashing is done
/// via the DepTrackingHash trait defined below, since the standard Hash
/// implementation might not be suitable (e.g. arguments are stored in a Vec,
/// the hash of which is order dependent, but we might not want the order of
/// arguments to make a difference for the hash).
///
/// However, since the value provided by Hash::hash often *is* suitable,
/// especially for primitive types, there is the
/// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
/// Hash implementation for DepTrackingHash. It's important though that
/// we have an opt-in scheme here, so one is hopefully forced to think about
/// how the hash should be calculated when adding a new commandline argument.
mod dep_tracking {
    use lint;
    use middle::cstore;
    use std::collections::BTreeMap;
    use std::hash::Hash;
    use std::path::PathBuf;
    use std::collections::hash_map::DefaultHasher;
    use super::{CrateType, DebugInfoLevel, ErrorOutputType, Lto, OptLevel, OutputTypes,
                Passes, Sanitizer, CrossLangLto};
    use syntax::feature_gate::UnstableFeatures;
    use rustc_target::spec::{PanicStrategy, RelroLevel, TargetTriple};
    use syntax::edition::Edition;

    pub trait DepTrackingHash {
        fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
    }

    macro_rules! impl_dep_tracking_hash_via_hash {
        ($t:ty) => (
            impl DepTrackingHash for $t {
                fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
                    Hash::hash(self, hasher);
                }
            }
        )
    }

    macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
        ($t:ty) => (
            impl DepTrackingHash for Vec<$t> {
                fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
                    let mut elems: Vec<&$t> = self.iter().collect();
                    elems.sort();
                    Hash::hash(&elems.len(), hasher);
                    for (index, elem) in elems.iter().enumerate() {
                        Hash::hash(&index, hasher);
                        DepTrackingHash::hash(*elem, hasher, error_format);
                    }
                }
            }
        );
    }

    impl_dep_tracking_hash_via_hash!(bool);
    impl_dep_tracking_hash_via_hash!(usize);
    impl_dep_tracking_hash_via_hash!(u64);
    impl_dep_tracking_hash_via_hash!(String);
    impl_dep_tracking_hash_via_hash!(PathBuf);
    impl_dep_tracking_hash_via_hash!(lint::Level);
    impl_dep_tracking_hash_via_hash!(Option<bool>);
    impl_dep_tracking_hash_via_hash!(Option<usize>);
    impl_dep_tracking_hash_via_hash!(Option<String>);
    impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
    impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
    impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
    impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
    impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
    impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
    impl_dep_tracking_hash_via_hash!(CrateType);
    impl_dep_tracking_hash_via_hash!(PanicStrategy);
    impl_dep_tracking_hash_via_hash!(RelroLevel);
    impl_dep_tracking_hash_via_hash!(Passes);
    impl_dep_tracking_hash_via_hash!(OptLevel);
    impl_dep_tracking_hash_via_hash!(Lto);
    impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
    impl_dep_tracking_hash_via_hash!(UnstableFeatures);
    impl_dep_tracking_hash_via_hash!(OutputTypes);
    impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
    impl_dep_tracking_hash_via_hash!(Sanitizer);
    impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
    impl_dep_tracking_hash_via_hash!(TargetTriple);
    impl_dep_tracking_hash_via_hash!(Edition);
    impl_dep_tracking_hash_via_hash!(CrossLangLto);

    impl_dep_tracking_hash_for_sortable_vec_of!(String);
    impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
    impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
    impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
    impl_dep_tracking_hash_for_sortable_vec_of!((
        String,
        Option<String>,
        Option<cstore::NativeLibraryKind>
    ));
    impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));

    impl<T1, T2> DepTrackingHash for (T1, T2)
    where
        T1: DepTrackingHash,
        T2: DepTrackingHash,
    {
        fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
            Hash::hash(&0, hasher);
            DepTrackingHash::hash(&self.0, hasher, error_format);
            Hash::hash(&1, hasher);
            DepTrackingHash::hash(&self.1, hasher, error_format);
        }
    }

    impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
    where
        T1: DepTrackingHash,
        T2: DepTrackingHash,
        T3: DepTrackingHash,
    {
        fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
            Hash::hash(&0, hasher);
            DepTrackingHash::hash(&self.0, hasher, error_format);
            Hash::hash(&1, hasher);
            DepTrackingHash::hash(&self.1, hasher, error_format);
            Hash::hash(&2, hasher);
            DepTrackingHash::hash(&self.2, hasher, error_format);
        }
    }

    // This is a stable hash because BTreeMap is a sorted container
    pub fn stable_hash(
        sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
        hasher: &mut DefaultHasher,
        error_format: ErrorOutputType,
    ) {
        for (key, sub_hash) in sub_hashes {
            // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
            // the keys, as they are just plain strings
            Hash::hash(&key.len(), hasher);
            Hash::hash(key, hasher);
            sub_hash.hash(hasher, error_format);
        }
    }
}

#[cfg(test)]
mod tests {
    use errors;
    use getopts;
    use lint;
    use middle::cstore;
    use session::config::{build_configuration, build_session_options_and_crate_config};
    use session::config::{Lto, CrossLangLto};
    use session::build_session;
    use std::collections::{BTreeMap, BTreeSet};
    use std::iter::FromIterator;
    use std::path::PathBuf;
    use super::{Externs, OutputType, OutputTypes};
    use rustc_target::spec::{PanicStrategy, RelroLevel};
    use syntax::symbol::Symbol;
    use syntax::edition::{Edition, DEFAULT_EDITION};
    use syntax;

    fn optgroups() -> getopts::Options {
        let mut opts = getopts::Options::new();
        for group in super::rustc_optgroups() {
            (group.apply)(&mut opts);
        }
        return opts;
    }

    fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
        BTreeMap::from_iter(entries.into_iter())
    }

    fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
        BTreeSet::from_iter(entries.into_iter())
    }

    // When the user supplies --test we should implicitly supply --cfg test
    #[test]
    fn test_switch_implies_cfg_test() {
        syntax::with_globals(|| {
            let matches = &match optgroups().parse(&["--test".to_string()]) {
                Ok(m) => m,
                Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
            };
            let registry = errors::registry::Registry::new(&[]);
            let (sessopts, cfg) = build_session_options_and_crate_config(matches);
            let sess = build_session(sessopts, None, registry);
            let cfg = build_configuration(&sess, cfg);
            assert!(cfg.contains(&(Symbol::intern("test"), None)));
        });
    }

    // When the user supplies --test and --cfg test, don't implicitly add
    // another --cfg test
    #[test]
    fn test_switch_implies_cfg_test_unless_cfg_test() {
        syntax::with_globals(|| {
            let matches = &match optgroups().parse(&["--test".to_string(),
                                                     "--cfg=test".to_string()]) {
                Ok(m) => m,
                Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
            };
            let registry = errors::registry::Registry::new(&[]);
            let (sessopts, cfg) = build_session_options_and_crate_config(matches);
            let sess = build_session(sessopts, None, registry);
            let cfg = build_configuration(&sess, cfg);
            let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
            assert!(test_items.next().is_some());
            assert!(test_items.next().is_none());
        });
    }

    #[test]
    fn test_can_print_warnings() {
        syntax::with_globals(|| {
            let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
            let registry = errors::registry::Registry::new(&[]);
            let (sessopts, _) = build_session_options_and_crate_config(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(!sess.diagnostic().flags.can_emit_warnings);
        });

        syntax::with_globals(|| {
            let matches = optgroups()
                .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
                .unwrap();
            let registry = errors::registry::Registry::new(&[]);
            let (sessopts, _) = build_session_options_and_crate_config(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(sess.diagnostic().flags.can_emit_warnings);
        });

        syntax::with_globals(|| {
            let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
            let registry = errors::registry::Registry::new(&[]);
            let (sessopts, _) = build_session_options_and_crate_config(&matches);
            let sess = build_session(sessopts, None, registry);
            assert!(sess.diagnostic().flags.can_emit_warnings);
        });
    }

    #[test]
    fn test_output_types_tracking_hash_different_paths() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();

        v1.output_types =
            OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
        v2.output_types =
            OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
        v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);

        assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
        assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
    }

    #[test]
    fn test_output_types_tracking_hash_different_construction_order() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();

        v1.output_types = OutputTypes::new(&[
            (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
            (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
        ]);

        v2.output_types = OutputTypes::new(&[
            (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
            (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
        ]);

        assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
    }

    #[test]
    fn test_externs_tracking_hash_different_construction_order() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();

        v1.externs = Externs::new(mk_map(vec![
            (
                String::from("a"),
                mk_set(vec![String::from("b"), String::from("c")]),
            ),
            (
                String::from("d"),
                mk_set(vec![String::from("e"), String::from("f")]),
            ),
        ]));

        v2.externs = Externs::new(mk_map(vec![
            (
                String::from("d"),
                mk_set(vec![String::from("e"), String::from("f")]),
            ),
            (
                String::from("a"),
                mk_set(vec![String::from("b"), String::from("c")]),
            ),
        ]));

        v3.externs = Externs::new(mk_map(vec![
            (
                String::from("a"),
                mk_set(vec![String::from("b"), String::from("c")]),
            ),
            (
                String::from("d"),
                mk_set(vec![String::from("f"), String::from("e")]),
            ),
        ]));

        assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
        assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
    }

    #[test]
    fn test_lints_tracking_hash_different_values() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();

        v1.lint_opts = vec![
            (String::from("a"), lint::Allow),
            (String::from("b"), lint::Warn),
            (String::from("c"), lint::Deny),
            (String::from("d"), lint::Forbid),
        ];

        v2.lint_opts = vec![
            (String::from("a"), lint::Allow),
            (String::from("b"), lint::Warn),
            (String::from("X"), lint::Deny),
            (String::from("d"), lint::Forbid),
        ];

        v3.lint_opts = vec![
            (String::from("a"), lint::Allow),
            (String::from("b"), lint::Warn),
            (String::from("c"), lint::Forbid),
            (String::from("d"), lint::Deny),
        ];

        assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
        assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
    }

    #[test]
    fn test_lints_tracking_hash_different_construction_order() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();

        v1.lint_opts = vec![
            (String::from("a"), lint::Allow),
            (String::from("b"), lint::Warn),
            (String::from("c"), lint::Deny),
            (String::from("d"), lint::Forbid),
        ];

        v2.lint_opts = vec![
            (String::from("a"), lint::Allow),
            (String::from("c"), lint::Deny),
            (String::from("b"), lint::Warn),
            (String::from("d"), lint::Forbid),
        ];

        assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
    }

    #[test]
    fn test_search_paths_tracking_hash_different_order() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();
        let mut v4 = super::basic_options();

        // Reference
        v1.search_paths
            .add_path("native=abc", super::ErrorOutputType::Json(false));
        v1.search_paths
            .add_path("crate=def", super::ErrorOutputType::Json(false));
        v1.search_paths
            .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
        v1.search_paths
            .add_path("framework=jkl", super::ErrorOutputType::Json(false));
        v1.search_paths
            .add_path("all=mno", super::ErrorOutputType::Json(false));

        v2.search_paths
            .add_path("native=abc", super::ErrorOutputType::Json(false));
        v2.search_paths
            .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
        v2.search_paths
            .add_path("crate=def", super::ErrorOutputType::Json(false));
        v2.search_paths
            .add_path("framework=jkl", super::ErrorOutputType::Json(false));
        v2.search_paths
            .add_path("all=mno", super::ErrorOutputType::Json(false));

        v3.search_paths
            .add_path("crate=def", super::ErrorOutputType::Json(false));
        v3.search_paths
            .add_path("framework=jkl", super::ErrorOutputType::Json(false));
        v3.search_paths
            .add_path("native=abc", super::ErrorOutputType::Json(false));
        v3.search_paths
            .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
        v3.search_paths
            .add_path("all=mno", super::ErrorOutputType::Json(false));

        v4.search_paths
            .add_path("all=mno", super::ErrorOutputType::Json(false));
        v4.search_paths
            .add_path("native=abc", super::ErrorOutputType::Json(false));
        v4.search_paths
            .add_path("crate=def", super::ErrorOutputType::Json(false));
        v4.search_paths
            .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
        v4.search_paths
            .add_path("framework=jkl", super::ErrorOutputType::Json(false));

        assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
        assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
    }

    #[test]
    fn test_native_libs_tracking_hash_different_values() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();
        let mut v4 = super::basic_options();

        // Reference
        v1.libs = vec![
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("b"), None, Some(cstore::NativeFramework)),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        // Change label
        v2.libs = vec![
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("X"), None, Some(cstore::NativeFramework)),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        // Change kind
        v3.libs = vec![
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("b"), None, Some(cstore::NativeStatic)),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        // Change new-name
        v4.libs = vec![
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (
                String::from("b"),
                Some(String::from("X")),
                Some(cstore::NativeFramework),
            ),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
        assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
    }

    #[test]
    fn test_native_libs_tracking_hash_different_order() {
        let mut v1 = super::basic_options();
        let mut v2 = super::basic_options();
        let mut v3 = super::basic_options();

        // Reference
        v1.libs = vec![
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("b"), None, Some(cstore::NativeFramework)),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        v2.libs = vec![
            (String::from("b"), None, Some(cstore::NativeFramework)),
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("c"), None, Some(cstore::NativeUnknown)),
        ];

        v3.libs = vec![
            (String::from("c"), None, Some(cstore::NativeUnknown)),
            (String::from("a"), None, Some(cstore::NativeStatic)),
            (String::from("b"), None, Some(cstore::NativeFramework)),
        ];

        assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
        assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
        assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());

        // Check clone
        assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
        assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
        assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
    }

    #[test]
    fn test_codegen_options_tracking_hash() {
        let reference = super::basic_options();
        let mut opts = super::basic_options();

        // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
        opts.cg.ar = Some(String::from("abc"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.linker = Some(PathBuf::from("linker"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.link_dead_code = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.rpath = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.extra_filename = String::from("extra-filename");
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.codegen_units = Some(42);
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.remark = super::SomePasses(vec![String::from("pass1"), String::from("pass2")]);
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.save_temps = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts.cg.incremental = Some(String::from("abc"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        // Make sure changing a [TRACKED] option changes the hash
        opts = reference.clone();
        opts.cg.lto = Lto::Fat;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.target_cpu = Some(String::from("abc"));
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.target_feature = String::from("all the features, all of them");
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.passes = vec![String::from("1"), String::from("2")];
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.overflow_checks = Some(true);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.no_prepopulate_passes = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.no_vectorize_loops = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.no_vectorize_slp = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.soft_float = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.prefer_dynamic = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.no_integrated_as = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.no_redzone = Some(true);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.relocation_model = Some(String::from("relocation model"));
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.code_model = Some(String::from("code model"));
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.tls_model = Some(String::from("tls model"));
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.pgo_gen = Some(String::from("abc"));
        assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.pgo_use = String::from("abc");
        assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.metadata = vec![String::from("A"), String::from("B")];
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.debuginfo = Some(0xdeadbeef);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.debuginfo = Some(0xba5eba11);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.force_frame_pointers = Some(false);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.debug_assertions = Some(true);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.inline_threshold = Some(0xf007ba11);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.cg.panic = Some(PanicStrategy::Abort);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
    }

    #[test]
    fn test_debugging_options_tracking_hash() {
        let reference = super::basic_options();
        let mut opts = super::basic_options();

        // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
        opts.debugging_opts.verbose = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.time_passes = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.count_llvm_insns = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.time_llvm_passes = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.input_stats = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.codegen_stats = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.borrowck_stats = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.meta_stats = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.print_link_args = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.print_llvm_passes = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.ast_json = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.ast_json_noexpand = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.ls = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.save_analysis = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.flowgraph_print_loans = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.flowgraph_print_moves = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.flowgraph_print_assigns = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.flowgraph_print_all = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.print_region_graph = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.parse_only = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.incremental = Some(String::from("abc"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.dump_dep_graph = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.query_dep_graph = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.no_analysis = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.unstable_options = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.trace_macros = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.keep_hygiene_data = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.keep_ast = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.print_mono_items = Some(String::from("abc"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.dump_mir = Some(String::from("abc"));
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.dump_mir_dir = String::from("abc");
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
        opts.debugging_opts.dump_mir_graphviz = true;
        assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

        // Make sure changing a [TRACKED] option changes the hash
        opts = reference.clone();
        opts.debugging_opts.asm_comments = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.no_verify = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.no_landing_pads = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.fewer_names = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.no_codegen = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.treat_err_as_bug = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.continue_parse_after_error = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.force_overflow_checks = Some(true);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.enable_nonzeroing_move_hints = true;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.show_span = Some(String::from("abc"));
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.mir_opt_level = 3;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.relro_level = Some(RelroLevel::Full);
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());

        opts = reference.clone();
        opts.debugging_opts.cross_lang_lto = CrossLangLto::NoLink;
        assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
    }

    #[test]
    fn test_edition_parsing() {
        // test default edition
        let options = super::basic_options();
        assert!(options.edition == DEFAULT_EDITION);

        let matches = optgroups()
            .parse(&["--edition=2018".to_string()])
            .unwrap();
        let (sessopts, _) = build_session_options_and_crate_config(&matches);
        assert!(sessopts.edition == Edition::Edition2018)
    }
}