summaryrefslogtreecommitdiff
path: root/lib/spack/spack/spec.py
blob: 270cf5eaf278f984c466b280f42ddc492b7de787 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
# Copyright 2013-2023 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""
Spack allows very fine-grained control over how packages are installed and
over how they are built and configured.  To make this easy, it has its own
syntax for declaring a dependence.  We call a descriptor of a particular
package configuration a "spec".

The syntax looks like this:

.. code-block:: sh

    $ spack install mpileaks ^openmpi @1.2:1.4 +debug %intel @12.1 target=zen
                    0        1        2        3      4      5     6

The first part of this is the command, 'spack install'.  The rest of the
line is a spec for a particular installation of the mpileaks package.

0. The package to install

1. A dependency of the package, prefixed by ^

2. A version descriptor for the package.  This can either be a specific
   version, like "1.2", or it can be a range of versions, e.g. "1.2:1.4".
   If multiple specific versions or multiple ranges are acceptable, they
   can be separated by commas, e.g. if a package will only build with
   versions 1.0, 1.2-1.4, and 1.6-1.8 of mavpich, you could say:

       depends_on("mvapich@1.0,1.2:1.4,1.6:1.8")

3. A compile-time variant of the package.  If you need openmpi to be
   built in debug mode for your package to work, you can require it by
   adding +debug to the openmpi spec when you depend on it.  If you do
   NOT want the debug option to be enabled, then replace this with -debug.
   If you would like for the variant to be propagated through all your
   package's dependencies use "++" for enabling and "--" or "~~" for disabling.

4. The name of the compiler to build with.

5. The versions of the compiler to build with.  Note that the identifier
   for a compiler version is the same '@' that is used for a package version.
   A version list denoted by '@' is associated with the compiler only if
   if it comes immediately after the compiler name.  Otherwise it will be
   associated with the current package spec.

6. The architecture to build with.  This is needed on machines where
   cross-compilation is required
"""
import collections
import collections.abc
import enum
import io
import itertools
import os
import pathlib
import platform
import re
import socket
import warnings
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union

import llnl.path
import llnl.string
import llnl.util.filesystem as fs
import llnl.util.lang as lang
import llnl.util.tty as tty
import llnl.util.tty.color as clr

import spack.compiler
import spack.compilers
import spack.config
import spack.dependency as dp
import spack.deptypes as dt
import spack.error
import spack.hash_types as ht
import spack.parser
import spack.patch
import spack.paths
import spack.platforms
import spack.provider_index
import spack.repo
import spack.solver
import spack.store
import spack.target
import spack.traverse as traverse
import spack.util.crypto
import spack.util.executable
import spack.util.hash
import spack.util.module_cmd as md
import spack.util.prefix
import spack.util.spack_json as sjson
import spack.util.spack_yaml as syaml
import spack.variant as vt
import spack.version as vn
import spack.version.git_ref_lookup

__all__ = [
    "CompilerSpec",
    "Spec",
    "SpecParseError",
    "ArchitecturePropagationError",
    "DuplicateDependencyError",
    "DuplicateCompilerSpecError",
    "UnsupportedCompilerError",
    "DuplicateArchitectureError",
    "InconsistentSpecError",
    "InvalidDependencyError",
    "NoProviderError",
    "MultipleProviderError",
    "UnsatisfiableSpecNameError",
    "UnsatisfiableVersionSpecError",
    "UnsatisfiableCompilerSpecError",
    "UnsatisfiableCompilerFlagSpecError",
    "UnsatisfiableArchitectureSpecError",
    "UnsatisfiableProviderSpecError",
    "UnsatisfiableDependencySpecError",
    "AmbiguousHashError",
    "InvalidHashError",
    "SpecDeprecatedError",
]

#: Valid pattern for an identifier in Spack

IDENTIFIER_RE = r"\w[\w-]*"

COMPILER_COLOR = "@g"  #: color for highlighting compilers
VERSION_COLOR = "@c"  #: color for highlighting versions
ARCHITECTURE_COLOR = "@m"  #: color for highlighting architectures
ENABLED_VARIANT_COLOR = "@B"  #: color for highlighting enabled variants
DISABLED_VARIANT_COLOR = "r"  #: color for highlighting disabled varaints
DEPENDENCY_COLOR = "@."  #: color for highlighting dependencies
HASH_COLOR = "@K"  #: color for highlighting package hashes

#: This map determines the coloring of specs when using color output.
#: We make the fields different colors to enhance readability.
#: See llnl.util.tty.color for descriptions of the color codes.
COLOR_FORMATS = {
    "%": COMPILER_COLOR,
    "@": VERSION_COLOR,
    "=": ARCHITECTURE_COLOR,
    "+": ENABLED_VARIANT_COLOR,
    "~": DISABLED_VARIANT_COLOR,
    "^": DEPENDENCY_COLOR,
    "#": HASH_COLOR,
}

#: Regex used for splitting by spec field separators.
#: These need to be escaped to avoid metacharacters in
#: ``COLOR_FORMATS.keys()``.
_SEPARATORS = "[\\%s]" % "\\".join(COLOR_FORMATS.keys())

#: Default format for Spec.format(). This format can be round-tripped, so that:
#:     Spec(Spec("string").format()) == Spec("string)"
DEFAULT_FORMAT = (
    "{name}{@versions}"
    "{%compiler.name}{@compiler.versions}{compiler_flags}"
    "{variants}{arch=architecture}{/abstract_hash}"
)

#: Display format, which eliminates extra `@=` in the output, for readability.
DISPLAY_FORMAT = (
    "{name}{@version}"
    "{%compiler.name}{@compiler.version}{compiler_flags}"
    "{variants}{arch=architecture}{/abstract_hash}"
)

#: Regular expression to pull spec contents out of clearsigned signature
#: file.
CLEARSIGN_FILE_REGEX = re.compile(
    (
        r"^-----BEGIN PGP SIGNED MESSAGE-----"
        r"\s+Hash:\s+[^\s]+\s+(.+)-----BEGIN PGP SIGNATURE-----"
    ),
    re.MULTILINE | re.DOTALL,
)

#: specfile format version. Must increase monotonically
SPECFILE_FORMAT_VERSION = 4


class InstallStatus(enum.Enum):
    """Maps install statuses to symbols for display.

    Options are artificially disjoint for display purposes
    """

    installed = "@g{[+]}  "
    upstream = "@g{[^]}  "
    external = "@g{[e]}  "
    absent = "@K{ - }  "
    missing = "@r{[-]}  "


def colorize_spec(spec):
    """Returns a spec colorized according to the colors specified in
    COLOR_FORMATS."""

    class insert_color:
        def __init__(self):
            self.last = None

        def __call__(self, match):
            # ignore compiler versions (color same as compiler)
            sep = match.group(0)
            if self.last == "%" and sep == "@":
                return clr.cescape(sep)
            self.last = sep

            return "%s%s" % (COLOR_FORMATS[sep], clr.cescape(sep))

    return clr.colorize(re.sub(_SEPARATORS, insert_color(), str(spec)) + "@.")


@lang.lazy_lexicographic_ordering
class ArchSpec:
    """Aggregate the target platform, the operating system and the target microarchitecture."""

    @staticmethod
    def _return_arch(os_tag, target_tag):
        platform = spack.platforms.host()
        default_os = platform.operating_system(os_tag)
        default_target = platform.target(target_tag)
        arch_tuple = str(platform), str(default_os), str(default_target)
        return ArchSpec(arch_tuple)

    @staticmethod
    def default_arch():
        """Return the default architecture"""
        return ArchSpec._return_arch("default_os", "default_target")

    @staticmethod
    def frontend_arch():
        """Return the frontend architecture"""
        return ArchSpec._return_arch("frontend", "frontend")

    __slots__ = "_platform", "_os", "_target"

    def __init__(self, spec_or_platform_tuple=(None, None, None)):
        """Architecture specification a package should be built with.

        Each ArchSpec is comprised of three elements: a platform (e.g. Linux),
        an OS (e.g. RHEL6), and a target (e.g. x86_64).

        Args:
            spec_or_platform_tuple (ArchSpec or str or tuple): if an ArchSpec
                is passed it will be duplicated into the new instance.
                Otherwise information on platform, OS and target should be
                passed in either as a spec string or as a tuple.
        """

        # If the argument to __init__ is a spec string, parse it
        # and construct an ArchSpec
        def _string_or_none(s):
            if s and s != "None":
                return str(s)
            return None

        # If another instance of ArchSpec was passed, duplicate it
        if isinstance(spec_or_platform_tuple, ArchSpec):
            other = spec_or_platform_tuple
            platform_tuple = other.platform, other.os, other.target

        elif isinstance(spec_or_platform_tuple, (str, tuple)):
            spec_fields = spec_or_platform_tuple

            # Normalize the string to a tuple
            if isinstance(spec_or_platform_tuple, str):
                spec_fields = spec_or_platform_tuple.split("-")
                if len(spec_fields) != 3:
                    msg = "cannot construct an ArchSpec from {0!s}"
                    raise ValueError(msg.format(spec_or_platform_tuple))

            platform, operating_system, target = spec_fields
            platform_tuple = (_string_or_none(platform), _string_or_none(operating_system), target)

        self.platform, self.os, self.target = platform_tuple

    @staticmethod
    def override(init_spec, change_spec):
        if init_spec:
            new_spec = init_spec.copy()
        else:
            new_spec = ArchSpec()
        if change_spec.platform:
            new_spec.platform = change_spec.platform
            # TODO: if the platform is changed to something that is incompatible
            # with the current os, we should implicitly remove it
        if change_spec.os:
            new_spec.os = change_spec.os
        if change_spec.target:
            new_spec.target = change_spec.target
        return new_spec

    def _autospec(self, spec_like):
        if isinstance(spec_like, ArchSpec):
            return spec_like
        return ArchSpec(spec_like)

    def _cmp_iter(self):
        yield self.platform
        yield self.os
        yield self.target

    @property
    def platform(self):
        """The platform of the architecture."""
        return self._platform

    @platform.setter
    def platform(self, value):
        # The platform of the architecture spec will be verified as a
        # supported Spack platform before it's set to ensure all specs
        # refer to valid platforms.
        value = str(value) if value is not None else None
        self._platform = value

    @property
    def os(self):
        """The OS of this ArchSpec."""
        return self._os

    @os.setter
    def os(self, value):
        # The OS of the architecture spec will update the platform field
        # if the OS is set to one of the reserved OS types so that the
        # default OS type can be resolved.  Since the reserved OS
        # information is only available for the host machine, the platform
        # will assumed to be the host machine's platform.
        value = str(value) if value is not None else None

        if value in spack.platforms.Platform.reserved_oss:
            curr_platform = str(spack.platforms.host())
            self.platform = self.platform or curr_platform

            if self.platform != curr_platform:
                raise ValueError(
                    "Can't set arch spec OS to reserved value '%s' when the "
                    "arch platform (%s) isn't the current platform (%s)"
                    % (value, self.platform, curr_platform)
                )

            spec_platform = spack.platforms.by_name(self.platform)
            value = str(spec_platform.operating_system(value))

        self._os = value

    @property
    def target(self):
        """The target of the architecture."""
        return self._target

    @target.setter
    def target(self, value):
        # The target of the architecture spec will update the platform field
        # if the target is set to one of the reserved target types so that
        # the default target type can be resolved.  Since the reserved target
        # information is only available for the host machine, the platform
        # will assumed to be the host machine's platform.

        def target_or_none(t):
            if isinstance(t, spack.target.Target):
                return t
            if t and t != "None":
                return spack.target.Target(t)
            return None

        value = target_or_none(value)

        if str(value) in spack.platforms.Platform.reserved_targets:
            curr_platform = str(spack.platforms.host())
            self.platform = self.platform or curr_platform

            if self.platform != curr_platform:
                raise ValueError(
                    "Can't set arch spec target to reserved value '%s' when "
                    "the arch platform (%s) isn't the current platform (%s)"
                    % (value, self.platform, curr_platform)
                )

            spec_platform = spack.platforms.by_name(self.platform)
            value = spec_platform.target(value)

        self._target = value

    def satisfies(self, other: "ArchSpec") -> bool:
        """Return True if all concrete specs matching self also match other, otherwise False.

        Args:
            other: spec to be satisfied
        """
        other = self._autospec(other)

        # Check platform and os
        for attribute in ("platform", "os"):
            other_attribute = getattr(other, attribute)
            self_attribute = getattr(self, attribute)
            if other_attribute and self_attribute != other_attribute:
                return False

        return self._target_satisfies(other, strict=True)

    def intersects(self, other: "ArchSpec") -> bool:
        """Return True if there exists at least one concrete spec that matches both
        self and other, otherwise False.

        This operation is commutative, and if two specs intersect it means that one
        can constrain the other.

        Args:
            other: spec to be checked for compatibility
        """
        other = self._autospec(other)

        # Check platform and os
        for attribute in ("platform", "os"):
            other_attribute = getattr(other, attribute)
            self_attribute = getattr(self, attribute)
            if other_attribute and self_attribute and self_attribute != other_attribute:
                return False

        return self._target_satisfies(other, strict=False)

    def _target_satisfies(self, other: "ArchSpec", strict: bool) -> bool:
        if strict is True:
            need_to_check = bool(other.target)
        else:
            need_to_check = bool(other.target and self.target)

        if not need_to_check:
            return True

        # other_target is there and strict=True
        if self.target is None:
            return False

        return bool(self._target_intersection(other))

    def _target_constrain(self, other: "ArchSpec") -> bool:
        if not other._target_satisfies(self, strict=False):
            raise UnsatisfiableArchitectureSpecError(self, other)

        if self.target_concrete:
            return False

        elif other.target_concrete:
            self.target = other.target
            return True

        # Compute the intersection of every combination of ranges in the lists
        results = self._target_intersection(other)
        attribute_str = ",".join(results)

        if self.target == attribute_str:
            return False

        self.target = attribute_str
        return True

    def _target_intersection(self, other):
        results = []

        if not self.target or not other.target:
            return results

        for s_target_range in str(self.target).split(","):
            s_min, s_sep, s_max = s_target_range.partition(":")
            for o_target_range in str(other.target).split(","):
                o_min, o_sep, o_max = o_target_range.partition(":")

                if not s_sep:
                    # s_target_range is a concrete target
                    # get a microarchitecture reference for at least one side
                    # of each comparison so we can use archspec comparators
                    s_comp = spack.target.Target(s_min).microarchitecture
                    if not o_sep:
                        if s_min == o_min:
                            results.append(s_min)
                    elif (not o_min or s_comp >= o_min) and (not o_max or s_comp <= o_max):
                        results.append(s_min)
                elif not o_sep:
                    # "cast" to microarchitecture
                    o_comp = spack.target.Target(o_min).microarchitecture
                    if (not s_min or o_comp >= s_min) and (not s_max or o_comp <= s_max):
                        results.append(o_min)
                else:
                    # Take intersection of two ranges
                    # Lots of comparisons needed
                    _s_min = spack.target.Target(s_min).microarchitecture
                    _s_max = spack.target.Target(s_max).microarchitecture
                    _o_min = spack.target.Target(o_min).microarchitecture
                    _o_max = spack.target.Target(o_max).microarchitecture

                    n_min = s_min if _s_min >= _o_min else o_min
                    n_max = s_max if _s_max <= _o_max else o_max
                    _n_min = spack.target.Target(n_min).microarchitecture
                    _n_max = spack.target.Target(n_max).microarchitecture
                    if _n_min == _n_max:
                        results.append(n_min)
                    elif not n_min or not n_max or _n_min < _n_max:
                        results.append("%s:%s" % (n_min, n_max))
        return results

    def constrain(self, other: "ArchSpec") -> bool:
        """Projects all architecture fields that are specified in the given
        spec onto the instance spec if they're missing from the instance
        spec.

        This will only work if the two specs are compatible.

        Args:
            other (ArchSpec or str): constraints to be added

        Returns:
            True if the current instance was constrained, False otherwise.
        """
        other = self._autospec(other)

        if not other.intersects(self):
            raise UnsatisfiableArchitectureSpecError(other, self)

        constrained = False
        for attr in ("platform", "os"):
            svalue, ovalue = getattr(self, attr), getattr(other, attr)
            if svalue is None and ovalue is not None:
                setattr(self, attr, ovalue)
                constrained = True

        constrained |= self._target_constrain(other)

        return constrained

    def copy(self):
        """Copy the current instance and returns the clone."""
        return ArchSpec(self)

    @property
    def concrete(self):
        """True if the spec is concrete, False otherwise"""
        return self.platform and self.os and self.target and self.target_concrete

    @property
    def target_concrete(self):
        """True if the target is not a range or list."""
        return (
            self.target is not None and ":" not in str(self.target) and "," not in str(self.target)
        )

    def to_dict(self):
        d = syaml.syaml_dict(
            [
                ("platform", self.platform),
                ("platform_os", self.os),
                ("target", self.target.to_dict_or_value()),
            ]
        )
        return syaml.syaml_dict([("arch", d)])

    @staticmethod
    def from_dict(d):
        """Import an ArchSpec from raw YAML/JSON data"""
        arch = d["arch"]
        target = spack.target.Target.from_dict_or_value(arch["target"])
        return ArchSpec((arch["platform"], arch["platform_os"], target))

    def __str__(self):
        return "%s-%s-%s" % (self.platform, self.os, self.target)

    def __repr__(self):
        fmt = "ArchSpec(({0.platform!r}, {0.os!r}, {1!r}))"
        return fmt.format(self, str(self.target))

    def __contains__(self, string):
        return string in str(self) or string in self.target


@lang.lazy_lexicographic_ordering
class CompilerSpec:
    """The CompilerSpec field represents the compiler or range of compiler
    versions that a package should be built with.  CompilerSpecs have a
    name and a version list."""

    __slots__ = "name", "versions"

    def __init__(self, *args):
        nargs = len(args)
        if nargs == 1:
            arg = args[0]
            # If there is one argument, it's either another CompilerSpec
            # to copy or a string to parse
            if isinstance(arg, str):
                spec = spack.parser.parse_one_or_raise(f"%{arg}")
                self.name = spec.compiler.name
                self.versions = spec.compiler.versions

            elif isinstance(arg, CompilerSpec):
                self.name = arg.name
                self.versions = arg.versions.copy()

            else:
                raise TypeError(
                    "Can only build CompilerSpec from string or "
                    + "CompilerSpec. Found %s" % type(arg)
                )

        elif nargs == 2:
            name, version = args
            self.name = name
            self.versions = vn.VersionList([vn.ver(version)])

        else:
            raise TypeError("__init__ takes 1 or 2 arguments. (%d given)" % nargs)

    def _add_versions(self, version_list):
        # If it already has a non-trivial version list, this is an error
        if self.versions and self.versions != vn.any_version:
            # Note: This may be impossible to reach by the current parser
            # Keeping it in case the implementation changes.
            raise MultipleVersionError(
                "A spec cannot contain multiple version signifiers. Use a version list instead."
            )
        self.versions = vn.VersionList()
        for version in version_list:
            self.versions.add(version)

    def _autospec(self, compiler_spec_like):
        if isinstance(compiler_spec_like, CompilerSpec):
            return compiler_spec_like
        return CompilerSpec(compiler_spec_like)

    def intersects(self, other: "CompilerSpec") -> bool:
        """Return True if all concrete specs matching self also match other, otherwise False.

        For compiler specs this means that the name of the compiler must be the same for
        self and other, and that the versions ranges should intersect.

        Args:
            other: spec to be satisfied
        """
        other = self._autospec(other)
        return self.name == other.name and self.versions.intersects(other.versions)

    def satisfies(self, other: "CompilerSpec") -> bool:
        """Return True if all concrete specs matching self also match other, otherwise False.

        For compiler specs this means that the name of the compiler must be the same for
        self and other, and that the version range of self is a subset of that of other.

        Args:
            other: spec to be satisfied
        """
        other = self._autospec(other)
        return self.name == other.name and self.versions.satisfies(other.versions)

    def constrain(self, other: "CompilerSpec") -> bool:
        """Intersect self's versions with other.

        Return whether the CompilerSpec changed.
        """
        other = self._autospec(other)

        # ensure that other will actually constrain this spec.
        if not other.intersects(self):
            raise UnsatisfiableCompilerSpecError(other, self)

        return self.versions.intersect(other.versions)

    @property
    def concrete(self):
        """A CompilerSpec is concrete if its versions are concrete and there
        is an available compiler with the right version."""
        return self.versions.concrete

    @property
    def version(self):
        if not self.concrete:
            raise spack.error.SpecError("Spec is not concrete: " + str(self))
        return self.versions[0]

    def copy(self):
        clone = CompilerSpec.__new__(CompilerSpec)
        clone.name = self.name
        clone.versions = self.versions.copy()
        return clone

    def _cmp_iter(self):
        yield self.name
        yield self.versions

    def to_dict(self):
        d = syaml.syaml_dict([("name", self.name)])
        d.update(self.versions.to_dict())

        return syaml.syaml_dict([("compiler", d)])

    @staticmethod
    def from_dict(d):
        d = d["compiler"]
        return CompilerSpec(d["name"], vn.VersionList.from_dict(d))

    @property
    def display_str(self):
        """Equivalent to {compiler.name}{@compiler.version} for Specs, without extra
        @= for readability."""
        if self.concrete:
            return f"{self.name}@{self.version}"
        elif self.versions != vn.any_version:
            return f"{self.name}@{self.versions}"
        return self.name

    def __str__(self):
        out = self.name
        if self.versions and self.versions != vn.any_version:
            out += f"@{self.versions}"
        return out

    def __repr__(self):
        return str(self)


@lang.lazy_lexicographic_ordering
class DependencySpec:
    """DependencySpecs represent an edge in the DAG, and contain dependency types
    and information on the virtuals being provided.

    Dependencies can be one (or more) of several types:

    - build: needs to be in the PATH at build time.
    - link: is linked to and added to compiler flags.
    - run: needs to be in the PATH for the package to run.

    Args:
        parent: starting node of the edge
        spec: ending node of the edge.
        depflag: represents dependency relationships.
        virtuals: virtual packages provided from child to parent node.
    """

    __slots__ = "parent", "spec", "depflag", "virtuals"

    def __init__(
        self, parent: "Spec", spec: "Spec", *, depflag: dt.DepFlag, virtuals: Tuple[str, ...]
    ):
        self.parent = parent
        self.spec = spec
        self.depflag = depflag
        self.virtuals = tuple(sorted(set(virtuals)))

    def update_deptypes(self, depflag: dt.DepFlag) -> bool:
        """Update the current dependency types"""
        old = self.depflag
        new = depflag | old
        if new == old:
            return False
        self.depflag = new
        return True

    def update_virtuals(self, virtuals: Tuple[str, ...]) -> bool:
        """Update the list of provided virtuals"""
        old = self.virtuals
        self.virtuals = tuple(sorted(set(virtuals).union(self.virtuals)))
        return old != self.virtuals

    def copy(self) -> "DependencySpec":
        """Return a copy of this edge"""
        return DependencySpec(self.parent, self.spec, depflag=self.depflag, virtuals=self.virtuals)

    def _cmp_iter(self):
        yield self.parent.name if self.parent else None
        yield self.spec.name if self.spec else None
        yield self.depflag
        yield self.virtuals

    def __str__(self) -> str:
        parent = self.parent.name if self.parent else None
        child = self.spec.name if self.spec else None
        return f"{parent} {self.depflag}[virtuals={','.join(self.virtuals)}] --> {child}"

    def flip(self) -> "DependencySpec":
        """Flip the dependency, and drop virtual information"""
        return DependencySpec(
            parent=self.spec, spec=self.parent, depflag=self.depflag, virtuals=()
        )


class CompilerFlag(str):
    """Will store a flag value and it's propagation value

    Args:
        value (str): the flag's value
        propagate (bool): if ``True`` the flag value will
            be passed to the package's dependencies. If
            ``False`` it will not
    """

    def __new__(cls, value, **kwargs):
        obj = str.__new__(cls, value)
        obj.propagate = kwargs.pop("propagate", False)
        return obj


_valid_compiler_flags = ["cflags", "cxxflags", "fflags", "ldflags", "ldlibs", "cppflags"]


class FlagMap(lang.HashableMap):
    __slots__ = ("spec",)

    def __init__(self, spec):
        super().__init__()
        self.spec = spec

    def satisfies(self, other):
        return all(f in self and self[f] == other[f] for f in other)

    def intersects(self, other):
        common_types = set(self) & set(other)
        for flag_type in common_types:
            if not self[flag_type] or not other[flag_type]:
                # At least one of the two is empty
                continue

            if self[flag_type] != other[flag_type]:
                return False

            if not all(
                f1.propagate == f2.propagate for f1, f2 in zip(self[flag_type], other[flag_type])
            ):
                # At least one propagation flag didn't match
                return False
        return True

    def constrain(self, other):
        """Add all flags in other that aren't in self to self.

        Return whether the spec changed.
        """
        if other.spec and other.spec._concrete:
            for k in self:
                if k not in other:
                    raise UnsatisfiableCompilerFlagSpecError(self[k], "<absent>")

        changed = False
        for k in other:
            if k in self and not set(self[k]) <= set(other[k]):
                raise UnsatisfiableCompilerFlagSpecError(
                    " ".join(f for f in self[k]), " ".join(f for f in other[k])
                )
            elif k not in self:
                self[k] = other[k]
                changed = True

            # Check that the propagation values match
            if self[k] == other[k]:
                for i in range(len(other[k])):
                    if self[k][i].propagate != other[k][i].propagate:
                        raise UnsatisfiableCompilerFlagSpecError(
                            self[k][i].propagate, other[k][i].propagate
                        )
        return changed

    @staticmethod
    def valid_compiler_flags():
        return _valid_compiler_flags

    def copy(self):
        clone = FlagMap(self.spec)
        for name, compiler_flag in self.items():
            clone[name] = compiler_flag
        return clone

    def add_flag(self, flag_type, value, propagation):
        """Stores the flag's value in CompilerFlag and adds it
        to the FlagMap

        Args:
            flag_type (str): the type of flag
            value (str): the flag's value that will be added to the flag_type's
                corresponding list
            propagation (bool): if ``True`` the flag value will be passed to
                the packages' dependencies. If``False`` it will not be passed
        """
        flag = CompilerFlag(value, propagate=propagation)

        if flag_type not in self:
            self[flag_type] = [flag]
        else:
            self[flag_type].append(flag)

    def yaml_entry(self, flag_type):
        """Returns the flag type and a list of the flag values since the
        propagation values aren't needed when writing to yaml

        Args:
            flag_type (str): the type of flag to get values from

        Returns the flag_type and a list of the corresponding flags in
            string format
        """
        return flag_type, [str(flag) for flag in self[flag_type]]

    def _cmp_iter(self):
        for k, v in sorted(self.items()):
            yield k

            def flags():
                for flag in v:
                    yield flag

            yield flags

    def __str__(self):
        sorted_items = sorted((k, v) for k, v in self.items() if v)

        result = ""
        for flag_type, flags in sorted_items:
            normal = [f for f in flags if not f.propagate]
            if normal:
                result += f" {flag_type}={spack.parser.quote_if_needed(' '.join(normal))}"

            propagated = [f for f in flags if f.propagate]
            if propagated:
                result += f" {flag_type}=={spack.parser.quote_if_needed(' '.join(propagated))}"

        # TODO: somehow add this space only if something follows in Spec.format()
        if sorted_items:
            result += " "

        return result


def _sort_by_dep_types(dspec: DependencySpec):
    return dspec.depflag


#: Enum for edge directions
EdgeDirection = lang.enum(parent=0, child=1)


@lang.lazy_lexicographic_ordering
class _EdgeMap(collections.abc.Mapping):
    """Represent a collection of edges (DependencySpec objects) in the DAG.

    Objects of this class are used in Specs to track edges that are
    outgoing towards direct dependencies, or edges that are incoming
    from direct dependents.

    Edges are stored in a dictionary and keyed by package name.
    """

    __slots__ = "edges", "store_by_child"

    def __init__(self, store_by=EdgeDirection.child):
        # Sanitize input arguments
        msg = 'unexpected value for "store_by" argument'
        assert store_by in (EdgeDirection.child, EdgeDirection.parent), msg

        #: This dictionary maps a package name to a list of edges
        #: i.e. to a list of DependencySpec objects
        self.edges = {}
        self.store_by_child = store_by == EdgeDirection.child

    def __getitem__(self, key):
        return self.edges[key]

    def __iter__(self):
        return iter(self.edges)

    def __len__(self):
        return len(self.edges)

    def add(self, edge: DependencySpec):
        key = edge.spec.name if self.store_by_child else edge.parent.name
        if key in self.edges:
            lst = self.edges[key]
            lst.append(edge)
            lst.sort(key=_sort_by_dep_types)
        else:
            self.edges[key] = [edge]

    def __str__(self):
        return "{deps: %s}" % ", ".join(str(d) for d in sorted(self.values()))

    def _cmp_iter(self):
        for item in sorted(itertools.chain.from_iterable(self.edges.values())):
            yield item

    def copy(self):
        """Copies this object and returns a clone"""
        clone = type(self)()
        clone.store_by_child = self.store_by_child

        # Copy everything from this dict into it.
        for dspec in itertools.chain.from_iterable(self.values()):
            clone.add(dspec.copy())

        return clone

    def select(self, parent=None, child=None, depflag: dt.DepFlag = dt.ALL):
        """Select a list of edges and return them.

        If an edge:
        - Has *any* of the dependency types passed as argument,
        - Matches the parent and/or child name, if passed
        then it is selected.

        The deptypes argument needs to be a flag, since the method won't
        convert it for performance reason.

        Args:
            parent (str): name of the parent package
            child (str): name of the child package
            depflag: allowed dependency types in flag form

        Returns:
            List of DependencySpec objects
        """
        if not depflag:
            return []

        # Start from all the edges we store
        selected = (d for d in itertools.chain.from_iterable(self.values()))

        # Filter by parent name
        if parent:
            selected = (d for d in selected if d.parent.name == parent)

        # Filter by child name
        if child:
            selected = (d for d in selected if d.spec.name == child)

        # Filter by allowed dependency types
        selected = (dep for dep in selected if not dep.depflag or (depflag & dep.depflag))

        return list(selected)

    def clear(self):
        self.edges.clear()


def _command_default_handler(descriptor, spec, cls):
    """Default handler when looking for the 'command' attribute.

    Tries to search for ``spec.name`` in the ``spec.home.bin`` directory.

    Parameters:
        descriptor (ForwardQueryToPackage): descriptor that triggered the call
        spec (Spec): spec that is being queried
        cls (type(spec)): type of spec, to match the signature of the
            descriptor ``__get__`` method

    Returns:
        Executable: An executable of the command

    Raises:
        RuntimeError: If the command is not found
    """
    home = getattr(spec.package, "home")
    path = os.path.join(home.bin, spec.name)

    if fs.is_exe(path):
        return spack.util.executable.Executable(path)
    else:
        msg = "Unable to locate {0} command in {1}"
        raise RuntimeError(msg.format(spec.name, home.bin))


def _headers_default_handler(descriptor, spec, cls):
    """Default handler when looking for the 'headers' attribute.

    Tries to search for ``*.h`` files recursively starting from
    ``spec.package.home.include``.

    Parameters:
        descriptor (ForwardQueryToPackage): descriptor that triggered the call
        spec (Spec): spec that is being queried
        cls (type(spec)): type of spec, to match the signature of the
            descriptor ``__get__`` method

    Returns:
        HeaderList: The headers in ``prefix.include``

    Raises:
        NoHeadersError: If no headers are found
    """
    home = getattr(spec.package, "home")
    headers = fs.find_headers("*", root=home.include, recursive=True)

    if headers:
        return headers
    else:
        msg = "Unable to locate {0} headers in {1}"
        raise spack.error.NoHeadersError(msg.format(spec.name, home))


def _libs_default_handler(descriptor, spec, cls):
    """Default handler when looking for the 'libs' attribute.

    Tries to search for ``lib{spec.name}`` recursively starting from
    ``spec.package.home``. If ``spec.name`` starts with ``lib``, searches for
    ``{spec.name}`` instead.

    Parameters:
        descriptor (ForwardQueryToPackage): descriptor that triggered the call
        spec (Spec): spec that is being queried
        cls (type(spec)): type of spec, to match the signature of the
            descriptor ``__get__`` method

    Returns:
        LibraryList: The libraries found

    Raises:
        NoLibrariesError: If no libraries are found
    """

    # Variable 'name' is passed to function 'find_libraries', which supports
    # glob characters. For example, we have a package with a name 'abc-abc'.
    # Now, we don't know if the original name of the package is 'abc_abc'
    # (and it generates a library 'libabc_abc.so') or 'abc-abc' (and it
    # generates a library 'libabc-abc.so'). So, we tell the function
    # 'find_libraries' to give us anything that matches 'libabc?abc' and it
    # gives us either 'libabc-abc.so' or 'libabc_abc.so' (or an error)
    # depending on which one exists (there is a possibility, of course, to
    # get something like 'libabcXabc.so, but for now we consider this
    # unlikely).
    name = spec.name.replace("-", "?")
    home = getattr(spec.package, "home")

    # Avoid double 'lib' for packages whose names already start with lib
    if not name.startswith("lib") and not spec.satisfies("platform=windows"):
        name = "lib" + name

    # If '+shared' search only for shared library; if '~shared' search only for
    # static library; otherwise, first search for shared and then for static.
    search_shared = (
        [True] if ("+shared" in spec) else ([False] if ("~shared" in spec) else [True, False])
    )

    for shared in search_shared:
        # Since we are searching for link libraries, on Windows search only for
        # ".Lib" extensions by default as those represent import libraries for implict links.
        libs = fs.find_libraries(name, home, shared=shared, recursive=True, runtime=False)
        if libs:
            return libs

    msg = "Unable to recursively locate {0} libraries in {1}"
    raise spack.error.NoLibrariesError(msg.format(spec.name, home))


class ForwardQueryToPackage:
    """Descriptor used to forward queries from Spec to Package"""

    def __init__(self, attribute_name, default_handler=None):
        """Create a new descriptor.

        Parameters:
            attribute_name (str): name of the attribute to be
                searched for in the Package instance
            default_handler (callable, optional): default function to be
                called if the attribute was not found in the Package
                instance
        """
        self.attribute_name = attribute_name
        self.default = default_handler

    def __get__(self, instance, cls):
        """Retrieves the property from Package using a well defined chain
        of responsibility.

        The order of call is:

        1. if the query was through the name of a virtual package try to
            search for the attribute `{virtual_name}_{attribute_name}`
            in Package

        2. try to search for attribute `{attribute_name}` in Package

        3. try to call the default handler

        The first call that produces a value will stop the chain.

        If no call can handle the request then AttributeError is raised with a
        message indicating that no relevant attribute exists.
        If a call returns None, an AttributeError is raised with a message
        indicating a query failure, e.g. that library files were not found in a
        'libs' query.
        """
        pkg = instance.package
        try:
            query = instance.last_query
        except AttributeError:
            # There has been no query yet: this means
            # a spec is trying to access its own attributes
            _ = instance[instance.name]  # NOQA: ignore=F841
            query = instance.last_query

        callbacks_chain = []
        # First in the chain : specialized attribute for virtual packages
        if query.isvirtual:
            specialized_name = "{0}_{1}".format(query.name, self.attribute_name)
            callbacks_chain.append(lambda: getattr(pkg, specialized_name))
        # Try to get the generic method from Package
        callbacks_chain.append(lambda: getattr(pkg, self.attribute_name))
        # Final resort : default callback
        if self.default is not None:
            callbacks_chain.append(lambda: self.default(self, instance, cls))

        # Trigger the callbacks in order, the first one producing a
        # value wins
        value = None
        message = None
        for f in callbacks_chain:
            try:
                value = f()
                # A callback can return None to trigger an error indicating
                # that the query failed.
                if value is None:
                    msg = "Query of package '{name}' for '{attrib}' failed\n"
                    msg += "\tprefix : {spec.prefix}\n"
                    msg += "\tspec : {spec}\n"
                    msg += "\tqueried as : {query.name}\n"
                    msg += "\textra parameters : {query.extra_parameters}"
                    message = msg.format(
                        name=pkg.name,
                        attrib=self.attribute_name,
                        spec=instance,
                        query=instance.last_query,
                    )
                else:
                    return value
                break
            except AttributeError:
                pass
        # value is 'None'
        if message is not None:
            # Here we can use another type of exception. If we do that, the
            # unit test 'test_getitem_exceptional_paths' in the file
            # lib/spack/spack/test/spec_dag.py will need to be updated to match
            # the type.
            raise AttributeError(message)
        # 'None' value at this point means that there are no appropriate
        # properties defined and no default handler, or that all callbacks
        # raised AttributeError. In this case, we raise AttributeError with an
        # appropriate message.
        fmt = "'{name}' package has no relevant attribute '{query}'\n"
        fmt += "\tspec : '{spec}'\n"
        fmt += "\tqueried as : '{spec.last_query.name}'\n"
        fmt += "\textra parameters : '{spec.last_query.extra_parameters}'\n"
        message = fmt.format(name=pkg.name, query=self.attribute_name, spec=instance)
        raise AttributeError(message)

    def __set__(self, instance, value):
        cls_name = type(instance).__name__
        msg = "'{0}' object attribute '{1}' is read-only"
        raise AttributeError(msg.format(cls_name, self.attribute_name))


# Represents a query state in a BuildInterface object
QueryState = collections.namedtuple("QueryState", ["name", "extra_parameters", "isvirtual"])


class SpecBuildInterface(lang.ObjectWrapper):
    # home is available in the base Package so no default is needed
    home = ForwardQueryToPackage("home", default_handler=None)

    command = ForwardQueryToPackage("command", default_handler=_command_default_handler)

    headers = ForwardQueryToPackage("headers", default_handler=_headers_default_handler)

    libs = ForwardQueryToPackage("libs", default_handler=_libs_default_handler)

    def __init__(self, spec, name, query_parameters):
        super().__init__(spec)
        # Adding new attributes goes after super() call since the ObjectWrapper
        # resets __dict__ to behave like the passed object
        original_spec = getattr(spec, "wrapped_obj", spec)
        self.wrapped_obj = original_spec
        self.token = original_spec, name, query_parameters
        is_virtual = spack.repo.PATH.is_virtual(name)
        self.last_query = QueryState(
            name=name, extra_parameters=query_parameters, isvirtual=is_virtual
        )

    def __reduce__(self):
        return SpecBuildInterface, self.token

    def copy(self, *args, **kwargs):
        return self.wrapped_obj.copy(*args, **kwargs)


@lang.lazy_lexicographic_ordering(set_hash=False)
class Spec:
    #: Cache for spec's prefix, computed lazily in the corresponding property
    _prefix = None
    abstract_hash = None

    @staticmethod
    def default_arch():
        """Return an anonymous spec for the default architecture"""
        s = Spec()
        s.architecture = ArchSpec.default_arch()
        return s

    def __init__(
        self,
        spec_like=None,
        normal=False,
        concrete=False,
        external_path=None,
        external_modules=None,
    ):
        """Create a new Spec.

        Arguments:
            spec_like (optional string): if not provided, we initialize
                an anonymous Spec that matches any Spec object; if
                provided we parse this as a Spec string.

        Keyword arguments:
        # assign special fields from constructor
        self._normal = normal
        self._concrete = concrete
        self.external_path = external_path
        self.external_module = external_module
        """
        # Copy if spec_like is a Spec.
        if isinstance(spec_like, Spec):
            self._dup(spec_like)
            return

        # init an empty spec that matches anything.
        self.name = None
        self.versions = vn.VersionList(":")
        self.variants = vt.VariantMap(self)
        self.architecture = None
        self.compiler = None
        self.compiler_flags = FlagMap(self)
        self._dependents = _EdgeMap(store_by=EdgeDirection.parent)
        self._dependencies = _EdgeMap(store_by=EdgeDirection.child)
        self.namespace = None

        # initial values for all spec hash types
        for h in ht.hashes:
            setattr(self, h.attr, None)

        # Python __hash__ is handled separately from the cached spec hashes
        self._dunder_hash = None

        # cache of package for this spec
        self._package = None

        # Most of these are internal implementation details that can be
        # set by internal Spack calls in the constructor.
        #
        # For example, Specs are by default not assumed to be normal, but
        # in some cases we've read them from a file want to assume
        # normal.  This allows us to manipulate specs that Spack doesn't
        # have package.py files for.
        self._normal = normal
        self._concrete = concrete
        self._external_path = external_path
        self.external_modules = Spec._format_module_list(external_modules)

        # This attribute is used to store custom information for
        # external specs. None signal that it was not set yet.
        self.extra_attributes = None

        # This attribute holds the original build copy of the spec if it is
        # deployed differently than it was built. None signals that the spec
        # is deployed "as built."
        # Build spec should be the actual build spec unless marked dirty.
        self._build_spec = None

        if isinstance(spec_like, str):
            spack.parser.parse_one_or_raise(spec_like, self)

        elif spec_like is not None:
            raise TypeError("Can't make spec out of %s" % type(spec_like))

    @staticmethod
    def _format_module_list(modules):
        """Return a module list that is suitable for YAML serialization
        and hash computation.

        Given a module list, possibly read from a configuration file,
        return an object that serializes to a consistent YAML string
        before/after round-trip serialization to/from a Spec dictionary
        (stored in JSON format): when read in, the module list may
        contain YAML formatting that is discarded (non-essential)
        when stored as a Spec dictionary; we take care in this function
        to discard such formatting such that the Spec hash does not
        change before/after storage in JSON.
        """
        if modules:
            modules = list(modules)
        return modules

    @property
    def external_path(self):
        return llnl.path.path_to_os_path(self._external_path)[0]

    @external_path.setter
    def external_path(self, ext_path):
        self._external_path = ext_path

    @property
    def external(self):
        return bool(self.external_path) or bool(self.external_modules)

    def clear_dependencies(self):
        """Trim the dependencies of this spec."""
        self._dependencies.clear()

    def clear_edges(self):
        """Trim the dependencies and dependents of this spec."""
        self._dependencies.clear()
        self._dependents.clear()

    def detach(self, deptype="all"):
        """Remove any reference that dependencies have of this node.

        Args:
            deptype (str or tuple): dependency types tracked by the
                current spec
        """
        key = self.dag_hash()
        # Go through the dependencies
        for dep in self.dependencies(deptype=deptype):
            # Remove the spec from dependents
            if self.name in dep._dependents:
                dependents_copy = dep._dependents.edges[self.name]
                del dep._dependents.edges[self.name]
                for edge in dependents_copy:
                    if edge.parent.dag_hash() == key:
                        continue
                    dep._dependents.add(edge)

    def _get_dependency(self, name):
        # WARNING: This function is an implementation detail of the
        # WARNING: original concretizer. Since with that greedy
        # WARNING: algorithm we don't allow multiple nodes from
        # WARNING: the same package in a DAG, here we hard-code
        # WARNING: using index 0 i.e. we assume that we have only
        # WARNING: one edge from package "name"
        deps = self.edges_to_dependencies(name=name)
        if len(deps) != 1:
            err_msg = 'expected only 1 "{0}" dependency, but got {1}'
            raise spack.error.SpecError(err_msg.format(name, len(deps)))
        return deps[0]

    def edges_from_dependents(self, name=None, depflag: dt.DepFlag = dt.ALL):
        """Return a list of edges connecting this node in the DAG
        to parents.

        Args:
            name (str): filter dependents by package name
            depflag: allowed dependency types
        """
        return [d for d in self._dependents.select(parent=name, depflag=depflag)]

    def edges_to_dependencies(self, name=None, depflag: dt.DepFlag = dt.ALL):
        """Return a list of edges connecting this node in the DAG
        to children.

        Args:
            name (str): filter dependencies by package name
            depflag: allowed dependency types
        """
        return [d for d in self._dependencies.select(child=name, depflag=depflag)]

    @property
    def edge_attributes(self) -> str:
        """Helper method to print edge attributes in spec literals"""
        edges = self.edges_from_dependents()
        if not edges:
            return ""

        union = DependencySpec(parent=Spec(), spec=self, depflag=0, virtuals=())
        for edge in edges:
            union.update_deptypes(edge.depflag)
            union.update_virtuals(edge.virtuals)
        deptypes_str = (
            f"deptypes={','.join(dt.flag_to_tuple(union.depflag))}" if union.depflag else ""
        )
        virtuals_str = f"virtuals={','.join(union.virtuals)}" if union.virtuals else ""
        if not deptypes_str and not virtuals_str:
            return ""
        result = f"{deptypes_str} {virtuals_str}".strip()
        return f"[{result}]"

    def dependencies(self, name=None, deptype: Union[dt.DepTypes, dt.DepFlag] = dt.ALL):
        """Return a list of direct dependencies (nodes in the DAG).

        Args:
            name (str): filter dependencies by package name
            deptype: allowed dependency types
        """
        if not isinstance(deptype, dt.DepFlag):
            deptype = dt.canonicalize(deptype)
        return [d.spec for d in self.edges_to_dependencies(name, depflag=deptype)]

    def dependents(self, name=None, deptype: Union[dt.DepTypes, dt.DepFlag] = dt.ALL):
        """Return a list of direct dependents (nodes in the DAG).

        Args:
            name (str): filter dependents by package name
            deptype: allowed dependency types
        """
        if not isinstance(deptype, dt.DepFlag):
            deptype = dt.canonicalize(deptype)
        return [d.parent for d in self.edges_from_dependents(name, depflag=deptype)]

    def _dependencies_dict(self, depflag: dt.DepFlag = dt.ALL):
        """Return a dictionary, keyed by package name, of the direct
        dependencies.

        Each value in the dictionary is a list of edges.

        Args:
            deptype: allowed dependency types
        """
        _sort_fn = lambda x: (x.spec.name, _sort_by_dep_types(x))
        _group_fn = lambda x: x.spec.name
        selected_edges = self._dependencies.select(depflag=depflag)
        result = {}
        for key, group in itertools.groupby(sorted(selected_edges, key=_sort_fn), key=_group_fn):
            result[key] = list(group)
        return result

    #
    # Private routines here are called by the parser when building a spec.
    #
    def _add_versions(self, version_list):
        """Called by the parser to add an allowable version."""
        # If it already has a non-trivial version list, this is an error
        if self.versions and self.versions != vn.any_version:
            raise MultipleVersionError(
                "A spec cannot contain multiple version signifiers." " Use a version list instead."
            )
        self.versions = vn.VersionList()
        for version in version_list:
            self.versions.add(version)

    def _add_flag(self, name, value, propagate):
        """Called by the parser to add a known flag.
        Known flags currently include "arch"
        """

        # If the == syntax is used to propagate the spec architecture
        # This is an error
        architecture_names = [
            "arch",
            "architecture",
            "platform",
            "os",
            "operating_system",
            "target",
        ]
        if propagate and name in architecture_names:
            raise ArchitecturePropagationError(
                "Unable to propagate the architecture failed." " Use a '=' instead."
            )

        valid_flags = FlagMap.valid_compiler_flags()
        if name == "arch" or name == "architecture":
            parts = tuple(value.split("-"))
            plat, os, tgt = parts if len(parts) == 3 else (None, None, value)
            self._set_architecture(platform=plat, os=os, target=tgt)
        elif name == "platform":
            self._set_architecture(platform=value)
        elif name == "os" or name == "operating_system":
            self._set_architecture(os=value)
        elif name == "target":
            self._set_architecture(target=value)
        elif name in valid_flags:
            assert self.compiler_flags is not None
            flags_and_propagation = spack.compiler.tokenize_flags(value, propagate)
            for flag, propagation in flags_and_propagation:
                self.compiler_flags.add_flag(name, flag, propagation)
        else:
            # FIXME:
            # All other flags represent variants. 'foo=true' and 'foo=false'
            # map to '+foo' and '~foo' respectively. As such they need a
            # BoolValuedVariant instance.
            if str(value).upper() == "TRUE" or str(value).upper() == "FALSE":
                self.variants[name] = vt.BoolValuedVariant(name, value, propagate)
            else:
                self.variants[name] = vt.AbstractVariant(name, value, propagate)

    def _set_architecture(self, **kwargs):
        """Called by the parser to set the architecture."""
        arch_attrs = ["platform", "os", "target"]
        if self.architecture and self.architecture.concrete:
            raise DuplicateArchitectureError(
                "Spec for '%s' cannot have two architectures." % self.name
            )

        if not self.architecture:
            new_vals = tuple(kwargs.get(arg, None) for arg in arch_attrs)
            self.architecture = ArchSpec(new_vals)
        else:
            new_attrvals = [(a, v) for a, v in kwargs.items() if a in arch_attrs]
            for new_attr, new_value in new_attrvals:
                if getattr(self.architecture, new_attr):
                    raise DuplicateArchitectureError(
                        "Spec for '%s' cannot have two '%s' specified "
                        "for its architecture" % (self.name, new_attr)
                    )
                else:
                    setattr(self.architecture, new_attr, new_value)

    def _set_compiler(self, compiler):
        """Called by the parser to set the compiler."""
        if self.compiler:
            raise DuplicateCompilerSpecError(
                "Spec for '%s' cannot have two compilers." % self.name
            )
        self.compiler = compiler

    def _add_dependency(self, spec: "Spec", *, depflag: dt.DepFlag, virtuals: Tuple[str, ...]):
        """Called by the parser to add another spec as a dependency."""
        if spec.name not in self._dependencies or not spec.name:
            self.add_dependency_edge(spec, depflag=depflag, virtuals=virtuals)
            return

        # Keep the intersection of constraints when a dependency is added
        # multiple times. Currently, we only allow identical edge types.
        orig = self._dependencies[spec.name]
        try:
            dspec = next(dspec for dspec in orig if depflag == dspec.depflag)
        except StopIteration:
            current_deps = ", ".join(
                dt.flag_to_chars(x.depflag) + " " + x.spec.short_spec for x in orig
            )
            raise DuplicateDependencyError(
                f"{self.short_spec} cannot depend on '{spec.short_spec}' multiple times.\n"
                f"\tRequired: {dt.flag_to_chars(depflag)}\n"
                f"\tDependency: {current_deps}"
            )

        try:
            dspec.spec.constrain(spec)
        except spack.error.UnsatisfiableSpecError:
            raise DuplicateDependencyError(
                f"Cannot depend on incompatible specs '{dspec.spec}' and '{spec}'"
            )

    def add_dependency_edge(
        self, dependency_spec: "Spec", *, depflag: dt.DepFlag, virtuals: Tuple[str, ...]
    ):
        """Add a dependency edge to this spec.

        Args:
            dependency_spec: spec of the dependency
            deptypes: dependency types for this edge
            virtuals: virtuals provided by this edge
        """
        # Check if we need to update edges that are already present
        selected = self._dependencies.select(child=dependency_spec.name)
        for edge in selected:
            has_errors, details = False, []
            msg = f"cannot update the edge from {edge.parent.name} to {edge.spec.name}"
            if edge.depflag & depflag:
                has_errors = True
                details.append(
                    (
                        f"{edge.parent.name} has already an edge matching any"
                        f" of these types {depflag}"
                    )
                )

            if any(v in edge.virtuals for v in virtuals):
                has_errors = True
                details.append(
                    (
                        f"{edge.parent.name} has already an edge matching any"
                        f" of these virtuals {virtuals}"
                    )
                )

            if has_errors:
                raise spack.error.SpecError(msg, "\n".join(details))

        for edge in selected:
            if id(dependency_spec) == id(edge.spec):
                # If we are here, it means the edge object was previously added to
                # both the parent and the child. When we update this object they'll
                # both see the deptype modification.
                edge.update_deptypes(depflag=depflag)
                edge.update_virtuals(virtuals=virtuals)
                return

        edge = DependencySpec(self, dependency_spec, depflag=depflag, virtuals=virtuals)
        self._dependencies.add(edge)
        dependency_spec._dependents.add(edge)

    #
    # Public interface
    #
    @property
    def fullname(self):
        return (
            ("%s.%s" % (self.namespace, self.name))
            if self.namespace
            else (self.name if self.name else "")
        )

    @property
    def anonymous(self):
        return not self.name and not self.abstract_hash

    @property
    def root(self):
        """Follow dependent links and find the root of this spec's DAG.

        Spack specs have a single root (the package being installed).
        """
        # FIXME: In the case of multiple parents this property does not
        # FIXME: make sense. Should we revisit the semantics?
        if not self._dependents:
            return self
        edges_by_package = next(iter(self._dependents.values()))
        return edges_by_package[0].parent.root

    @property
    def package(self):
        assert self.concrete, "{0}: Spec.package can only be called on concrete specs".format(
            self.name
        )
        if not self._package:
            self._package = spack.repo.PATH.get(self)
        return self._package

    @property
    def package_class(self):
        """Internal package call gets only the class object for a package.
        Use this to just get package metadata.
        """
        return spack.repo.PATH.get_pkg_class(self.fullname)

    @property
    def virtual(self):
        return spack.repo.PATH.is_virtual(self.name)

    @property
    def concrete(self):
        """A spec is concrete if it describes a single build of a package.

        More formally, a spec is concrete if concretize() has been called
        on it and it has been marked `_concrete`.

        Concrete specs either can be or have been built. All constraints
        have been resolved, optional dependencies have been added or
        removed, a compiler has been chosen, and all variants have
        values.
        """
        return self._concrete

    @property
    def spliced(self):
        """Returns whether or not this Spec is being deployed as built i.e.
        whether or not this Spec has ever been spliced.
        """
        return any(s.build_spec is not s for s in self.traverse(root=True))

    @property
    def installed(self):
        """Installation status of a package.

        Returns:
            True if the package has been installed, False otherwise.
        """
        if not self.concrete:
            return False

        try:
            # If the spec is in the DB, check the installed
            # attribute of the record
            return spack.store.STORE.db.get_record(self).installed
        except KeyError:
            # If the spec is not in the DB, the method
            #  above raises a Key error
            return False

    @property
    def installed_upstream(self):
        """Whether the spec is installed in an upstream repository.

        Returns:
            True if the package is installed in an upstream, False otherwise.
        """
        if not self.concrete:
            return False

        upstream, _ = spack.store.STORE.db.query_by_spec_hash(self.dag_hash())
        return upstream

    def traverse(self, **kwargs):
        """Shorthand for :meth:`~spack.traverse.traverse_nodes`"""
        return traverse.traverse_nodes([self], **kwargs)

    def traverse_edges(self, **kwargs):
        """Shorthand for :meth:`~spack.traverse.traverse_edges`"""
        return traverse.traverse_edges([self], **kwargs)

    @property
    def short_spec(self):
        """Returns a version of the spec with the dependencies hashed
        instead of completely enumerated."""
        spec_format = "{name}{@version}{%compiler.name}{@compiler.version}"
        spec_format += "{variants}{arch=architecture}{/hash:7}"
        return self.format(spec_format)

    @property
    def cshort_spec(self):
        """Returns an auto-colorized version of ``self.short_spec``."""
        spec_format = "{name}{@version}{%compiler.name}{@compiler.version}"
        spec_format += "{variants}{arch=architecture}{/hash:7}"
        return self.cformat(spec_format)

    @property
    def prefix(self):
        if not self._concrete:
            raise spack.error.SpecError("Spec is not concrete: " + str(self))

        if self._prefix is None:
            upstream, record = spack.store.STORE.db.query_by_spec_hash(self.dag_hash())
            if record and record.path:
                self.prefix = record.path
            else:
                self.prefix = spack.store.STORE.layout.path_for_spec(self)
        return self._prefix

    @prefix.setter
    def prefix(self, value):
        self._prefix = spack.util.prefix.Prefix(llnl.path.convert_to_platform_path(value))

    def spec_hash(self, hash):
        """Utility method for computing different types of Spec hashes.

        Arguments:
            hash (spack.hash_types.SpecHashDescriptor): type of hash to generate.
        """
        # TODO: currently we strip build dependencies by default.  Rethink
        # this when we move to using package hashing on all specs.
        if hash.override is not None:
            return hash.override(self)
        node_dict = self.to_node_dict(hash=hash)
        json_text = sjson.dump(node_dict)
        # This implements "frankenhashes", preserving the last 7 characters of the
        # original hash when splicing so that we can avoid relocation issues
        out = spack.util.hash.b32_hash(json_text)
        if self.build_spec is not self:
            return out[:-7] + self.build_spec.spec_hash(hash)[-7:]
        return out

    def _cached_hash(self, hash, length=None, force=False):
        """Helper function for storing a cached hash on the spec.

        This will run spec_hash() with the deptype and package_hash
        parameters, and if this spec is concrete, it will store the value
        in the supplied attribute on this spec.

        Arguments:
            hash (spack.hash_types.SpecHashDescriptor): type of hash to generate.
            length (int): length of hash prefix to return (default is full hash string)
            force (bool): cache the hash even if spec is not concrete (default False)
        """
        if not hash.attr:
            return self.spec_hash(hash)[:length]

        hash_string = getattr(self, hash.attr, None)
        if hash_string:
            return hash_string[:length]
        else:
            hash_string = self.spec_hash(hash)
            if force or self.concrete:
                setattr(self, hash.attr, hash_string)

            return hash_string[:length]

    def package_hash(self):
        """Compute the hash of the contents of the package for this node"""
        # Concrete specs with the old DAG hash did not have the package hash, so we do
        # not know what the package looked like at concretization time
        if self.concrete and not self._package_hash:
            raise ValueError(
                "Cannot call package_hash() on concrete specs with the old dag_hash()"
            )

        return self._cached_hash(ht.package_hash)

    def dag_hash(self, length=None):
        """This is Spack's default hash, used to identify installations.

        Same as the full hash (includes package hash and build/link/run deps).
        Tells us when package files and any dependencies have changes.

        NOTE: Versions of Spack prior to 0.18 only included link and run deps.

        """
        return self._cached_hash(ht.dag_hash, length)

    def process_hash(self, length=None):
        """Hash used to transfer specs among processes.

        This hash includes build and test dependencies and is only used to
        serialize a spec and pass it around among processes.
        """
        return self._cached_hash(ht.process_hash, length)

    def dag_hash_bit_prefix(self, bits):
        """Get the first <bits> bits of the DAG hash as an integer type."""
        return spack.util.hash.base32_prefix_bits(self.dag_hash(), bits)

    def process_hash_bit_prefix(self, bits):
        """Get the first <bits> bits of the DAG hash as an integer type."""
        return spack.util.hash.base32_prefix_bits(self.process_hash(), bits)

    def _lookup_hash(self):
        """Lookup just one spec with an abstract hash, returning a spec from the the environment,
        store, or finally, binary caches."""
        import spack.environment

        active_env = spack.environment.active_environment()

        # First env, then store, then binary cache
        matches = (
            (active_env.all_matching_specs(self) if active_env else [])
            or spack.store.STORE.db.query(self, installed=any)
            or spack.binary_distribution.BinaryCacheQuery(True)(self)
        )

        if not matches:
            raise InvalidHashError(self, self.abstract_hash)

        if len(matches) != 1:
            raise spack.spec.AmbiguousHashError(
                f"Multiple packages specify hash beginning '{self.abstract_hash}'.", *matches
            )

        return matches[0]

    def lookup_hash(self):
        """Given a spec with an abstract hash, return a copy of the spec with all properties and
        dependencies by looking up the hash in the environment, store, or finally, binary caches.
        This is non-destructive."""
        if self.concrete or not any(node.abstract_hash for node in self.traverse()):
            return self

        spec = self.copy(deps=False)
        # root spec is replaced
        if spec.abstract_hash:
            spec._dup(self._lookup_hash())
            return spec

        # Get dependencies that need to be replaced
        for node in self.traverse(root=False):
            if node.abstract_hash:
                spec._add_dependency(node._lookup_hash(), depflag=0, virtuals=())

        # reattach nodes that were not otherwise satisfied by new dependencies
        for node in self.traverse(root=False):
            if not any(n.satisfies(node) for n in spec.traverse()):
                spec._add_dependency(node.copy(), depflag=0, virtuals=())

        return spec

    def replace_hash(self):
        """Given a spec with an abstract hash, attempt to populate all properties and dependencies
        by looking up the hash in the environment, store, or finally, binary caches.
        This is destructive."""

        if not any(node for node in self.traverse(order="post") if node.abstract_hash):
            return

        self._dup(self.lookup_hash())

    def to_node_dict(self, hash=ht.dag_hash):
        """Create a dictionary representing the state of this Spec.

        ``to_node_dict`` creates the content that is eventually hashed by
        Spack to create identifiers like the DAG hash (see
        ``dag_hash()``).  Example result of ``to_node_dict`` for the
        ``sqlite`` package::

            {
                'sqlite': {
                    'version': '3.28.0',
                    'arch': {
                        'platform': 'darwin',
                        'platform_os': 'mojave',
                        'target': 'x86_64',
                    },
                    'compiler': {
                        'name': 'apple-clang',
                        'version': '10.0.0',
                    },
                    'namespace': 'builtin',
                    'parameters': {
                        'fts': 'true',
                        'functions': 'false',
                        'cflags': [],
                        'cppflags': [],
                        'cxxflags': [],
                        'fflags': [],
                        'ldflags': [],
                        'ldlibs': [],
                    },
                    'dependencies': {
                        'readline': {
                            'hash': 'zvaa4lhlhilypw5quj3akyd3apbq5gap',
                            'type': ['build', 'link'],
                        }
                    },
                }
            }

        Note that the dictionary returned does *not* include the hash of
        the *root* of the spec, though it does include hashes for each
        dependency, and (optionally) the package file corresponding to
        each node.

        See ``to_dict()`` for a "complete" spec hash, with hashes for
        each node and nodes for each dependency (instead of just their
        hashes).

        Arguments:
            hash (spack.hash_types.SpecHashDescriptor) type of hash to generate.
        """
        d = syaml.syaml_dict()

        d["name"] = self.name

        if self.versions:
            d.update(self.versions.to_dict())

        if self.architecture:
            d.update(self.architecture.to_dict())

        if self.compiler:
            d.update(self.compiler.to_dict())

        if self.namespace:
            d["namespace"] = self.namespace

        params = syaml.syaml_dict(sorted(v.yaml_entry() for _, v in self.variants.items()))

        # Only need the string compiler flag for yaml file
        params.update(
            sorted(
                self.compiler_flags.yaml_entry(flag_type)
                for flag_type in self.compiler_flags.keys()
            )
        )

        if params:
            d["parameters"] = params

        if self.external:
            d["external"] = syaml.syaml_dict(
                [
                    ("path", self.external_path),
                    ("module", self.external_modules),
                    ("extra_attributes", self.extra_attributes),
                ]
            )

        if not self._concrete:
            d["concrete"] = False

        if "patches" in self.variants:
            variant = self.variants["patches"]
            if hasattr(variant, "_patches_in_order_of_appearance"):
                d["patches"] = variant._patches_in_order_of_appearance

        if self._concrete and hash.package_hash and self._package_hash:
            # We use the attribute here instead of `self.package_hash()` because this
            # should *always* be assignhed at concretization time. We don't want to try
            # to compute a package hash for concrete spec where a) the package might not
            # exist, or b) the `dag_hash` didn't include the package hash when the spec
            # was concretized.
            package_hash = self._package_hash

            # Full hashes are in bytes
            if not isinstance(package_hash, str) and isinstance(package_hash, bytes):
                package_hash = package_hash.decode("utf-8")
            d["package_hash"] = package_hash

        # Note: Relies on sorting dict by keys later in algorithm.
        deps = self._dependencies_dict(depflag=hash.depflag)
        if deps:
            deps_list = []
            for name, edges_for_name in sorted(deps.items()):
                name_tuple = ("name", name)
                for dspec in edges_for_name:
                    hash_tuple = (hash.name, dspec.spec._cached_hash(hash))
                    parameters_tuple = (
                        "parameters",
                        syaml.syaml_dict(
                            (
                                ("deptypes", dt.flag_to_tuple(dspec.depflag)),
                                ("virtuals", dspec.virtuals),
                            )
                        ),
                    )
                    ordered_entries = [name_tuple, hash_tuple, parameters_tuple]
                    deps_list.append(syaml.syaml_dict(ordered_entries))
            d["dependencies"] = deps_list

        # Name is included in case this is replacing a virtual.
        if self._build_spec:
            d["build_spec"] = syaml.syaml_dict(
                [("name", self.build_spec.name), (hash.name, self.build_spec._cached_hash(hash))]
            )
        return d

    def to_dict(self, hash=ht.dag_hash):
        """Create a dictionary suitable for writing this spec to YAML or JSON.

        This dictionaries like the one that is ultimately written to a
        ``spec.json`` file in each Spack installation directory.  For
        example, for sqlite::

            {
            "spec": {
                "_meta": {
                "version": 2
                },
                "nodes": [
                {
                    "name": "sqlite",
                    "version": "3.34.0",
                    "arch": {
                    "platform": "darwin",
                    "platform_os": "catalina",
                    "target": "x86_64"
                    },
                    "compiler": {
                    "name": "apple-clang",
                    "version": "11.0.0"
                    },
                    "namespace": "builtin",
                    "parameters": {
                    "column_metadata": true,
                    "fts": true,
                    "functions": false,
                    "rtree": false,
                    "cflags": [],
                    "cppflags": [],
                    "cxxflags": [],
                    "fflags": [],
                    "ldflags": [],
                    "ldlibs": []
                    },
                    "dependencies": [
                    {
                        "name": "readline",
                        "hash": "4f47cggum7p4qmp3xna4hi547o66unva",
                        "type": [
                        "build",
                        "link"
                        ]
                    },
                    {
                        "name": "zlib",
                        "hash": "uvgh6p7rhll4kexqnr47bvqxb3t33jtq",
                        "type": [
                        "build",
                        "link"
                        ]
                    }
                    ],
                    "hash": "tve45xfqkfgmzwcyfetze2z6syrg7eaf",
                },
                    # ... more node dicts for readline and its dependencies ...
                ]
            }

        Note that this dictionary starts with the 'spec' key, and what
        follows is a list starting with the root spec, followed by its
        dependencies in preorder.  Each node in the list also has a
        'hash' key that contains the hash of the node *without* the hash
        field included.

        In the example, the package content hash is not included in the
        spec, but if ``package_hash`` were true there would be an
        additional field on each node called ``package_hash``.

        ``from_dict()`` can be used to read back in a spec that has been
        converted to a dictionary, serialized, and read back in.

        Arguments:
            deptype (tuple or str): dependency types to include when
                traversing the spec.
            package_hash (bool): whether to include package content
                hashes in the dictionary.

        """
        node_list = []  # Using a list to preserve preorder traversal for hash.
        hash_set = set()
        for s in self.traverse(order="pre", deptype=hash.depflag):
            spec_hash = s._cached_hash(hash)

            if spec_hash not in hash_set:
                node_list.append(s.node_dict_with_hashes(hash))
                hash_set.add(spec_hash)

            if s.build_spec is not s:
                build_spec_list = s.build_spec.to_dict(hash)["spec"]["nodes"]
                for node in build_spec_list:
                    node_hash = node[hash.name]
                    if node_hash not in hash_set:
                        node_list.append(node)
                        hash_set.add(node_hash)

        meta_dict = syaml.syaml_dict([("version", SPECFILE_FORMAT_VERSION)])
        inner_dict = syaml.syaml_dict([("_meta", meta_dict), ("nodes", node_list)])
        spec_dict = syaml.syaml_dict([("spec", inner_dict)])
        return spec_dict

    def node_dict_with_hashes(self, hash=ht.dag_hash):
        """Returns a node_dict of this spec with the dag hash added.  If this
        spec is concrete, the full hash is added as well.  If 'build' is in
        the hash_type, the build hash is also added."""
        node = self.to_node_dict(hash)
        node[ht.dag_hash.name] = self.dag_hash()

        # dag_hash is lazily computed -- but if we write a spec out, we want it
        # to be included. This is effectively the last chance we get to compute
        # it accurately.
        if self.concrete:
            # all specs have at least a DAG hash
            node[ht.dag_hash.name] = self.dag_hash()

        else:
            node["concrete"] = False

        # we can also give them other hash types if we want
        if hash.name != ht.dag_hash.name:
            node[hash.name] = self._cached_hash(hash)

        return node

    def to_yaml(self, stream=None, hash=ht.dag_hash):
        return syaml.dump(self.to_dict(hash), stream=stream, default_flow_style=False)

    def to_json(self, stream=None, hash=ht.dag_hash):
        return sjson.dump(self.to_dict(hash), stream)

    @staticmethod
    def from_specfile(path):
        """Construct a spec from a JSON or YAML spec file path"""
        with open(path, "r") as fd:
            file_content = fd.read()
            if path.endswith(".json"):
                return Spec.from_json(file_content)
            return Spec.from_yaml(file_content)

    @staticmethod
    def override(init_spec, change_spec):
        # TODO: this doesn't account for the case where the changed spec
        # (and the user spec) have dependencies
        new_spec = init_spec.copy()
        package_cls = spack.repo.PATH.get_pkg_class(new_spec.name)
        if change_spec.versions and not change_spec.versions == vn.any_version:
            new_spec.versions = change_spec.versions
        for variant, value in change_spec.variants.items():
            if variant in package_cls.variants:
                if variant in new_spec.variants:
                    new_spec.variants.substitute(value)
                else:
                    new_spec.variants[variant] = value
            else:
                raise ValueError("{0} is not a variant of {1}".format(variant, new_spec.name))
        if change_spec.compiler:
            new_spec.compiler = change_spec.compiler
        if change_spec.compiler_flags:
            for flagname, flagvals in change_spec.compiler_flags.items():
                new_spec.compiler_flags[flagname] = flagvals
        if change_spec.architecture:
            new_spec.architecture = ArchSpec.override(
                new_spec.architecture, change_spec.architecture
            )
        return new_spec

    @staticmethod
    def from_literal(spec_dict, normal=True):
        """Builds a Spec from a dictionary containing the spec literal.

        The dictionary must have a single top level key, representing the root,
        and as many secondary level keys as needed in the spec.

        The keys can be either a string or a Spec or a tuple containing the
        Spec and the dependency types.

        Args:
            spec_dict (dict): the dictionary containing the spec literal
            normal (bool): if True the same key appearing at different levels
                of the ``spec_dict`` will map to the same object in memory.

        Examples:
            A simple spec ``foo`` with no dependencies:

            .. code-block:: python

                {'foo': None}

            A spec ``foo`` with a ``(build, link)`` dependency ``bar``:

            .. code-block:: python

                {'foo':
                    {'bar:build,link': None}}

            A spec with a diamond dependency and various build types:

            .. code-block:: python

                {'dt-diamond': {
                    'dt-diamond-left:build,link': {
                        'dt-diamond-bottom:build': None
                    },
                    'dt-diamond-right:build,link': {
                        'dt-diamond-bottom:build,link,run': None
                    }
                }}

            The same spec with a double copy of ``dt-diamond-bottom`` and
            no diamond structure:

            .. code-block:: python

                {'dt-diamond': {
                    'dt-diamond-left:build,link': {
                        'dt-diamond-bottom:build': None
                    },
                    'dt-diamond-right:build,link': {
                        'dt-diamond-bottom:build,link,run': None
                    }
                }, normal=False}

            Constructing a spec using a Spec object as key:

            .. code-block:: python

                mpich = Spec('mpich')
                libelf = Spec('libelf@1.8.11')
                expected_normalized = Spec.from_literal({
                    'mpileaks': {
                        'callpath': {
                            'dyninst': {
                                'libdwarf': {libelf: None},
                                libelf: None
                            },
                            mpich: None
                        },
                        mpich: None
                    },
                })

        """

        # Maps a literal to a Spec, to be sure we are reusing the same object
        spec_cache = LazySpecCache()

        def spec_builder(d):
            # The invariant is that the top level dictionary must have
            # only one key
            assert len(d) == 1

            # Construct the top-level spec
            spec_like, dep_like = next(iter(d.items()))

            # If the requirements was for unique nodes (default)
            # then re-use keys from the local cache. Otherwise build
            # a new node every time.
            if not isinstance(spec_like, Spec):
                spec = spec_cache[spec_like] if normal else Spec(spec_like)
            else:
                spec = spec_like

            if dep_like is None:
                return spec

            def name_and_dependency_types(s: str) -> Tuple[str, dt.DepFlag]:
                """Given a key in the dictionary containing the literal,
                extracts the name of the spec and its dependency types.

                Args:
                    s: key in the dictionary containing the literal
                """
                t = s.split(":")

                if len(t) > 2:
                    msg = 'more than one ":" separator in key "{0}"'
                    raise KeyError(msg.format(s))

                name = t[0]
                if len(t) == 2:
                    depflag = dt.flag_from_strings(dep_str.strip() for dep_str in t[1].split(","))
                else:
                    depflag = 0
                return name, depflag

            def spec_and_dependency_types(
                s: Union[Spec, Tuple[Spec, str]]
            ) -> Tuple[Spec, dt.DepFlag]:
                """Given a non-string key in the literal, extracts the spec
                and its dependency types.

                Args:
                    s: either a Spec object, or a tuple of Spec and string of dependency types
                """
                if isinstance(s, Spec):
                    return s, 0

                spec_obj, dtypes = s
                return spec_obj, dt.flag_from_strings(dt.strip() for dt in dtypes.split(","))

            # Recurse on dependencies
            for s, s_dependencies in dep_like.items():
                if isinstance(s, str):
                    dag_node, dep_flag = name_and_dependency_types(s)
                else:
                    dag_node, dep_flag = spec_and_dependency_types(s)

                dependency_spec = spec_builder({dag_node: s_dependencies})
                spec._add_dependency(dependency_spec, depflag=dep_flag, virtuals=())

            return spec

        return spec_builder(spec_dict)

    @staticmethod
    def from_dict(data):
        """Construct a spec from JSON/YAML.

        Args:
            data: a nested dict/list data structure read from YAML or JSON.
        """
        # Legacy specfile format
        if isinstance(data["spec"], list):
            spec = SpecfileV1.load(data)
        elif int(data["spec"]["_meta"]["version"]) == 2:
            spec = SpecfileV2.load(data)
        elif int(data["spec"]["_meta"]["version"]) == 3:
            spec = SpecfileV3.load(data)
        else:
            spec = SpecfileV4.load(data)

        # Any git version should
        for s in spec.traverse():
            s.attach_git_version_lookup()

        return spec

    @staticmethod
    def from_yaml(stream):
        """Construct a spec from YAML.

        Args:
            stream: string or file object to read from.
        """
        data = syaml.load(stream)
        return Spec.from_dict(data)

    @staticmethod
    def from_json(stream):
        """Construct a spec from JSON.

        Args:
            stream: string or file object to read from.
        """
        try:
            data = sjson.load(stream)
            return Spec.from_dict(data)
        except Exception as e:
            raise sjson.SpackJSONError("error parsing JSON spec:", str(e)) from e

    @staticmethod
    def extract_json_from_clearsig(data):
        m = CLEARSIGN_FILE_REGEX.search(data)
        if m:
            return sjson.load(m.group(1))
        return sjson.load(data)

    @staticmethod
    def from_signed_json(stream):
        """Construct a spec from clearsigned json spec file.

        Args:
            stream: string or file object to read from.
        """
        data = stream
        if hasattr(stream, "read"):
            data = stream.read()

        extracted_json = Spec.extract_json_from_clearsig(data)
        return Spec.from_dict(extracted_json)

    @staticmethod
    def from_detection(spec_str, extra_attributes=None):
        """Construct a spec from a spec string determined during external
        detection and attach extra attributes to it.

        Args:
            spec_str (str): spec string
            extra_attributes (dict): dictionary containing extra attributes

        Returns:
            spack.spec.Spec: external spec
        """
        s = Spec(spec_str)
        extra_attributes = syaml.sorted_dict(extra_attributes or {})
        # This is needed to be able to validate multi-valued variants,
        # otherwise they'll still be abstract in the context of detection.
        vt.substitute_abstract_variants(s)
        s.extra_attributes = extra_attributes
        return s

    def validate_detection(self):
        """Validate the detection of an external spec.

        This method is used as part of Spack's detection protocol, and is
        not meant for client code use.
        """
        # Assert that _extra_attributes is a Mapping and not None,
        # which likely means the spec was created with Spec.from_detection
        msg = 'cannot validate "{0}" since it was not created ' "using Spec.from_detection".format(
            self
        )
        assert isinstance(self.extra_attributes, collections.abc.Mapping), msg

        # Validate the spec calling a package specific method
        pkg_cls = spack.repo.PATH.get_pkg_class(self.name)
        validate_fn = getattr(pkg_cls, "validate_detected_spec", lambda x, y: None)
        validate_fn(self, self.extra_attributes)

    def _concretize_helper(self, concretizer, presets=None, visited=None):
        """Recursive helper function for concretize().
        This concretizes everything bottom-up.  As things are
        concretized, they're added to the presets, and ancestors
        will prefer the settings of their children.
        """
        if presets is None:
            presets = {}
        if visited is None:
            visited = set()

        if self.name in visited:
            return False

        if self.concrete:
            visited.add(self.name)
            return False

        changed = False

        # Concretize deps first -- this is a bottom-up process.
        for name in sorted(self._dependencies):
            # WARNING: This function is an implementation detail of the
            # WARNING: original concretizer. Since with that greedy
            # WARNING: algorithm we don't allow multiple nodes from
            # WARNING: the same package in a DAG, here we hard-code
            # WARNING: using index 0 i.e. we assume that we have only
            # WARNING: one edge from package "name"
            changed |= self._dependencies[name][0].spec._concretize_helper(
                concretizer, presets, visited
            )

        if self.name in presets:
            changed |= self.constrain(presets[self.name])
        else:
            # Concretize virtual dependencies last.  Because they're added
            # to presets below, their constraints will all be merged, but we'll
            # still need to select a concrete package later.
            if not self.virtual:
                changed |= any(
                    (
                        concretizer.concretize_develop(self),  # special variant
                        concretizer.concretize_architecture(self),
                        concretizer.concretize_compiler(self),
                        concretizer.adjust_target(self),
                        # flags must be concretized after compiler
                        concretizer.concretize_compiler_flags(self),
                        concretizer.concretize_version(self),
                        concretizer.concretize_variants(self),
                    )
                )
            presets[self.name] = self

        visited.add(self.name)
        return changed

    def _replace_with(self, concrete):
        """Replace this virtual spec with a concrete spec."""
        assert self.virtual
        virtuals = (self.name,)
        for dep_spec in itertools.chain.from_iterable(self._dependents.values()):
            dependent = dep_spec.parent
            depflag = dep_spec.depflag

            # remove self from all dependents, unless it is already removed
            if self.name in dependent._dependencies:
                del dependent._dependencies.edges[self.name]

            # add the replacement, unless it is already a dep of dependent.
            if concrete.name not in dependent._dependencies:
                dependent._add_dependency(concrete, depflag=depflag, virtuals=virtuals)
            else:
                dependent.edges_to_dependencies(name=concrete.name)[0].update_virtuals(
                    virtuals=virtuals
                )

    def _expand_virtual_packages(self, concretizer):
        """Find virtual packages in this spec, replace them with providers,
        and normalize again to include the provider's (potentially virtual)
        dependencies.  Repeat until there are no virtual deps.

        Precondition: spec is normalized.

        .. todo::

           If a provider depends on something that conflicts with
           other dependencies in the spec being expanded, this can
           produce a conflicting spec.  For example, if mpich depends
           on hwloc@:1.3 but something in the spec needs hwloc1.4:,
           then we should choose an MPI other than mpich.  Cases like
           this are infrequent, but should implement this before it is
           a problem.
        """
        # Make an index of stuff this spec already provides
        self_index = spack.provider_index.ProviderIndex(
            repository=spack.repo.PATH, specs=self.traverse(), restrict=True
        )
        changed = False
        done = False

        while not done:
            done = True
            for spec in list(self.traverse()):
                replacement = None
                if spec.external:
                    continue
                if spec.virtual:
                    replacement = self._find_provider(spec, self_index)
                    if replacement:
                        # TODO: may break if in-place on self but
                        # shouldn't happen if root is traversed first.
                        spec._replace_with(replacement)
                        done = False
                        break

                if not replacement:
                    # Get a list of possible replacements in order of
                    # preference.
                    candidates = concretizer.choose_virtual_or_external(spec)

                    # Try the replacements in order, skipping any that cause
                    # satisfiability problems.
                    for replacement in candidates:
                        if replacement is spec:
                            break

                        # Replace spec with the candidate and normalize
                        copy = self.copy()
                        copy[spec.name]._dup(replacement, deps=False)

                        try:
                            # If there are duplicate providers or duplicate
                            # provider deps, consolidate them and merge
                            # constraints.
                            copy.normalize(force=True)
                            break
                        except spack.error.SpecError:
                            # On error, we'll try the next replacement.
                            continue

                # If replacement is external then trim the dependencies
                if replacement.external:
                    if spec._dependencies:
                        for dep in spec.dependencies():
                            del dep._dependents.edges[spec.name]
                        changed = True
                        spec.clear_dependencies()
                    replacement.clear_dependencies()
                    replacement.architecture = self.architecture

                # TODO: could this and the stuff in _dup be cleaned up?
                def feq(cfield, sfield):
                    return (not cfield) or (cfield == sfield)

                if replacement is spec or (
                    feq(replacement.name, spec.name)
                    and feq(replacement.versions, spec.versions)
                    and feq(replacement.compiler, spec.compiler)
                    and feq(replacement.architecture, spec.architecture)
                    and feq(replacement._dependencies, spec._dependencies)
                    and feq(replacement.variants, spec.variants)
                    and feq(replacement.external_path, spec.external_path)
                    and feq(replacement.external_modules, spec.external_modules)
                ):
                    continue
                # Refine this spec to the candidate. This uses
                # replace_with AND dup so that it can work in
                # place. TODO: make this more efficient.
                if spec.virtual:
                    spec._replace_with(replacement)
                    changed = True
                if spec._dup(replacement, deps=False, cleardeps=False):
                    changed = True

                self_index.update(spec)
                done = False
                break

        return changed

    def _old_concretize(self, tests=False, deprecation_warning=True):
        """A spec is concrete if it describes one build of a package uniquely.
        This will ensure that this spec is concrete.

        Args:
            tests (list or bool): list of packages that will need test
                dependencies, or True/False for test all/none
            deprecation_warning (bool): enable or disable the deprecation
                warning for the old concretizer

        If this spec could describe more than one version, variant, or build
        of a package, this will add constraints to make it concrete.

        Some rigorous validation and checks are also performed on the spec.
        Concretizing ensures that it is self-consistent and that it's
        consistent with requirements of its packages. See flatten() and
        normalize() for more details on this.
        """
        import spack.concretize

        # Add a warning message to inform users that the original concretizer
        # will be removed
        if deprecation_warning:
            msg = (
                "the original concretizer is currently being used.\n\tUpgrade to "
                '"clingo" at your earliest convenience. The original concretizer '
                "will be removed from Spack in a future version."
            )
            warnings.warn(msg)

        self.replace_hash()

        if not self.name:
            raise spack.error.SpecError("Attempting to concretize anonymous spec")

        if self._concrete:
            return

        changed = True
        force = False

        user_spec_deps = self.flat_dependencies(copy=False)
        concretizer = spack.concretize.Concretizer(self.copy())
        while changed:
            changes = (
                self.normalize(force, tests=tests, user_spec_deps=user_spec_deps),
                self._expand_virtual_packages(concretizer),
                self._concretize_helper(concretizer),
            )
            changed = any(changes)
            force = True

        visited_user_specs = set()
        for dep in self.traverse():
            visited_user_specs.add(dep.name)
            pkg_cls = spack.repo.PATH.get_pkg_class(dep.name)
            visited_user_specs.update(x.name for x in pkg_cls(dep).provided)

        extra = set(user_spec_deps.keys()).difference(visited_user_specs)
        if extra:
            raise InvalidDependencyError(self.name, extra)

        Spec.inject_patches_variant(self)

        for s in self.traverse():
            # TODO: Refactor this into a common method to build external specs
            # TODO: or turn external_path into a lazy property
            Spec.ensure_external_path_if_external(s)

        # assign hashes and mark concrete
        self._finalize_concretization()

        # If any spec in the DAG is deprecated, throw an error
        Spec.ensure_no_deprecated(self)

        # Update externals as needed
        for dep in self.traverse():
            if dep.external:
                dep.package.update_external_dependencies()

        # Now that the spec is concrete we should check if
        # there are declared conflicts
        #
        # TODO: this needs rethinking, as currently we can only express
        # TODO: internal configuration conflicts within one package.
        matches = []
        for x in self.traverse():
            if x.external:
                # external specs are already built, don't worry about whether
                # it's possible to build that configuration with Spack
                continue
            for conflict_spec, when_list in x.package_class.conflicts.items():
                if x.satisfies(conflict_spec):
                    for when_spec, msg in when_list:
                        if x.satisfies(when_spec):
                            when = when_spec.copy()
                            when.name = x.name
                            matches.append((x, conflict_spec, when, msg))
        if matches:
            raise ConflictsInSpecError(self, matches)

        # Check if we can produce an optimized binary (will throw if
        # there are declared inconsistencies)
        # No need on platform=cray because of the targeting modules
        if not self.satisfies("platform=cray"):
            self.architecture.target.optimization_flags(self.compiler)

    def _patches_assigned(self):
        """Whether patches have been assigned to this spec by the concretizer."""
        # FIXME: _patches_in_order_of_appearance is attached after concretization
        # FIXME: to store the order of patches.
        # FIXME: Probably needs to be refactored in a cleaner way.
        if "patches" not in self.variants:
            return False

        # ensure that patch state is consistent
        patch_variant = self.variants["patches"]
        assert hasattr(
            patch_variant, "_patches_in_order_of_appearance"
        ), "patches should always be assigned with a patch variant."

        return True

    @staticmethod
    def inject_patches_variant(root):
        # This dictionary will store object IDs rather than Specs as keys
        # since the Spec __hash__ will change as patches are added to them
        spec_to_patches = {}
        for s in root.traverse():
            # After concretizing, assign namespaces to anything left.
            # Note that this doesn't count as a "change".  The repository
            # configuration is constant throughout a spack run, and
            # normalize and concretize evaluate Packages using Repo.get(),
            # which respects precedence.  So, a namespace assignment isn't
            # changing how a package name would have been interpreted and
            # we can do it as late as possible to allow as much
            # compatibility across repositories as possible.
            if s.namespace is None:
                s.namespace = spack.repo.PATH.repo_for_pkg(s.name).namespace

            if s.concrete:
                continue

            # Add any patches from the package to the spec.
            patches = []
            for cond, patch_list in s.package_class.patches.items():
                if s.satisfies(cond):
                    for patch in patch_list:
                        patches.append(patch)
            if patches:
                spec_to_patches[id(s)] = patches
        # Also record all patches required on dependencies by
        # depends_on(..., patch=...)
        for dspec in root.traverse_edges(deptype=all, cover="edges", root=False):
            if dspec.spec.concrete:
                continue

            pkg_deps = dspec.parent.package_class.dependencies
            if dspec.spec.name not in pkg_deps:
                continue

            patches = []
            for cond, dependency in pkg_deps[dspec.spec.name].items():
                for pcond, patch_list in dependency.patches.items():
                    if dspec.parent.satisfies(cond) and dspec.spec.satisfies(pcond):
                        patches.extend(patch_list)
            if patches:
                all_patches = spec_to_patches.setdefault(id(dspec.spec), [])
                all_patches.extend(patches)
        for spec in root.traverse():
            if id(spec) not in spec_to_patches:
                continue

            patches = list(lang.dedupe(spec_to_patches[id(spec)]))
            mvar = spec.variants.setdefault("patches", vt.MultiValuedVariant("patches", ()))
            mvar.value = tuple(p.sha256 for p in patches)
            # FIXME: Monkey patches mvar to store patches order
            full_order_keys = list(tuple(p.ordering_key) + (p.sha256,) for p in patches)
            ordered_hashes = sorted(full_order_keys)
            tty.debug(
                "Ordered hashes [{0}]: ".format(spec.name)
                + ", ".join("/".join(str(e) for e in t) for t in ordered_hashes)
            )
            mvar._patches_in_order_of_appearance = list(t[-1] for t in ordered_hashes)

    @staticmethod
    def ensure_external_path_if_external(external_spec):
        if external_spec.external_modules and not external_spec.external_path:
            compiler = spack.compilers.compiler_for_spec(
                external_spec.compiler, external_spec.architecture
            )
            for mod in compiler.modules:
                md.load_module(mod)

            # Get the path from the module the package can override the default
            # (this is mostly needed for Cray)
            pkg_cls = spack.repo.PATH.get_pkg_class(external_spec.name)
            package = pkg_cls(external_spec)
            external_spec.external_path = getattr(
                package, "external_prefix", md.path_from_modules(external_spec.external_modules)
            )

    @staticmethod
    def ensure_no_deprecated(root):
        """Raise if a deprecated spec is in the dag.

        Args:
            root (Spec): root spec to be analyzed

        Raises:
            SpecDeprecatedError: if any deprecated spec is found
        """
        deprecated = []
        with spack.store.STORE.db.read_transaction():
            for x in root.traverse():
                _, rec = spack.store.STORE.db.query_by_spec_hash(x.dag_hash())
                if rec and rec.deprecated_for:
                    deprecated.append(rec)
        if deprecated:
            msg = "\n    The following specs have been deprecated"
            msg += " in favor of specs with the hashes shown:\n"
            for rec in deprecated:
                msg += "        %s  --> %s\n" % (rec.spec, rec.deprecated_for)
            msg += "\n"
            msg += "    For each package listed, choose another spec\n"
            raise SpecDeprecatedError(msg)

    def _new_concretize(self, tests=False):
        import spack.solver.asp

        self.replace_hash()

        for node in self.traverse():
            if not node.name:
                raise spack.error.SpecError(
                    f"Spec {node} has no name; cannot concretize an anonymous spec"
                )

        if self._concrete:
            return

        allow_deprecated = spack.config.get("config:deprecated", False)
        solver = spack.solver.asp.Solver()
        result = solver.solve([self], tests=tests, allow_deprecated=allow_deprecated)
        result.raise_if_unsat()

        # take the best answer
        opt, i, answer = min(result.answers)
        name = self.name
        # TODO: Consolidate this code with similar code in solve.py
        if self.virtual:
            providers = [spec.name for spec in answer.values() if spec.package.provides(name)]
            name = providers[0]

        node = spack.solver.asp.SpecBuilder.make_node(pkg=name)
        assert (
            node in answer
        ), f"cannot find {name} in the list of specs {','.join([n.pkg for n in answer.keys()])}"

        concretized = answer[node]
        self._dup(concretized)

    def concretize(self, tests=False):
        """Concretize the current spec.

        Args:
            tests (bool or list): if False disregard 'test' dependencies,
                if a list of names activate them for the packages in the list,
                if True activate 'test' dependencies for all packages.
        """
        if spack.config.get("config:concretizer", "clingo") == "clingo":
            self._new_concretize(tests)
        else:
            self._old_concretize(tests)

    def _mark_root_concrete(self, value=True):
        """Mark just this spec (not dependencies) concrete."""
        if (not value) and self.concrete and self.installed:
            return
        self._normal = value
        self._concrete = value
        self._validate_version()

    def _validate_version(self):
        # Specs that were concretized with just a git sha as version, without associated
        # Spack version, get their Spack version mapped to develop. This should only apply
        # when reading specs concretized with Spack 0.19 or earlier. Currently Spack always
        # ensures that GitVersion specs have an associated Spack version.
        v = self.versions.concrete
        if not isinstance(v, vn.GitVersion):
            return

        try:
            v.ref_version
        except vn.VersionLookupError:
            before = self.cformat("{name}{@version}{/hash:7}")
            v._ref_version = vn.StandardVersion.from_string("develop")
            tty.debug(
                f"the git sha of {before} could not be resolved to spack version; "
                f"it has been replaced by {self.cformat('{name}{@version}{/hash:7}')}."
            )

    def _mark_concrete(self, value=True):
        """Mark this spec and its dependencies as concrete.

        Only for internal use -- client code should use "concretize"
        unless there is a need to force a spec to be concrete.
        """
        # if set to false, clear out all hashes (set to None or remove attr)
        # may need to change references to respect None
        for s in self.traverse():
            if (not value) and s.concrete and s.installed:
                continue
            elif not value:
                s.clear_cached_hashes()
            s._mark_root_concrete(value)

    def _finalize_concretization(self):
        """Assign hashes to this spec, and mark it concrete.

        There are special semantics to consider for `package_hash`, because we can't
        call it on *already* concrete specs, but we need to assign it *at concretization
        time* to just-concretized specs. So, the concretizer must assign the package
        hash *before* marking their specs concrete (so that we know which specs were
        already concrete before this latest concretization).

        `dag_hash` is also tricky, since it cannot compute `package_hash()` lazily.
        Because `package_hash` needs to be assigned *at concretization time*,
        `to_node_dict()` can't just assume that it can compute `package_hash` itself
        -- it needs to either see or not see a `_package_hash` attribute.

        Rules of thumb for `package_hash`:
          1. Old-style concrete specs from *before* `dag_hash` included `package_hash`
             will not have a `_package_hash` attribute at all.
          2. New-style concrete specs will have a `_package_hash` assigned at
             concretization time.
          3. Abstract specs will not have a `_package_hash` attribute at all.

        """
        for spec in self.traverse():
            # Already concrete specs either already have a package hash (new dag_hash())
            # or they never will b/c we can't know it (old dag_hash()). Skip them.
            #
            # We only assign package hash to not-yet-concrete specs, for which we know
            # we can compute the hash.
            if not spec.concrete:
                # we need force=True here because package hash assignment has to happen
                # before we mark concrete, so that we know what was *already* concrete.
                spec._cached_hash(ht.package_hash, force=True)

                # keep this check here to ensure package hash is saved
                assert getattr(spec, ht.package_hash.attr)

        # Mark everything in the spec as concrete
        self._mark_concrete()

        # Assign dag_hash (this *could* be done lazily, but it's assigned anyway in
        # ensure_no_deprecated, and it's clearer to see explicitly where it happens).
        # Any specs that were concrete before finalization will already have a cached
        # DAG hash.
        for spec in self.traverse():
            spec._cached_hash(ht.dag_hash)

    def concretized(self, tests=False):
        """This is a non-destructive version of concretize().

        First clones, then returns a concrete version of this package
        without modifying this package.

        Args:
            tests (bool or list): if False disregard 'test' dependencies,
                if a list of names activate them for the packages in the list,
                if True activate 'test' dependencies for all packages.
        """
        clone = self.copy()
        clone.concretize(tests=tests)
        return clone

    def flat_dependencies(self, **kwargs):
        """Return a DependencyMap containing all of this spec's
        dependencies with their constraints merged.

        If copy is True, returns merged copies of its dependencies
        without modifying the spec it's called on.

        If copy is False, clears this spec's dependencies and
        returns them. This disconnects all dependency links including
        transitive dependencies, except for concrete specs: if a spec
        is concrete it will not be disconnected from its dependencies
        (although a non-concrete spec with concrete dependencies will
        be disconnected from those dependencies).
        """
        copy = kwargs.get("copy", True)

        flat_deps = {}
        try:
            deptree = self.traverse(root=False)
            for spec in deptree:
                if spec.name not in flat_deps:
                    if copy:
                        spec = spec.copy(deps=False)
                    flat_deps[spec.name] = spec
                else:
                    flat_deps[spec.name].constrain(spec)

            if not copy:
                for spec in flat_deps.values():
                    if not spec.concrete:
                        spec.clear_edges()
                self.clear_dependencies()

            return flat_deps

        except spack.error.UnsatisfiableSpecError as e:
            # Here, the DAG contains two instances of the same package
            # with inconsistent constraints.
            raise InconsistentSpecError("Invalid Spec DAG: %s" % e.message) from e

    def index(self, deptype="all"):
        """Return a dictionary that points to all the dependencies in this
        spec.
        """
        dm = collections.defaultdict(list)
        for spec in self.traverse(deptype=deptype):
            dm[spec.name].append(spec)
        return dm

    def _evaluate_dependency_conditions(self, name):
        """Evaluate all the conditions on a dependency with this name.

        Args:
            name (str): name of dependency to evaluate conditions on.

        Returns:
            (Dependency): new Dependency object combining all constraints.

        If the package depends on <name> in the current spec
        configuration, return the constrained dependency and
        corresponding dependency types.

        If no conditions are True (and we don't depend on it), return
        ``(None, None)``.
        """
        conditions = self.package_class.dependencies[name]

        vt.substitute_abstract_variants(self)
        # evaluate when specs to figure out constraints on the dependency.
        dep = None
        for when_spec, dependency in conditions.items():
            if self.satisfies(when_spec):
                if dep is None:
                    dep = dp.Dependency(self.name, Spec(name), depflag=0)
                try:
                    dep.merge(dependency)
                except spack.error.UnsatisfiableSpecError as e:
                    e.message = (
                        "Conflicting conditional dependencies for spec"
                        "\n\n\t{0}\n\n"
                        "Cannot merge constraint"
                        "\n\n\t{1}\n\n"
                        "into"
                        "\n\n\t{2}".format(self, dependency.spec, dep.spec)
                    )
                    raise e

        return dep

    def _find_provider(self, vdep, provider_index):
        """Find provider for a virtual spec in the provider index.
        Raise an exception if there is a conflicting virtual
        dependency already in this spec.
        """
        assert spack.repo.PATH.is_virtual_safe(vdep.name), vdep

        # note that this defensively copies.
        providers = provider_index.providers_for(vdep)

        # If there is a provider for the vpkg, then use that instead of
        # the virtual package.
        if providers:
            # Remove duplicate providers that can concretize to the same
            # result.
            for provider in providers:
                for spec in providers:
                    if spec is not provider and provider.intersects(spec):
                        providers.remove(spec)
            # Can't have multiple providers for the same thing in one spec.
            if len(providers) > 1:
                raise MultipleProviderError(vdep, providers)
            return providers[0]
        else:
            # The user might have required something insufficient for
            # pkg_dep -- so we'll get a conflict.  e.g., user asked for
            # mpi@:1.1 but some package required mpi@2.1:.
            required = provider_index.providers_for(vdep.name)
            if len(required) > 1:
                raise MultipleProviderError(vdep, required)
            elif required:
                raise UnsatisfiableProviderSpecError(required[0], vdep)

    def _merge_dependency(self, dependency, visited, spec_deps, provider_index, tests):
        """Merge dependency information from a Package into this Spec.

        Args:
            dependency (Dependency): dependency metadata from a package;
                this is typically the result of merging *all* matching
                dependency constraints from the package.
            visited (set): set of dependency nodes already visited by
                ``normalize()``.
            spec_deps (dict): ``dict`` of all dependencies from the spec
                being normalized.
            provider_index (dict): ``provider_index`` of virtual dep
                providers in the ``Spec`` as normalized so far.

        NOTE: Caller should assume that this routine owns the
        ``dependency`` parameter, i.e., it needs to be a copy of any
        internal structures.

        This is the core of ``normalize()``.  There are some basic steps:

          * If dep is virtual, evaluate whether it corresponds to an
            existing concrete dependency, and merge if so.

          * If it's real and it provides some virtual dep, see if it provides
            what some virtual dependency wants and merge if so.

          * Finally, if none of the above, merge dependency and its
            constraints into this spec.

        This method returns True if the spec was changed, False otherwise.

        """
        changed = False
        dep = dependency.spec

        # If it's a virtual dependency, try to find an existing
        # provider in the spec, and merge that.
        virtuals = ()
        if spack.repo.PATH.is_virtual_safe(dep.name):
            virtuals = (dep.name,)
            visited.add(dep.name)
            provider = self._find_provider(dep, provider_index)
            if provider:
                dep = provider
        else:
            index = spack.provider_index.ProviderIndex(
                repository=spack.repo.PATH, specs=[dep], restrict=True
            )
            items = list(spec_deps.items())
            for name, vspec in items:
                if not spack.repo.PATH.is_virtual_safe(vspec.name):
                    continue

                if index.providers_for(vspec):
                    vspec._replace_with(dep)
                    del spec_deps[vspec.name]
                    changed = True
                else:
                    required = index.providers_for(vspec.name)
                    if required:
                        raise UnsatisfiableProviderSpecError(required[0], dep)
            provider_index.update(dep)

        # If the spec isn't already in the set of dependencies, add it.
        # Note: dep is always owned by this method. If it's from the
        # caller, it's a copy from _evaluate_dependency_conditions. If it
        # comes from a vdep, it's a defensive copy from _find_provider.
        if dep.name not in spec_deps:
            if self.concrete:
                return False

            spec_deps[dep.name] = dep
            changed = True
        else:
            # merge package/vdep information into spec
            try:
                tty.debug("{0} applying constraint {1}".format(self.name, str(dep)))
                changed |= spec_deps[dep.name].constrain(dep)
            except spack.error.UnsatisfiableSpecError as e:
                fmt = "An unsatisfiable {0}".format(e.constraint_type)
                fmt += " constraint has been detected for spec:"
                fmt += "\n\n{0}\n\n".format(spec_deps[dep.name].tree(indent=4))
                fmt += "while trying to concretize the partial spec:"
                fmt += "\n\n{0}\n\n".format(self.tree(indent=4))
                fmt += "{0} requires {1} {2} {3}, but spec asked for {4}"

                e.message = fmt.format(
                    self.name, dep.name, e.constraint_type, e.required, e.provided
                )

                raise

        # Add merged spec to my deps and recurse
        spec_dependency = spec_deps[dep.name]
        if dep.name not in self._dependencies:
            self._add_dependency(spec_dependency, depflag=dependency.depflag, virtuals=virtuals)

        changed |= spec_dependency._normalize_helper(visited, spec_deps, provider_index, tests)
        return changed

    def _normalize_helper(self, visited, spec_deps, provider_index, tests):
        """Recursive helper function for _normalize."""
        if self.name in visited:
            return False
        visited.add(self.name)

        # If we descend into a virtual spec, there's nothing more
        # to normalize.  Concretize will finish resolving it later.
        if self.virtual or self.external:
            return False

        # Avoid recursively adding constraints for already-installed packages:
        # these may include build dependencies which are not needed for this
        # install (since this package is already installed).
        if self.concrete and self.installed:
            return False

        # Combine constraints from package deps with constraints from
        # the spec, until nothing changes.
        any_change = False
        changed = True

        while changed:
            changed = False
            for dep_name in self.package_class.dependencies:
                # Do we depend on dep_name?  If so pkg_dep is not None.
                dep = self._evaluate_dependency_conditions(dep_name)

                # If dep is a needed dependency, merge it.
                if dep:
                    merge = (
                        # caller requested test dependencies
                        tests is True
                        or (tests and self.name in tests)
                        or
                        # this is not a test-only dependency
                        (dep.depflag & ~dt.TEST)
                    )

                    if merge:
                        changed |= self._merge_dependency(
                            dep, visited, spec_deps, provider_index, tests
                        )
            any_change |= changed

        return any_change

    def normalize(self, force=False, tests=False, user_spec_deps=None):
        """When specs are parsed, any dependencies specified are hanging off
        the root, and ONLY the ones that were explicitly provided are there.
        Normalization turns a partial flat spec into a DAG, where:

        1. Known dependencies of the root package are in the DAG.
        2. Each node's dependencies dict only contains its known direct
           deps.
        3. There is only ONE unique spec for each package in the DAG.

           * This includes virtual packages.  If there a non-virtual
             package that provides a virtual package that is in the spec,
             then we replace the virtual package with the non-virtual one.

        TODO: normalize should probably implement some form of cycle
        detection, to ensure that the spec is actually a DAG.
        """
        if not self.name:
            raise spack.error.SpecError("Attempting to normalize anonymous spec")

        # Set _normal and _concrete to False when forced
        if force and not self._concrete:
            self._normal = False

        if self._normal:
            return False

        # Ensure first that all packages & compilers in the DAG exist.
        self.validate_or_raise()
        # Clear the DAG and collect all dependencies in the DAG, which will be
        # reapplied as constraints. All dependencies collected this way will
        # have been created by a previous execution of 'normalize'.
        # A dependency extracted here will only be reintegrated if it is
        # discovered to apply according to _normalize_helper, so
        # user-specified dependencies are recorded separately in case they
        # refer to specs which take several normalization passes to
        # materialize.
        all_spec_deps = self.flat_dependencies(copy=False)

        if user_spec_deps:
            for name, spec in user_spec_deps.items():
                if not name:
                    msg = "Attempted to normalize anonymous dependency spec"
                    msg += " %s" % spec
                    raise InvalidSpecDetected(msg)
                if name not in all_spec_deps:
                    all_spec_deps[name] = spec
                else:
                    all_spec_deps[name].constrain(spec)

        # Initialize index of virtual dependency providers if
        # concretize didn't pass us one already
        provider_index = spack.provider_index.ProviderIndex(
            repository=spack.repo.PATH, specs=[s for s in all_spec_deps.values()], restrict=True
        )

        # traverse the package DAG and fill out dependencies according
        # to package files & their 'when' specs
        visited = set()

        any_change = self._normalize_helper(visited, all_spec_deps, provider_index, tests)

        # Mark the spec as normal once done.
        self._normal = True
        return any_change

    def normalized(self):
        """
        Return a normalized copy of this spec without modifying this spec.
        """
        clone = self.copy()
        clone.normalize()
        return clone

    def validate_or_raise(self):
        """Checks that names and values in this spec are real. If they're not,
        it will raise an appropriate exception.
        """
        # FIXME: this function should be lazy, and collect all the errors
        # FIXME: before raising the exceptions, instead of being greedy and
        # FIXME: raise just the first one encountered
        for spec in self.traverse():
            # raise an UnknownPackageError if the spec's package isn't real.
            if (not spec.virtual) and spec.name:
                spack.repo.PATH.get_pkg_class(spec.fullname)

            # validate compiler in addition to the package name.
            if spec.compiler:
                if not spack.compilers.supported(spec.compiler):
                    raise UnsupportedCompilerError(spec.compiler.name)

            # Ensure correctness of variants (if the spec is not virtual)
            if not spec.virtual:
                Spec.ensure_valid_variants(spec)
                vt.substitute_abstract_variants(spec)

    @staticmethod
    def ensure_valid_variants(spec):
        """Ensures that the variant attached to a spec are valid.

        Args:
            spec (Spec): spec to be analyzed

        Raises:
            spack.variant.UnknownVariantError: on the first unknown variant found
        """
        # concrete variants are always valid
        if spec.concrete:
            return

        pkg_cls = spec.package_class
        pkg_variants = pkg_cls.variants
        # reserved names are variants that may be set on any package
        # but are not necessarily recorded by the package's class
        not_existing = set(spec.variants) - (
            set(pkg_variants) | set(spack.directives.reserved_names)
        )
        if not_existing:
            raise vt.UnknownVariantError(spec, not_existing)

    def update_variant_validate(self, variant_name, values):
        """If it is not already there, adds the variant named
        `variant_name` to the spec `spec` based on the definition
        contained in the package metadata. Validates the variant and
        values before returning.

        Used to add values to a variant without being sensitive to the
        variant being single or multi-valued. If the variant already
        exists on the spec it is assumed to be multi-valued and the
        values are appended.

        Args:
           variant_name: the name of the variant to add or append to
           values: the value or values (as a tuple) to add/append
                   to the variant
        """
        if not isinstance(values, tuple):
            values = (values,)

        pkg_variant, _ = self.package_class.variants[variant_name]

        for value in values:
            if self.variants.get(variant_name):
                msg = (
                    f"cannot append the new value '{value}' to the single-valued "
                    f"variant '{self.variants[variant_name]}'"
                )
                assert pkg_variant.multi, msg
                self.variants[variant_name].append(value)
            else:
                variant = pkg_variant.make_variant(value)
                self.variants[variant_name] = variant

        pkg_cls = spack.repo.PATH.get_pkg_class(self.name)
        pkg_variant.validate_or_raise(self.variants[variant_name], pkg_cls)

    def constrain(self, other, deps=True):
        """Intersect self with other in-place. Return True if self changed, False otherwise.

        Args:
            other: constraint to be added to self
            deps: if False, constrain only the root node, otherwise constrain dependencies
                as well.

        Raises:
             spack.error.UnsatisfiableSpecError: when self cannot be constrained
        """
        # If we are trying to constrain a concrete spec, either the spec
        # already satisfies the constraint (and the method returns False)
        # or it raises an exception
        if self.concrete:
            if self.satisfies(other):
                return False
            else:
                raise spack.error.UnsatisfiableSpecError(self, other, "constrain a concrete spec")

        other = self._autospec(other)
        if other.abstract_hash:
            if not self.abstract_hash or other.abstract_hash.startswith(self.abstract_hash):
                self.abstract_hash = other.abstract_hash
            elif not self.abstract_hash.startswith(other.abstract_hash):
                raise InvalidHashError(self, other.abstract_hash)

        if not (self.name == other.name or (not self.name) or (not other.name)):
            raise UnsatisfiableSpecNameError(self.name, other.name)

        if (
            other.namespace is not None
            and self.namespace is not None
            and other.namespace != self.namespace
        ):
            raise UnsatisfiableSpecNameError(self.fullname, other.fullname)

        if not self.versions.overlaps(other.versions):
            raise UnsatisfiableVersionSpecError(self.versions, other.versions)

        for v in [x for x in other.variants if x in self.variants]:
            if not self.variants[v].compatible(other.variants[v]):
                raise vt.UnsatisfiableVariantSpecError(self.variants[v], other.variants[v])

        # TODO: Check out the logic here
        sarch, oarch = self.architecture, other.architecture
        if sarch is not None and oarch is not None:
            if sarch.platform is not None and oarch.platform is not None:
                if sarch.platform != oarch.platform:
                    raise UnsatisfiableArchitectureSpecError(sarch, oarch)
            if sarch.os is not None and oarch.os is not None:
                if sarch.os != oarch.os:
                    raise UnsatisfiableArchitectureSpecError(sarch, oarch)
            if sarch.target is not None and oarch.target is not None:
                if sarch.target != oarch.target:
                    raise UnsatisfiableArchitectureSpecError(sarch, oarch)

        changed = False

        if not self.name and other.name:
            self.name = other.name
            changed = True

        if not self.namespace and other.namespace:
            self.namespace = other.namespace
            changed = True

        if self.compiler is not None and other.compiler is not None:
            changed |= self.compiler.constrain(other.compiler)
        elif self.compiler is None:
            changed |= self.compiler != other.compiler
            self.compiler = other.compiler

        changed |= self.versions.intersect(other.versions)
        changed |= self.variants.constrain(other.variants)

        changed |= self.compiler_flags.constrain(other.compiler_flags)

        old = str(self.architecture)
        sarch, oarch = self.architecture, other.architecture
        if sarch is None or other.architecture is None:
            self.architecture = sarch or oarch
        else:
            if sarch.platform is None or oarch.platform is None:
                self.architecture.platform = sarch.platform or oarch.platform
            if sarch.os is None or oarch.os is None:
                sarch.os = sarch.os or oarch.os
            if sarch.target is None or oarch.target is None:
                sarch.target = sarch.target or oarch.target
        changed |= str(self.architecture) != old

        if deps:
            changed |= self._constrain_dependencies(other)

        if other.concrete and not self.concrete and other.satisfies(self):
            self._finalize_concretization()

        return changed

    def _constrain_dependencies(self, other):
        """Apply constraints of other spec's dependencies to this spec."""
        other = self._autospec(other)

        if not other._dependencies:
            return False

        # TODO: might want more detail than this, e.g. specific deps
        # in violation. if this becomes a priority get rid of this
        # check and be more specific about what's wrong.
        if not other._intersects_dependencies(self):
            raise UnsatisfiableDependencySpecError(other, self)

        if any(not d.name for d in other.traverse(root=False)):
            raise UnconstrainableDependencySpecError(other)

        # Handle common first-order constraints directly
        changed = False
        for name in self.common_dependencies(other):
            changed |= self[name].constrain(other[name], deps=False)
            if name in self._dependencies:
                # WARNING: This function is an implementation detail of the
                # WARNING: original concretizer. Since with that greedy
                # WARNING: algorithm we don't allow multiple nodes from
                # WARNING: the same package in a DAG, here we hard-code
                # WARNING: using index 0 i.e. we assume that we have only
                # WARNING: one edge from package "name"
                edges_from_name = self._dependencies[name]
                changed |= edges_from_name[0].update_deptypes(other._dependencies[name][0].depflag)
                changed |= edges_from_name[0].update_virtuals(
                    other._dependencies[name][0].virtuals
                )

        # Update with additional constraints from other spec
        # operate on direct dependencies only, because a concrete dep
        # represented by hash may have structure that needs to be preserved
        for name in other.direct_dep_difference(self):
            dep_spec_copy = other._get_dependency(name)
            self._add_dependency(
                dep_spec_copy.spec.copy(),
                depflag=dep_spec_copy.depflag,
                virtuals=dep_spec_copy.virtuals,
            )
            changed = True

        return changed

    def common_dependencies(self, other):
        """Return names of dependencies that self an other have in common."""
        common = set(s.name for s in self.traverse(root=False))
        common.intersection_update(s.name for s in other.traverse(root=False))
        return common

    def constrained(self, other, deps=True):
        """Return a constrained copy without modifying this spec."""
        clone = self.copy(deps=deps)
        clone.constrain(other, deps)
        return clone

    def direct_dep_difference(self, other):
        """Returns dependencies in self that are not in other."""
        mine = set(dname for dname in self._dependencies)
        mine.difference_update(dname for dname in other._dependencies)
        return mine

    def _autospec(self, spec_like):
        """
        Used to convert arguments to specs.  If spec_like is a spec, returns
        it.  If it's a string, tries to parse a string.  If that fails, tries
        to parse a local spec from it (i.e. name is assumed to be self's name).
        """
        if isinstance(spec_like, Spec):
            return spec_like
        return Spec(spec_like)

    def intersects(self, other: Union[str, "Spec"], deps: bool = True) -> bool:
        """Return True if there exists at least one concrete spec that matches both
        self and other, otherwise False.

        This operation is commutative, and if two specs intersect it means that one
        can constrain the other.

        Args:
            other: spec to be checked for compatibility
            deps: if True check compatibility of dependency nodes too, if False only check root
        """
        other = self._autospec(other)

        if other.concrete and self.concrete:
            return self.dag_hash() == other.dag_hash()

        elif self.concrete:
            return self.satisfies(other)

        elif other.concrete:
            return other.satisfies(self)

        # From here we know both self and other are not concrete
        self_hash = self.abstract_hash
        other_hash = other.abstract_hash

        if (
            self_hash
            and other_hash
            and not (self_hash.startswith(other_hash) or other_hash.startswith(self_hash))
        ):
            return False

        # If the names are different, we need to consider virtuals
        if self.name != other.name and self.name and other.name:
            if self.virtual and other.virtual:
                # Two virtual specs intersect only if there are providers for both
                lhs = spack.repo.PATH.providers_for(str(self))
                rhs = spack.repo.PATH.providers_for(str(other))
                intersection = [s for s in lhs if any(s.intersects(z) for z in rhs)]
                return bool(intersection)

            # A provider can satisfy a virtual dependency.
            elif self.virtual or other.virtual:
                virtual_spec, non_virtual_spec = (self, other) if self.virtual else (other, self)
                try:
                    # Here we might get an abstract spec
                    pkg_cls = spack.repo.PATH.get_pkg_class(non_virtual_spec.fullname)
                    pkg = pkg_cls(non_virtual_spec)
                except spack.repo.UnknownEntityError:
                    # If we can't get package info on this spec, don't treat
                    # it as a provider of this vdep.
                    return False

                if pkg.provides(virtual_spec.name):
                    for provided, when_specs in pkg.provided.items():
                        if any(
                            non_virtual_spec.intersects(when, deps=False) for when in when_specs
                        ):
                            if provided.intersects(virtual_spec):
                                return True
            return False

        # namespaces either match, or other doesn't require one.
        if (
            other.namespace is not None
            and self.namespace is not None
            and self.namespace != other.namespace
        ):
            return False

        if self.versions and other.versions:
            if not self.versions.intersects(other.versions):
                return False

        if self.compiler and other.compiler:
            if not self.compiler.intersects(other.compiler):
                return False

        if not self.variants.intersects(other.variants):
            return False

        if self.architecture and other.architecture:
            if not self.architecture.intersects(other.architecture):
                return False

        if not self.compiler_flags.intersects(other.compiler_flags):
            return False

        # If we need to descend into dependencies, do it, otherwise we're done.
        if deps:
            return self._intersects_dependencies(other)

        return True

    def _intersects_dependencies(self, other):
        if not other._dependencies or not self._dependencies:
            # one spec *could* eventually satisfy the other
            return True

        # Handle first-order constraints directly
        for name in self.common_dependencies(other):
            if not self[name].intersects(other[name], deps=False):
                return False

        # For virtual dependencies, we need to dig a little deeper.
        self_index = spack.provider_index.ProviderIndex(
            repository=spack.repo.PATH, specs=self.traverse(), restrict=True
        )
        other_index = spack.provider_index.ProviderIndex(
            repository=spack.repo.PATH, specs=other.traverse(), restrict=True
        )

        # These two loops handle cases where there is an overly restrictive
        # vpkg in one spec for a provider in the other (e.g., mpi@3: is not
        # compatible with mpich2)
        for spec in self.virtual_dependencies():
            if spec.name in other_index and not other_index.providers_for(spec):
                return False

        for spec in other.virtual_dependencies():
            if spec.name in self_index and not self_index.providers_for(spec):
                return False

        return True

    def satisfies(self, other: Union[str, "Spec"], deps: bool = True) -> bool:
        """Return True if all concrete specs matching self also match other, otherwise False.

        Args:
            other: spec to be satisfied
            deps: if True descend to dependencies, otherwise only check root node
        """
        other = self._autospec(other)

        if other.concrete:
            # The left-hand side must be the same singleton with identical hash. Notice that
            # package hashes can be different for otherwise indistinguishable concrete Spec
            # objects.
            return self.concrete and self.dag_hash() == other.dag_hash()

        # If the right-hand side has an abstract hash, make sure it's a prefix of the
        # left-hand side's (abstract) hash.
        if other.abstract_hash:
            compare_hash = self.dag_hash() if self.concrete else self.abstract_hash
            if not compare_hash or not compare_hash.startswith(other.abstract_hash):
                return False

        # If the names are different, we need to consider virtuals
        if self.name != other.name and self.name and other.name:
            # A concrete provider can satisfy a virtual dependency.
            if not self.virtual and other.virtual:
                try:
                    # Here we might get an abstract spec
                    pkg_cls = spack.repo.PATH.get_pkg_class(self.fullname)
                    pkg = pkg_cls(self)
                except spack.repo.UnknownEntityError:
                    # If we can't get package info on this spec, don't treat
                    # it as a provider of this vdep.
                    return False

                if pkg.provides(other.name):
                    for provided, when_specs in pkg.provided.items():
                        if any(self.satisfies(when, deps=False) for when in when_specs):
                            if provided.intersects(other):
                                return True
            return False

        # namespaces either match, or other doesn't require one.
        if (
            other.namespace is not None
            and self.namespace is not None
            and self.namespace != other.namespace
        ):
            return False

        if not self.versions.satisfies(other.versions):
            return False

        if self.compiler and other.compiler:
            if not self.compiler.satisfies(other.compiler):
                return False
        elif other.compiler and not self.compiler:
            return False

        if not self.variants.satisfies(other.variants):
            return False

        if self.architecture and other.architecture:
            if not self.architecture.satisfies(other.architecture):
                return False
        elif other.architecture and not self.architecture:
            return False

        if not self.compiler_flags.satisfies(other.compiler_flags):
            return False

        # If we need to descend into dependencies, do it, otherwise we're done.
        if not deps:
            return True

        # If there are no constraints to satisfy, we're done.
        if not other._dependencies:
            return True

        # If we have no dependencies, we can't satisfy any constraints.
        if not self._dependencies:
            return False

        # If we arrived here, then rhs is abstract. At the moment we don't care about the edge
        # structure of an abstract DAG, so we check if any edge could satisfy the properties
        # we ask for.
        lhs_edges: Dict[str, Set[DependencySpec]] = collections.defaultdict(set)
        for rhs_edge in other.traverse_edges(root=False, cover="edges"):
            # If we are checking for ^mpi we need to verify if there is any edge
            if rhs_edge.spec.virtual:
                rhs_edge.update_virtuals(virtuals=(rhs_edge.spec.name,))

            if not rhs_edge.virtuals:
                continue

            if not lhs_edges:
                # Construct a map of the link/run subDAG + direct "build" edges,
                # keyed by dependency name
                for lhs_edge in self.traverse_edges(
                    root=False, cover="edges", deptype=("link", "run")
                ):
                    lhs_edges[lhs_edge.spec.name].add(lhs_edge)
                    for virtual_name in lhs_edge.virtuals:
                        lhs_edges[virtual_name].add(lhs_edge)

                build_edges = self.edges_to_dependencies(depflag=dt.BUILD)
                for lhs_edge in build_edges:
                    lhs_edges[lhs_edge.spec.name].add(lhs_edge)
                    for virtual_name in lhs_edge.virtuals:
                        lhs_edges[virtual_name].add(lhs_edge)

            # We don't have edges to this dependency
            current_dependency_name = rhs_edge.spec.name
            if current_dependency_name not in lhs_edges:
                return False

            for virtual in rhs_edge.virtuals:
                has_virtual = any(
                    virtual in edge.virtuals for edge in lhs_edges[current_dependency_name]
                )
                if not has_virtual:
                    return False

        # Edges have been checked above already, hence deps=False
        return all(
            any(lhs.satisfies(rhs, deps=False) for lhs in self.traverse(root=False))
            for rhs in other.traverse(root=False)
        )

    def virtual_dependencies(self):
        """Return list of any virtual deps in this spec."""
        return [spec for spec in self.traverse() if spec.virtual]

    @property  # type: ignore[misc] # decorated prop not supported in mypy
    def patches(self):
        """Return patch objects for any patch sha256 sums on this Spec.

        This is for use after concretization to iterate over any patches
        associated with this spec.

        TODO: this only checks in the package; it doesn't resurrect old
        patches from install directories, but it probably should.
        """
        if not hasattr(self, "_patches"):
            self._patches = []

            # translate patch sha256sums to patch objects by consulting the index
            if self._patches_assigned():
                for sha256 in self.variants["patches"]._patches_in_order_of_appearance:
                    index = spack.repo.PATH.patch_index
                    pkg_cls = spack.repo.PATH.get_pkg_class(self.name)
                    try:
                        patch = index.patch_for_package(sha256, pkg_cls)
                    except spack.patch.PatchLookupError as e:
                        raise spack.error.SpecError(
                            f"{e}. This usually means the patch was modified or removed. "
                            "To fix this, either reconcretize or use the original package "
                            "repository"
                        ) from e

                    self._patches.append(patch)

        return self._patches

    def _dup(self, other, deps: Union[bool, dt.DepTypes, dt.DepFlag] = True, cleardeps=True):
        """Copy the spec other into self.  This is an overwriting
        copy. It does not copy any dependents (parents), but by default
        copies dependencies.

        To duplicate an entire DAG, call _dup() on the root of the DAG.

        Args:
            other (Spec): spec to be copied onto ``self``
            deps: if True copies all the dependencies. If
                False copies None. If deptype/depflag, copy matching types.
            cleardeps (bool): if True clears the dependencies of ``self``,
                before possibly copying the dependencies of ``other`` onto
                ``self``

        Returns:
            True if ``self`` changed because of the copy operation,
            False otherwise.

        """
        # We don't count dependencies as changes here
        changed = True
        if hasattr(self, "name"):
            changed = (
                self.name != other.name
                and self.versions != other.versions
                and self.architecture != other.architecture
                and self.compiler != other.compiler
                and self.variants != other.variants
                and self._normal != other._normal
                and self.concrete != other.concrete
                and self.external_path != other.external_path
                and self.external_modules != other.external_modules
                and self.compiler_flags != other.compiler_flags
                and self.abstract_hash != other.abstract_hash
            )

        self._package = None

        # Local node attributes get copied first.
        self.name = other.name
        self.versions = other.versions.copy()
        self.architecture = other.architecture.copy() if other.architecture else None
        self.compiler = other.compiler.copy() if other.compiler else None
        if cleardeps:
            self._dependents = _EdgeMap(store_by=EdgeDirection.parent)
            self._dependencies = _EdgeMap(store_by=EdgeDirection.child)
        self.compiler_flags = other.compiler_flags.copy()
        self.compiler_flags.spec = self
        self.variants = other.variants.copy()
        self._build_spec = other._build_spec

        # FIXME: we manage _patches_in_order_of_appearance specially here
        # to keep it from leaking out of spec.py, but we should figure
        # out how to handle it more elegantly in the Variant classes.
        for k, v in other.variants.items():
            patches = getattr(v, "_patches_in_order_of_appearance", None)
            if patches:
                self.variants[k]._patches_in_order_of_appearance = patches

        self.variants.spec = self
        self.external_path = other.external_path
        self.external_modules = other.external_modules
        self.extra_attributes = other.extra_attributes
        self.namespace = other.namespace

        # If we copy dependencies, preserve DAG structure in the new spec
        if deps:
            # If caller restricted deptypes to be copied, adjust that here.
            # By default, just copy all deptypes
            depflag = dt.ALL
            if isinstance(deps, (tuple, list, str)):
                depflag = dt.canonicalize(deps)
            self._dup_deps(other, depflag)

        self._concrete = other._concrete

        self.abstract_hash = other.abstract_hash

        if self._concrete:
            self._dunder_hash = other._dunder_hash
            self._normal = other._normal
            for h in ht.hashes:
                setattr(self, h.attr, getattr(other, h.attr, None))
        else:
            self._dunder_hash = None
            # Note, we could use other._normal if we are copying all deps, but
            # always set it False here to avoid the complexity of checking
            self._normal = False
            for h in ht.hashes:
                setattr(self, h.attr, None)

        return changed

    def _dup_deps(self, other, depflag: dt.DepFlag):
        def spid(spec):
            return id(spec)

        new_specs = {spid(other): self}
        for edge in other.traverse_edges(cover="edges", root=False):
            if edge.depflag and not depflag & edge.depflag:
                continue

            if spid(edge.parent) not in new_specs:
                new_specs[spid(edge.parent)] = edge.parent.copy(deps=False)

            if spid(edge.spec) not in new_specs:
                new_specs[spid(edge.spec)] = edge.spec.copy(deps=False)

            new_specs[spid(edge.parent)].add_dependency_edge(
                new_specs[spid(edge.spec)], depflag=edge.depflag, virtuals=edge.virtuals
            )

    def copy(self, deps: Union[bool, dt.DepTypes, dt.DepFlag] = True, **kwargs):
        """Make a copy of this spec.

        Args:
            deps: Defaults to True. If boolean, controls
                whether dependencies are copied (copied if True). If a
                DepTypes or DepFlag is provided, *only* matching dependencies are copied.
            kwargs: additional arguments for internal use (passed to ``_dup``).

        Returns:
            A copy of this spec.

        Examples:
            Deep copy with dependencies::

                spec.copy()
                spec.copy(deps=True)

            Shallow copy (no dependencies)::

                spec.copy(deps=False)

            Only build and run dependencies::

                deps=('build', 'run'):

        """
        clone = Spec.__new__(Spec)
        clone._dup(self, deps=deps, **kwargs)
        return clone

    @property
    def version(self):
        if not self.versions.concrete:
            raise spack.error.SpecError("Spec version is not concrete: " + str(self))
        return self.versions[0]

    def __getitem__(self, name):
        """Get a dependency from the spec by its name. This call implicitly
        sets a query state in the package being retrieved. The behavior of
        packages may be influenced by additional query parameters that are
        passed after a colon symbol.

        Note that if a virtual package is queried a copy of the Spec is
        returned while for non-virtual a reference is returned.
        """
        query_parameters = name.split(":")
        if len(query_parameters) > 2:
            raise KeyError("key has more than one ':' symbol. At most one is admitted.")

        name, query_parameters = query_parameters[0], query_parameters[1:]
        if query_parameters:
            # We have extra query parameters, which are comma separated
            # values
            csv = query_parameters.pop().strip()
            query_parameters = re.split(r"\s*,\s*", csv)

        # In some cases a package appears multiple times in the same DAG for *distinct*
        # specs. For example, a build-type dependency may itself depend on a package
        # the current spec depends on, but their specs may differ. Therefore we iterate
        # in an order here that prioritizes the build, test and runtime dependencies;
        # only when we don't find the package do we consider the full DAG.
        order = lambda: itertools.chain(
            self.traverse(deptype="link"),
            self.dependencies(deptype=dt.BUILD | dt.RUN | dt.TEST),
            self.traverse(),  # fall back to a full search
        )

        try:
            value = next(
                itertools.chain(
                    # Regular specs
                    (x for x in order() if x.name == name),
                    (
                        x
                        for x in order()
                        if (not x.virtual)
                        and any(name in edge.virtuals for edge in x.edges_from_dependents())
                    ),
                    (x for x in order() if (not x.virtual) and x.package.provides(name)),
                )
            )
        except StopIteration:
            raise KeyError(f"No spec with name {name} in {self}")

        if self._concrete:
            return SpecBuildInterface(value, name, query_parameters)

        return value

    def __contains__(self, spec):
        """True if this spec or some dependency satisfies the spec.

        Note: If ``spec`` is anonymous, we ONLY check whether the root
        satisfies it, NOT dependencies.  This is because most anonymous
        specs (e.g., ``@1.2``) don't make sense when applied across an
        entire DAG -- we limit them to the root.

        """
        spec = self._autospec(spec)

        # if anonymous or same name, we only have to look at the root
        if not spec.name or spec.name == self.name:
            return self.satisfies(spec)
        else:
            return any(s.satisfies(spec) for s in self.traverse(root=False))

    def eq_dag(self, other, deptypes=True, vs=None, vo=None):
        """True if the full dependency DAGs of specs are equal."""
        if vs is None:
            vs = set()
        if vo is None:
            vo = set()

        vs.add(id(self))
        vo.add(id(other))

        if not self.eq_node(other):
            return False

        if len(self._dependencies) != len(other._dependencies):
            return False

        ssorted = [self._dependencies[name] for name in sorted(self._dependencies)]
        osorted = [other._dependencies[name] for name in sorted(other._dependencies)]
        for s_dspec, o_dspec in zip(
            itertools.chain.from_iterable(ssorted), itertools.chain.from_iterable(osorted)
        ):
            if deptypes and s_dspec.depflag != o_dspec.depflag:
                return False

            s, o = s_dspec.spec, o_dspec.spec
            visited_s = id(s) in vs
            visited_o = id(o) in vo

            # Check for duplicate or non-equal dependencies
            if visited_s != visited_o:
                return False

            # Skip visited nodes
            if visited_s or visited_o:
                continue

            # Recursive check for equality
            if not s.eq_dag(o, deptypes, vs, vo):
                return False

        return True

    def _cmp_node(self):
        """Yield comparable elements of just *this node* and not its deps."""
        yield self.name
        yield self.namespace
        yield self.versions
        yield self.variants
        yield self.compiler
        yield self.compiler_flags
        yield self.architecture
        yield self.abstract_hash

        # this is not present on older specs
        yield getattr(self, "_package_hash", None)

    def eq_node(self, other):
        """Equality with another spec, not including dependencies."""
        return (other is not None) and lang.lazy_eq(self._cmp_node, other._cmp_node)

    def _cmp_iter(self):
        """Lazily yield components of self for comparison."""

        for item in self._cmp_node():
            yield item

        # This needs to be in _cmp_iter so that no specs with different process hashes
        # are considered the same by `__hash__` or `__eq__`.
        #
        # TODO: We should eventually unify the `_cmp_*` methods with `to_node_dict` so
        # TODO: there aren't two sources of truth, but this needs some thought, since
        # TODO: they exist for speed.  We should benchmark whether it's really worth
        # TODO: having two types of hashing now that we use `json` instead of `yaml` for
        # TODO: spec hashing.
        yield self.process_hash() if self.concrete else None

        def deps():
            for dep in sorted(itertools.chain.from_iterable(self._dependencies.values())):
                yield dep.spec.name
                yield dep.depflag
                yield hash(dep.spec)

        yield deps

    def colorized(self):
        return colorize_spec(self)

    def format(self, format_string=DEFAULT_FORMAT, **kwargs):
        r"""Prints out particular pieces of a spec, depending on what is
        in the format string.

        Using the ``{attribute}`` syntax, any field of the spec can be
        selected.  Those attributes can be recursive. For example,
        ``s.format({compiler.version})`` will print the version of the
        compiler.

        Commonly used attributes of the Spec for format strings include::

            name
            version
            compiler
            compiler.name
            compiler.version
            compiler_flags
            variants
            architecture
            architecture.platform
            architecture.os
            architecture.target
            prefix

        Some additional special-case properties can be added::

            hash[:len]    The DAG hash with optional length argument
            spack_root    The spack root directory
            spack_install The spack install directory

        The ``^`` sigil can be used to access dependencies by name.
        ``s.format({^mpi.name})`` will print the name of the MPI
        implementation in the spec.

        The ``@``, ``%``, ``arch=``, and ``/`` sigils
        can be used to include the sigil with the printed
        string. These sigils may only be used with the appropriate
        attributes, listed below::

            @        ``{@version}``, ``{@compiler.version}``
            %        ``{%compiler}``, ``{%compiler.name}``
            arch=    ``{arch=architecture}``
            /        ``{/hash}``, ``{/hash:7}``, etc

        The ``@`` sigil may also be used for any other property named
        ``version``. Sigils printed with the attribute string are only
        printed if the attribute string is non-empty, and are colored
        according to the color of the attribute.

        Sigils are not used for printing variants. Variants listed by
        name naturally print with their sigil. For example,
        ``spec.format('{variants.debug}')`` would print either
        ``+debug`` or ``~debug`` depending on the name of the
        variant. Non-boolean variants print as ``name=value``. To
        print variant names or values independently, use
        ``spec.format('{variants.<name>.name}')`` or
        ``spec.format('{variants.<name>.value}')``.

        Spec format strings use ``\`` as the escape character. Use
        ``\{`` and ``\}`` for literal braces, and ``\\`` for the
        literal ``\`` character.

        Args:
            format_string (str): string containing the format to be expanded

        Keyword Args:
            color (bool): True if returned string is colored
            transform (dict): maps full-string formats to a callable \
                that accepts a string and returns another one

        """
        color = kwargs.get("color", False)
        transform = kwargs.get("transform", {})

        out = io.StringIO()

        def write(s, c=None):
            f = clr.cescape(s)
            if c is not None:
                f = COLOR_FORMATS[c] + f + "@."
            clr.cwrite(f, stream=out, color=color)

        def write_attribute(spec, attribute, color):
            attribute = attribute.lower()

            sig = ""
            if attribute.startswith(("@", "%", "/")):
                # color sigils that are inside braces
                sig = attribute[0]
                attribute = attribute[1:]
            elif attribute.startswith("arch="):
                sig = " arch="  # include space as separator
                attribute = attribute[5:]

            current = spec
            if attribute.startswith("^"):
                attribute = attribute[1:]
                dep, attribute = attribute.split(".", 1)
                current = self[dep]

            if attribute == "":
                raise SpecFormatStringError("Format string attributes must be non-empty")

            parts = attribute.split(".")
            assert parts

            # check that the sigil is valid for the attribute.
            if sig == "@" and parts[-1] not in ("versions", "version"):
                raise SpecFormatSigilError(sig, "versions", attribute)
            elif sig == "%" and attribute not in ("compiler", "compiler.name"):
                raise SpecFormatSigilError(sig, "compilers", attribute)
            elif sig == "/" and not re.match(r"(abstract_)?hash(:\d+)?$", attribute):
                raise SpecFormatSigilError(sig, "DAG hashes", attribute)
            elif sig == " arch=" and attribute not in ("architecture", "arch"):
                raise SpecFormatSigilError(sig, "the architecture", attribute)

            # find the morph function for our attribute
            morph = transform.get(attribute, lambda s, x: x)

            # Special cases for non-spec attributes and hashes.
            # These must be the only non-dep component of the format attribute
            if attribute == "spack_root":
                write(morph(spec, spack.paths.spack_root))
                return
            elif attribute == "spack_install":
                write(morph(spec, spack.store.STORE.layout.root))
                return
            elif re.match(r"hash(:\d)?", attribute):
                col = "#"
                if ":" in attribute:
                    _, length = attribute.split(":")
                    write(sig + morph(spec, current.dag_hash(int(length))), col)
                else:
                    write(sig + morph(spec, current.dag_hash()), col)
                return

            # Iterate over components using getattr to get next element
            for idx, part in enumerate(parts):
                if not part:
                    raise SpecFormatStringError("Format string attributes must be non-empty")
                if part.startswith("_"):
                    raise SpecFormatStringError("Attempted to format private attribute")
                else:
                    if isinstance(current, vt.VariantMap):
                        # subscript instead of getattr for variant names
                        current = current[part]
                    else:
                        # aliases
                        if part == "arch":
                            part = "architecture"
                        elif part == "version":
                            # version (singular) requires a concrete versions list. Avoid
                            # pedantic errors by using versions (plural) when not concrete.
                            # These two are not entirely equivalent for pkg@=1.2.3:
                            # - version prints '1.2.3'
                            # - versions prints '=1.2.3'
                            if not current.versions.concrete:
                                part = "versions"
                        try:
                            current = getattr(current, part)
                        except AttributeError:
                            parent = ".".join(parts[:idx])
                            m = "Attempted to format attribute %s." % attribute
                            m += "Spec %s has no attribute %s" % (parent, part)
                            raise SpecFormatStringError(m)
                        if isinstance(current, vn.VersionList):
                            if current == vn.any_version:
                                # We don't print empty version lists
                                return

                    if callable(current):
                        raise SpecFormatStringError("Attempted to format callable object")
                    if current is None:
                        # We're not printing anything
                        return

            # Set color codes for various attributes
            col = None
            if "variants" in parts:
                col = "+"
            elif "architecture" in parts:
                col = "="
            elif "compiler" in parts or "compiler_flags" in parts:
                col = "%"
            elif "version" in parts or "versions" in parts:
                col = "@"

            # Finally, write the output
            write(sig + morph(spec, str(current)), col)

        attribute = ""
        in_attribute = False
        escape = False

        for c in format_string:
            if escape:
                out.write(c)
                escape = False
            elif c == "\\":
                escape = True
            elif in_attribute:
                if c == "}":
                    write_attribute(self, attribute, color)
                    attribute = ""
                    in_attribute = False
                else:
                    attribute += c
            else:
                if c == "}":
                    raise SpecFormatStringError(
                        "Encountered closing } before opening { in %s" % format_string
                    )
                elif c == "{":
                    in_attribute = True
                else:
                    out.write(c)
        if in_attribute:
            raise SpecFormatStringError(
                "Format string terminated while reading attribute." "Missing terminating }."
            )

        formatted_spec = out.getvalue()
        return formatted_spec.strip()

    def cformat(self, *args, **kwargs):
        """Same as format, but color defaults to auto instead of False."""
        kwargs = kwargs.copy()
        kwargs.setdefault("color", None)
        return self.format(*args, **kwargs)

    def format_path(
        # self, format_string: str, _path_ctor: Optional[pathlib.PurePath] = None
        self,
        format_string: str,
        _path_ctor: Optional[Callable[[Any], pathlib.PurePath]] = None,
    ) -> str:
        """Given a `format_string` that is intended as a path, generate a string
        like from `Spec.format`, but eliminate extra path separators introduced by
        formatting of Spec properties.

        Path separators explicitly added to the string are preserved, so for example
        "{name}/{version}" would generate a directory based on the Spec's name, and
        a subdirectory based on its version; this function guarantees though that
        the resulting string would only have two directories (i.e. that if under
        normal circumstances that `str(Spec.version)` would contain a path
        separator, it would not in this case).
        """
        format_component_with_sep = r"\{[^}]*[/\\][^}]*}"
        if re.search(format_component_with_sep, format_string):
            raise SpecFormatPathError(
                f"Invalid path format string: cannot contain {{/...}}\n\t{format_string}"
            )

        path_ctor = _path_ctor or pathlib.PurePath
        format_string_as_path = path_ctor(format_string)
        if format_string_as_path.is_absolute():
            output_path_components = [format_string_as_path.parts[0]]
            input_path_components = list(format_string_as_path.parts[1:])
        else:
            output_path_components = []
            input_path_components = list(format_string_as_path.parts)
        output_path_components += [
            fs.polite_filename(self.format(x)) for x in input_path_components
        ]
        return str(path_ctor(*output_path_components))

    def __str__(self):
        root_str = [self.format()]
        sorted_dependencies = sorted(
            self.traverse(root=False), key=lambda x: (x.name, x.abstract_hash)
        )
        sorted_dependencies = [
            d.format("{edge_attributes} " + DEFAULT_FORMAT) for d in sorted_dependencies
        ]
        spec_str = " ^".join(root_str + sorted_dependencies)
        return spec_str.strip()

    @property
    def colored_str(self):
        root_str = [self.cformat()]
        sorted_dependencies = sorted(
            self.traverse(root=False), key=lambda x: (x.name, x.abstract_hash)
        )
        sorted_dependencies = [
            d.cformat("{edge_attributes} " + DISPLAY_FORMAT) for d in sorted_dependencies
        ]
        spec_str = " ^".join(root_str + sorted_dependencies)
        return spec_str.strip()

    def install_status(self):
        """Helper for tree to print DB install status."""
        if not self.concrete:
            return InstallStatus.absent

        if self.external:
            return InstallStatus.external

        upstream, record = spack.store.STORE.db.query_by_spec_hash(self.dag_hash())
        if not record:
            return InstallStatus.absent
        elif upstream and record.installed:
            return InstallStatus.upstream
        elif record.installed:
            return InstallStatus.installed
        else:
            return InstallStatus.missing

    def _installed_explicitly(self):
        """Helper for tree to print DB install status."""
        if not self.concrete:
            return None
        try:
            record = spack.store.STORE.db.get_record(self)
            return record.explicit
        except KeyError:
            return None

    def tree(
        self,
        *,
        color: Optional[bool] = None,
        depth: bool = False,
        hashes: bool = False,
        hashlen: Optional[int] = None,
        cover: str = "nodes",
        indent: int = 0,
        format: str = DEFAULT_FORMAT,
        deptypes: Union[Tuple[str, ...], str] = "all",
        show_types: bool = False,
        depth_first: bool = False,
        recurse_dependencies: bool = True,
        status_fn: Optional[Callable[["Spec"], InstallStatus]] = None,
        prefix: Optional[Callable[["Spec"], str]] = None,
    ) -> str:
        """Prints out this spec and its dependencies, tree-formatted
        with indentation.

        Status function may either output a boolean or an InstallStatus

        Args:
            color: if True, always colorize the tree. If False, don't colorize the tree. If None,
                use the default from llnl.tty.color
            depth: print the depth from the root
            hashes: if True, print the hash of each node
            hashlen: length of the hash to be printed
            cover: either "nodes" or "edges"
            indent: extra indentation for the tree being printed
            format: format to be used to print each node
            deptypes: dependency types to be represented in the tree
            show_types: if True, show the (merged) dependency type of a node
            depth_first: if True, traverse the DAG depth first when representing it as a tree
            recurse_dependencies: if True, recurse on dependencies
            status_fn: optional callable that takes a node as an argument and return its
                installation status
            prefix: optional callable that takes a node as an argument and return its
                installation prefix
        """
        out = ""

        if color is None:
            color = clr.get_color_when()

        for d, dep_spec in traverse.traverse_tree(
            [self], cover=cover, deptype=deptypes, depth_first=depth_first
        ):
            node = dep_spec.spec

            if prefix is not None:
                out += prefix(node)
            out += " " * indent

            if depth:
                out += "%-4d" % d

            if status_fn:
                status = status_fn(node)
                if status in list(InstallStatus):
                    out += clr.colorize(status.value, color=color)
                elif status:
                    out += clr.colorize("@g{[+]}  ", color=color)
                else:
                    out += clr.colorize("@r{[-]}  ", color=color)

            if hashes:
                out += clr.colorize("@K{%s}  ", color=color) % node.dag_hash(hashlen)

            if show_types:
                if cover == "nodes":
                    # when only covering nodes, we merge dependency types
                    # from all dependents before showing them.
                    depflag = 0
                    for ds in node.edges_from_dependents():
                        depflag |= ds.depflag
                else:
                    # when covering edges or paths, we show dependency
                    # types only for the edge through which we visited
                    depflag = dep_spec.depflag

                type_chars = dt.flag_to_chars(depflag)
                out += "[%s]  " % type_chars

            out += "    " * d
            if d > 0:
                out += "^"
            out += node.format(format, color=color) + "\n"

            # Check if we wanted just the first line
            if not recurse_dependencies:
                break

        return out

    def __repr__(self):
        return str(self)

    @property
    def platform(self):
        return self.architecture.platform

    @property
    def os(self):
        return self.architecture.os

    @property
    def target(self):
        # This property returns the underlying microarchitecture object
        # to give to the attribute the appropriate comparison semantic
        return self.architecture.target.microarchitecture

    @property
    def build_spec(self):
        return self._build_spec or self

    @build_spec.setter
    def build_spec(self, value):
        self._build_spec = value

    def trim(self, dep_name):
        """
        Remove any package that is or provides `dep_name` transitively
        from this tree. This can also remove other dependencies if
        they are only present because of `dep_name`.
        """
        for spec in list(self.traverse()):
            new_dependencies = _EdgeMap()  # A new _EdgeMap
            for pkg_name, edge_list in spec._dependencies.items():
                for edge in edge_list:
                    if (dep_name not in edge.virtuals) and (not dep_name == edge.spec.name):
                        new_dependencies.add(edge)
            spec._dependencies = new_dependencies

    def splice(self, other, transitive):
        """Splices dependency "other" into this ("target") Spec, and return the
        result as a concrete Spec.
        If transitive, then other and its dependencies will be extrapolated to
        a list of Specs and spliced in accordingly.
        For example, let there exist a dependency graph as follows:
        T
        | \
        Z<-H
        In this example, Spec T depends on H and Z, and H also depends on Z.
        Suppose, however, that we wish to use a different H, known as H'. This
        function will splice in the new H' in one of two ways:
        1. transitively, where H' depends on the Z' it was built with, and the
        new T* also directly depends on this new Z', or
        2. intransitively, where the new T* and H' both depend on the original
        Z.
        Since the Spec returned by this splicing function is no longer deployed
        the same way it was built, any such changes are tracked by setting the
        build_spec to point to the corresponding dependency from the original
        Spec.
        TODO: Extend this for non-concrete Specs.
        """
        assert self.concrete
        assert other.concrete

        virtuals_to_replace = [v.name for v in other.package.virtuals_provided if v in self]
        if virtuals_to_replace:
            deps_to_replace = dict((self[v], other) for v in virtuals_to_replace)
            # deps_to_replace = [self[v] for v in virtuals_to_replace]
        else:
            # TODO: sanity check and error raise here for other.name not in self
            deps_to_replace = {self[other.name]: other}
            # deps_to_replace = [self[other.name]]

        for d in deps_to_replace:
            if not all(
                v in other.package.virtuals_provided or v not in self
                for v in d.package.virtuals_provided
            ):
                # There was something provided by the original that we don't
                # get from its replacement.
                raise SpliceError(
                    ("Splice between {0} and {1} will not provide " "the same virtuals.").format(
                        self.name, other.name
                    )
                )
            for n in d.traverse(root=False):
                if not all(
                    any(
                        v in other_n.package.virtuals_provided
                        for other_n in other.traverse(root=False)
                    )
                    or v not in self
                    for v in n.package.virtuals_provided
                ):
                    raise SpliceError(
                        (
                            "Splice between {0} and {1} will not provide " "the same virtuals."
                        ).format(self.name, other.name)
                    )

        # For now, check that we don't have DAG with multiple specs from the
        # same package
        def multiple_specs(root):
            counter = collections.Counter([node.name for node in root.traverse()])
            _, max_number = counter.most_common()[0]
            return max_number > 1

        if multiple_specs(self) or multiple_specs(other):
            msg = (
                'Either "{0}" or "{1}" contain multiple specs from the same '
                "package, which cannot be handled by splicing at the moment"
            )
            raise ValueError(msg.format(self, other))

        # Multiple unique specs with the same name will collide, so the
        # _dependents of these specs should not be trusted.
        # Variants may also be ignored here for now...

        # Keep all cached hashes because we will invalidate the ones that need
        # invalidating later, and we don't want to invalidate unnecessarily

        def from_self(name, transitive):
            if transitive:
                if name in other:
                    return False
                if any(v in other for v in self[name].package.virtuals_provided):
                    return False
                return True
            else:
                if name == other.name:
                    return False
                if any(
                    v in other.package.virtuals_provided
                    for v in self[name].package.virtuals_provided
                ):
                    return False
                return True

        self_nodes = dict(
            (s.name, s.copy(deps=False))
            for s in self.traverse(root=True)
            if from_self(s.name, transitive)
        )

        if transitive:
            other_nodes = dict((s.name, s.copy(deps=False)) for s in other.traverse(root=True))
        else:
            # NOTE: Does not fully validate providers; loader races possible
            other_nodes = dict(
                (s.name, s.copy(deps=False))
                for s in other.traverse(root=True)
                if s is other or s.name not in self
            )

        nodes = other_nodes.copy()
        nodes.update(self_nodes)

        for name in nodes:
            if name in self_nodes:
                for edge in self[name].edges_to_dependencies():
                    dep_name = deps_to_replace.get(edge.spec, edge.spec).name
                    nodes[name].add_dependency_edge(
                        nodes[dep_name], depflag=edge.depflag, virtuals=edge.virtuals
                    )
                if any(dep not in self_nodes for dep in self[name]._dependencies):
                    nodes[name].build_spec = self[name].build_spec
            else:
                for edge in other[name].edges_to_dependencies():
                    nodes[name].add_dependency_edge(
                        nodes[edge.spec.name], depflag=edge.depflag, virtuals=edge.virtuals
                    )
                if any(dep not in other_nodes for dep in other[name]._dependencies):
                    nodes[name].build_spec = other[name].build_spec

        ret = nodes[self.name]

        # Clear cached hashes for all affected nodes
        # Do not touch unaffected nodes
        for dep in ret.traverse(root=True, order="post"):
            opposite = other_nodes if dep.name in self_nodes else self_nodes
            if any(name in dep for name in opposite.keys()):
                # package hash cannot be affected by splice
                dep.clear_cached_hashes(ignore=["package_hash"])

                dep.dag_hash()

        return nodes[self.name]

    def clear_cached_hashes(self, ignore=()):
        """
        Clears all cached hashes in a Spec, while preserving other properties.
        """
        for h in ht.hashes:
            if h.attr not in ignore:
                if hasattr(self, h.attr):
                    setattr(self, h.attr, None)
        self._dunder_hash = None

    def __hash__(self):
        # If the spec is concrete, we leverage the process hash and just use
        # a 64-bit prefix of it. The process hash has the advantage that it's
        # computed once per concrete spec, and it's saved -- so if we read
        # concrete specs we don't need to recompute the whole hash. This is
        # good for large, unchanging specs.
        #
        # We use the process hash instead of the DAG hash here because the DAG
        # hash includes the package hash, which can cause infinite recursion,
        # and which isn't defined unless the spec has a known package.
        if self.concrete:
            if not self._dunder_hash:
                self._dunder_hash = self.process_hash_bit_prefix(64)
            return self._dunder_hash

        # This is the normal hash for lazy_lexicographic_ordering. It's
        # slow for large specs because it traverses the whole spec graph,
        # so we hope it only runs on abstract specs, which are small.
        return hash(lang.tuplify(self._cmp_iter))

    def __reduce__(self):
        return Spec.from_dict, (self.to_dict(hash=ht.process_hash),)

    def attach_git_version_lookup(self):
        # Add a git lookup method for GitVersions
        if not self.name:
            return
        for v in self.versions:
            if isinstance(v, vn.GitVersion) and v._ref_version is None:
                v.attach_lookup(spack.version.git_ref_lookup.GitRefLookup(self.fullname))


def parse_with_version_concrete(string: str, compiler: bool = False):
    """Same as Spec(string), but interprets @x as @=x"""
    s: Union[CompilerSpec, Spec] = CompilerSpec(string) if compiler else Spec(string)
    interpreted_version = s.versions.concrete_range_as_version
    if interpreted_version:
        s.versions = vn.VersionList([interpreted_version])
    return s


def merge_abstract_anonymous_specs(*abstract_specs: Spec):
    """Merge the abstracts specs passed as input and return the result.

    The root specs must be anonymous, and it's duty of the caller to ensure that.

    This function merge the abstract specs based on package names. In particular
    it doesn't try to resolve virtual dependencies.

    Args:
        *abstract_specs: abstract specs to be merged
    """
    merged_spec = spack.spec.Spec()
    for current_spec_constraint in abstract_specs:
        merged_spec.constrain(current_spec_constraint, deps=False)

        for name in merged_spec.common_dependencies(current_spec_constraint):
            merged_spec[name].constrain(current_spec_constraint[name], deps=False)

        # Update with additional constraints from other spec
        for name in current_spec_constraint.direct_dep_difference(merged_spec):
            edge = next(iter(current_spec_constraint.edges_to_dependencies(name)))

            merged_spec._add_dependency(
                edge.spec.copy(), depflag=edge.depflag, virtuals=edge.virtuals
            )

    return merged_spec


def reconstruct_virtuals_on_edges(spec):
    """Reconstruct virtuals on edges. Used to read from old DB and reindex.

    Args:
        spec: spec on which we want to reconstruct virtuals
    """
    # Collect all possible virtuals
    possible_virtuals = set()
    for node in spec.traverse():
        try:
            possible_virtuals.update({x for x in node.package.dependencies if Spec(x).virtual})
        except Exception as e:
            warnings.warn(f"cannot reconstruct virtual dependencies on package {node.name}: {e}")
            continue

    # Assume all incoming edges to provider are marked with virtuals=
    for vspec in possible_virtuals:
        try:
            provider = spec[vspec]
        except KeyError:
            # Virtual not in the DAG
            continue

        for edge in provider.edges_from_dependents():
            edge.update_virtuals([vspec])


class SpecfileReaderBase:
    @classmethod
    def from_node_dict(cls, node):
        spec = Spec()

        name, node = cls.name_and_data(node)
        for h in ht.hashes:
            setattr(spec, h.attr, node.get(h.name, None))

        spec.name = name
        spec.namespace = node.get("namespace", None)

        if "version" in node or "versions" in node:
            spec.versions = vn.VersionList.from_dict(node)
            spec.attach_git_version_lookup()

        if "arch" in node:
            spec.architecture = ArchSpec.from_dict(node)

        if "compiler" in node:
            spec.compiler = CompilerSpec.from_dict(node)
        else:
            spec.compiler = None

        for name, values in node.get("parameters", {}).items():
            if name in _valid_compiler_flags:
                spec.compiler_flags[name] = []
                for val in values:
                    spec.compiler_flags.add_flag(name, val, False)
            else:
                spec.variants[name] = vt.MultiValuedVariant.from_node_dict(name, values)

        spec.external_path = None
        spec.external_modules = None
        if "external" in node:
            # This conditional is needed because sometimes this function is
            # called with a node already constructed that contains a 'versions'
            # and 'external' field. Related to virtual packages provider
            # indexes.
            if node["external"]:
                spec.external_path = node["external"]["path"]
                spec.external_modules = node["external"]["module"]
                if spec.external_modules is False:
                    spec.external_modules = None
                spec.extra_attributes = node["external"].get(
                    "extra_attributes", syaml.syaml_dict()
                )

        # specs read in are concrete unless marked abstract
        if node.get("concrete", True):
            spec._mark_root_concrete()

        if "patches" in node:
            patches = node["patches"]
            if len(patches) > 0:
                mvar = spec.variants.setdefault("patches", vt.MultiValuedVariant("patches", ()))
                mvar.value = patches
                # FIXME: Monkey patches mvar to store patches order
                mvar._patches_in_order_of_appearance = patches

        # Don't read dependencies here; from_dict() is used by
        # from_yaml() and from_json() to read the root *and* each dependency
        # spec.

        return spec

    @classmethod
    def _load(cls, data):
        """Construct a spec from JSON/YAML using the format version 2.

        This format is used in Spack v0.17, was introduced in
        https://github.com/spack/spack/pull/22845

        Args:
            data: a nested dict/list data structure read from YAML or JSON.
        """
        # Current specfile format
        nodes = data["spec"]["nodes"]
        hash_type = None
        any_deps = False

        # Pass 0: Determine hash type
        for node in nodes:
            for _, _, _, dhash_type, _ in cls.dependencies_from_node_dict(node):
                any_deps = True
                if dhash_type:
                    hash_type = dhash_type
                    break

        if not any_deps:  # If we never see a dependency...
            hash_type = ht.dag_hash.name
        elif not hash_type:  # Seen a dependency, still don't know hash_type
            raise spack.error.SpecError(
                "Spec dictionary contains malformed dependencies. Old format?"
            )

        hash_dict = {}
        root_spec_hash = None

        # Pass 1: Create a single lookup dictionary by hash
        for i, node in enumerate(nodes):
            node_hash = node[hash_type]
            node_spec = cls.from_node_dict(node)
            hash_dict[node_hash] = node
            hash_dict[node_hash]["node_spec"] = node_spec
            if i == 0:
                root_spec_hash = node_hash

        if not root_spec_hash:
            raise spack.error.SpecError("Spec dictionary contains no nodes.")

        # Pass 2: Finish construction of all DAG edges (including build specs)
        for node_hash, node in hash_dict.items():
            node_spec = node["node_spec"]
            for _, dhash, dtype, _, virtuals in cls.dependencies_from_node_dict(node):
                node_spec._add_dependency(
                    hash_dict[dhash]["node_spec"],
                    depflag=dt.canonicalize(dtype),
                    virtuals=virtuals,
                )
            if "build_spec" in node.keys():
                _, bhash, _ = cls.build_spec_from_node_dict(node, hash_type=hash_type)
                node_spec._build_spec = hash_dict[bhash]["node_spec"]

        return hash_dict[root_spec_hash]["node_spec"]


class SpecfileV1(SpecfileReaderBase):
    @classmethod
    def load(cls, data):
        """Construct a spec from JSON/YAML using the format version 1.

        Note: Version 1 format has no notion of a build_spec, and names are
        guaranteed to be unique. This function is guaranteed to read specs as
        old as v0.10 - while it was not checked for older formats.

        Args:
            data: a nested dict/list data structure read from YAML or JSON.
        """
        nodes = data["spec"]

        # Read nodes out of list.  Root spec is the first element;
        # dependencies are the following elements.
        dep_list = [cls.from_node_dict(node) for node in nodes]
        if not dep_list:
            raise spack.error.SpecError("specfile contains no nodes.")

        deps = {spec.name: spec for spec in dep_list}
        result = dep_list[0]

        for node in nodes:
            # get dependency dict from the node.
            name, data = cls.name_and_data(node)
            for dname, _, dtypes, _, virtuals in cls.dependencies_from_node_dict(data):
                deps[name]._add_dependency(
                    deps[dname], depflag=dt.canonicalize(dtypes), virtuals=virtuals
                )

        reconstruct_virtuals_on_edges(result)
        return result

    @classmethod
    def name_and_data(cls, node):
        name = next(iter(node))
        node = node[name]
        return name, node

    @classmethod
    def dependencies_from_node_dict(cls, node):
        if "dependencies" not in node:
            return []

        for t in cls.read_specfile_dep_specs(node["dependencies"]):
            yield t

    @classmethod
    def read_specfile_dep_specs(cls, deps, hash_type=ht.dag_hash.name):
        """Read the DependencySpec portion of a YAML-formatted Spec.
        This needs to be backward-compatible with older spack spec
        formats so that reindex will work on old specs/databases.
        """
        for dep_name, elt in deps.items():
            if isinstance(elt, dict):
                for h in ht.hashes:
                    if h.name in elt:
                        dep_hash, deptypes = elt[h.name], elt["type"]
                        hash_type = h.name
                        virtuals = []
                        break
                else:  # We never determined a hash type...
                    raise spack.error.SpecError("Couldn't parse dependency spec.")
            else:
                raise spack.error.SpecError("Couldn't parse dependency types in spec.")
            yield dep_name, dep_hash, list(deptypes), hash_type, list(virtuals)


class SpecfileV2(SpecfileReaderBase):
    @classmethod
    def load(cls, data):
        result = cls._load(data)
        reconstruct_virtuals_on_edges(result)
        return result

    @classmethod
    def name_and_data(cls, node):
        return node["name"], node

    @classmethod
    def dependencies_from_node_dict(cls, node):
        return cls.read_specfile_dep_specs(node.get("dependencies", []))

    @classmethod
    def read_specfile_dep_specs(cls, deps, hash_type=ht.dag_hash.name):
        """Read the DependencySpec portion of a YAML-formatted Spec.
        This needs to be backward-compatible with older spack spec
        formats so that reindex will work on old specs/databases.
        """
        if not isinstance(deps, list):
            raise spack.error.SpecError("Spec dictionary contains malformed dependencies")

        result = []
        for dep in deps:
            elt = dep
            dep_name = dep["name"]
            if isinstance(elt, dict):
                # new format: elements of dependency spec are keyed.
                for h in ht.hashes:
                    if h.name in elt:
                        dep_hash, deptypes, hash_type, virtuals = cls.extract_info_from_dep(elt, h)
                        break
                else:  # We never determined a hash type...
                    raise spack.error.SpecError("Couldn't parse dependency spec.")
            else:
                raise spack.error.SpecError("Couldn't parse dependency types in spec.")
            result.append((dep_name, dep_hash, list(deptypes), hash_type, list(virtuals)))
        return result

    @classmethod
    def extract_info_from_dep(cls, elt, hash):
        dep_hash, deptypes = elt[hash.name], elt["type"]
        hash_type = hash.name
        virtuals = []
        return dep_hash, deptypes, hash_type, virtuals

    @classmethod
    def build_spec_from_node_dict(cls, node, hash_type=ht.dag_hash.name):
        build_spec_dict = node["build_spec"]
        return build_spec_dict["name"], build_spec_dict[hash_type], hash_type


class SpecfileV3(SpecfileV2):
    pass


class SpecfileV4(SpecfileV2):
    @classmethod
    def extract_info_from_dep(cls, elt, hash):
        dep_hash = elt[hash.name]
        deptypes = elt["parameters"]["deptypes"]
        hash_type = hash.name
        virtuals = elt["parameters"]["virtuals"]
        return dep_hash, deptypes, hash_type, virtuals

    @classmethod
    def load(cls, data):
        return cls._load(data)


class LazySpecCache(collections.defaultdict):
    """Cache for Specs that uses a spec_like as key, and computes lazily
    the corresponding value ``Spec(spec_like``.
    """

    def __init__(self):
        super().__init__(Spec)

    def __missing__(self, key):
        value = self.default_factory(key)
        self[key] = value
        return value


def save_dependency_specfiles(root: Spec, output_directory: str, dependencies: List[Spec]):
    """Given a root spec (represented as a yaml object), index it with a subset
    of its dependencies, and write each dependency to a separate yaml file
    in the output directory.  By default, all dependencies will be written
    out.  To choose a smaller subset of dependencies to be written, pass a
    list of package names in the dependencies parameter. If the format of the
    incoming spec is not json, that can be specified with the spec_format
    parameter. This can be used to convert from yaml specfiles to the
    json format."""

    for spec in root.traverse():
        if not any(spec.satisfies(dep) for dep in dependencies):
            continue

        json_path = os.path.join(output_directory, f"{spec.name}.json")

        with open(json_path, "w") as fd:
            fd.write(spec.to_json(hash=ht.dag_hash))


def get_host_environment_metadata() -> Dict[str, str]:
    """Get the host environment, reduce to a subset that we can store in
    the install directory, and add the spack version.
    """
    import spack.main

    environ = get_host_environment()
    return {
        "host_os": environ["os"],
        "platform": environ["platform"],
        "host_target": environ["target"],
        "hostname": environ["hostname"],
        "spack_version": spack.main.get_version(),
        "kernel_version": platform.version(),
    }


def get_host_environment() -> Dict[str, Any]:
    """Return a dictionary (lookup) with host information (not including the
    os.environ).
    """
    host_platform = spack.platforms.host()
    host_target = host_platform.target("default_target")
    host_os = host_platform.operating_system("default_os")
    arch_fmt = "platform={0} os={1} target={2}"
    arch_spec = Spec(arch_fmt.format(host_platform, host_os, host_target))
    return {
        "target": str(host_target),
        "os": str(host_os),
        "platform": str(host_platform),
        "arch": arch_spec,
        "architecture": arch_spec,
        "arch_str": str(arch_spec),
        "hostname": socket.gethostname(),
    }


class SpecParseError(spack.error.SpecError):
    """Wrapper for ParseError for when we're parsing specs."""

    def __init__(self, parse_error):
        super().__init__(parse_error.message)
        self.string = parse_error.string
        self.pos = parse_error.pos

    @property
    def long_message(self):
        return "\n".join(
            [
                "  Encountered when parsing spec:",
                "    %s" % self.string,
                "    %s^" % (" " * self.pos),
            ]
        )


class ArchitecturePropagationError(spack.error.SpecError):
    """Raised when the double equal symbols are used to assign
    the spec's architecture.
    """


class DuplicateDependencyError(spack.error.SpecError):
    """Raised when the same dependency occurs in a spec twice."""


class MultipleVersionError(spack.error.SpecError):
    """Raised when version constraints occur in a spec twice."""


class DuplicateCompilerSpecError(spack.error.SpecError):
    """Raised when the same compiler occurs in a spec twice."""


class UnsupportedCompilerError(spack.error.SpecError):
    """Raised when the user asks for a compiler spack doesn't know about."""

    def __init__(self, compiler_name):
        super().__init__("The '%s' compiler is not yet supported." % compiler_name)


class DuplicateArchitectureError(spack.error.SpecError):
    """Raised when the same architecture occurs in a spec twice."""


class InconsistentSpecError(spack.error.SpecError):
    """Raised when two nodes in the same spec DAG have inconsistent
    constraints."""


class InvalidDependencyError(spack.error.SpecError):
    """Raised when a dependency in a spec is not actually a dependency
    of the package."""

    def __init__(self, pkg, deps):
        self.invalid_deps = deps
        super().__init__(
            "Package {0} does not depend on {1}".format(pkg, llnl.string.comma_or(deps))
        )


class NoProviderError(spack.error.SpecError):
    """Raised when there is no package that provides a particular
    virtual dependency.
    """

    def __init__(self, vpkg):
        super().__init__("No providers found for virtual package: '%s'" % vpkg)
        self.vpkg = vpkg


class MultipleProviderError(spack.error.SpecError):
    """Raised when there is no package that provides a particular
    virtual dependency.
    """

    def __init__(self, vpkg, providers):
        """Takes the name of the vpkg"""
        super().__init__(
            "Multiple providers found for '%s': %s" % (vpkg, [str(s) for s in providers])
        )
        self.vpkg = vpkg
        self.providers = providers


class UnsatisfiableSpecNameError(spack.error.UnsatisfiableSpecError):
    """Raised when two specs aren't even for the same package."""

    def __init__(self, provided, required):
        super().__init__(provided, required, "name")


class UnsatisfiableVersionSpecError(spack.error.UnsatisfiableSpecError):
    """Raised when a spec version conflicts with package constraints."""

    def __init__(self, provided, required):
        super().__init__(provided, required, "version")


class UnsatisfiableCompilerSpecError(spack.error.UnsatisfiableSpecError):
    """Raised when a spec comiler conflicts with package constraints."""

    def __init__(self, provided, required):
        super().__init__(provided, required, "compiler")


class UnsatisfiableCompilerFlagSpecError(spack.error.UnsatisfiableSpecError):
    """Raised when a spec variant conflicts with package constraints."""

    def __init__(self, provided, required):
        super().__init__(provided, required, "compiler_flags")


class UnsatisfiableArchitectureSpecError(spack.error.UnsatisfiableSpecError):
    """Raised when a spec architecture conflicts with package constraints."""

    def __init__(self, provided, required):
        super().__init__(provided, required, "architecture")


class UnsatisfiableProviderSpecError(spack.error.UnsatisfiableSpecError):
    """Raised when a provider is supplied but constraints don't match
    a vpkg requirement"""

    def __init__(self, provided, required):
        super().__init__(provided, required, "provider")


# TODO: get rid of this and be more specific about particular incompatible
# dep constraints
class UnsatisfiableDependencySpecError(spack.error.UnsatisfiableSpecError):
    """Raised when some dependency of constrained specs are incompatible"""

    def __init__(self, provided, required):
        super().__init__(provided, required, "dependency")


class UnconstrainableDependencySpecError(spack.error.SpecError):
    """Raised when attempting to constrain by an anonymous dependency spec"""

    def __init__(self, spec):
        msg = "Cannot constrain by spec '%s'. Cannot constrain by a" % spec
        msg += " spec containing anonymous dependencies"
        super().__init__(msg)


class AmbiguousHashError(spack.error.SpecError):
    def __init__(self, msg, *specs):
        spec_fmt = "{namespace}.{name}{@version}{%compiler}{compiler_flags}"
        spec_fmt += "{variants}{arch=architecture}{/hash:7}"
        specs_str = "\n  " + "\n  ".join(spec.format(spec_fmt) for spec in specs)
        super().__init__(msg + specs_str)


class InvalidHashError(spack.error.SpecError):
    def __init__(self, spec, hash):
        msg = f"No spec with hash {hash} could be found to match {spec}."
        msg += " Either the hash does not exist, or it does not match other spec constraints."
        super().__init__(msg)


class SpecFilenameError(spack.error.SpecError):
    """Raised when a spec file name is invalid."""


class NoSuchSpecFileError(SpecFilenameError):
    """Raised when a spec file doesn't exist."""


class SpecFormatStringError(spack.error.SpecError):
    """Called for errors in Spec format strings."""


class SpecFormatPathError(spack.error.SpecError):
    """Called for errors in Spec path-format strings."""


class SpecFormatSigilError(SpecFormatStringError):
    """Called for mismatched sigils and attributes in format strings"""

    def __init__(self, sigil, requirement, used):
        msg = "The sigil %s may only be used for %s." % (sigil, requirement)
        msg += " It was used with the attribute %s." % used
        super().__init__(msg)


class ConflictsInSpecError(spack.error.SpecError, RuntimeError):
    def __init__(self, spec, matches):
        message = 'Conflicts in concretized spec "{0}"\n'.format(spec.short_spec)

        visited = set()

        long_message = ""

        match_fmt_default = '{0}. "{1}" conflicts with "{2}"\n'
        match_fmt_custom = '{0}. "{1}" conflicts with "{2}" [{3}]\n'

        for idx, (s, c, w, msg) in enumerate(matches):
            if s not in visited:
                visited.add(s)
                long_message += "List of matching conflicts for spec:\n\n"
                long_message += s.tree(indent=4) + "\n"

            if msg is None:
                long_message += match_fmt_default.format(idx + 1, c, w)
            else:
                long_message += match_fmt_custom.format(idx + 1, c, w, msg)

        super().__init__(message, long_message)


class SpecDeprecatedError(spack.error.SpecError):
    """Raised when a spec concretizes to a deprecated spec or dependency."""


class InvalidSpecDetected(spack.error.SpecError):
    """Raised when a detected spec doesn't pass validation checks."""


class SpliceError(spack.error.SpecError):
    """Raised when a splice is not possible due to dependency or provider
    satisfaction mismatch. The resulting splice would be unusable."""