    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

    use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation};
    use std::collections::{BTreeMap, BTreeSet, HashMap};
    use std::ffi::OsStr;
    use std::path::{Path, PathBuf};
    use std::rc::Rc;
    use std::str::{self, FromStr};

    use crate::AlreadyPrintedError;
    use anyhow::{anyhow, bail, Context as _};
    use cargo_platform::Platform;
    use cargo_util::paths;
    use cargo_util_schemas::manifest;
    use cargo_util_schemas::manifest::RustVersion;
    use itertools::Itertools;
    use lazycell::LazyCell;
    use pathdiff::diff_paths;
    use tracing::{debug, trace};
    use url::Url;

    use crate::core::compiler::{CompileKind, CompileTarget};
    use crate::core::dependency::{Artifact, ArtifactTarget, DepKind};
    use crate::core::manifest::{ManifestMetadata, TargetSourcePath, Warnings};
    use crate::core::resolver::ResolveBehavior;
    use crate::core::{find_workspace_root, resolve_relative_path, CliUnstable};
    use crate::core::{Dependency, Manifest, PackageId, Summary, Target};
    use crate::core::{Edition, EitherManifest, Feature, Features, VirtualManifest, Workspace};
    use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
    use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
    use crate::util::errors::{CargoResult, ManifestError};
    use crate::util::interning::InternedString;
    use crate::util::{self, config::ConfigRelativePath, Config, IntoUrl, OptVersionReq};

    mod embedded;
    mod targets;
    use self::targets::targets;

    /// Loads a `Cargo.toml` from a file on disk.
    ///
    /// This could result in a real or virtual manifest being returned.
    ///
    /// A list of nested paths is also returned, one for each path dependency
    /// within the manifest. For virtual manifests, these paths can only
    /// come from patched or replaced dependencies. These paths are not
    /// canonicalized.
    pub fn read_manifest(
        path: &Path,
        source_id: SourceId,
        config: &Config,
    ) -> CargoResult<(EitherManifest, Vec<PathBuf>)> {
        trace!(
            "read_manifest; path={}; source-id={}",
            path.display(),
            source_id
        );
        let mut contents = paths::read(path).map_err(|err| ManifestError::new(err, path.into()))?;
        let embedded = is_embedded(path);
        if embedded {
            if !config.cli_unstable().script {
                return Err(ManifestError::new(
                    anyhow::anyhow!("parsing `{}` requires `-Zscript`", path.display()),
                    path.into(),
                ))?;
            }
            contents = embedded::expand_manifest(&contents, path, config)
                .map_err(|err| ManifestError::new(err, path.into()))?;
        }

        read_manifest_from_str(&contents, path, embedded, source_id, config).map_err(|err| {
            if err.is::<AlreadyPrintedError>() {
                err
            } else {
                ManifestError::new(
                    err.context(format!("failed to parse manifest at `{}`", path.display())),
                    path.into(),
                )
                .into()
            }
        })
    }

    /// See also `bin/cargo/commands/run.rs`s `is_manifest_command`
    pub fn is_embedded(path: &Path) -> bool {
        let ext = path.extension();
        ext == Some(OsStr::new("rs")) ||
            // Provide better errors by not considering directories to be embedded manifests
            (ext.is_none() && path.is_file())
    }

    /// Parse an already-loaded `Cargo.toml` as a Cargo manifest.
    ///
    /// This could result in a real or virtual manifest being returned.
    ///
    /// A list of nested paths is also returned, one for each path dependency
    /// within the manifest. For virtual manifests, these paths can only
    /// come from patched or replaced dependencies. These paths are not
    /// canonicalized.
    fn read_manifest_from_str(
        contents: &str,
        manifest_file: &Path,
        embedded: bool,
        source_id: SourceId,
        config: &Config,
    ) -> CargoResult<(EitherManifest, Vec<PathBuf>)> {
        let package_root = manifest_file.parent().unwrap();

        let mut unused = BTreeSet::new();
        let deserializer = toml::de::Deserializer::new(contents);
        let manifest: manifest::TomlManifest = match serde_ignored::deserialize(deserializer, |path| {
            let mut key = String::new();
            stringify(&mut key, &path);
            unused.insert(key);
        }) {
            Ok(manifest) => manifest,
            Err(e) => {
                let Some(span) = e.span() else {
                    return Err(e.into());
                };

                let (line_num, column) = translate_position(&contents, span.start);
                let source_start = contents[0..span.start]
                    .rfind('\n')
                    .map(|s| s + 1)
                    .unwrap_or(0);
                let source_end = contents[span.end.saturating_sub(1)..]
                    .find('\n')
                    .map(|s| s + span.end)
                    .unwrap_or(contents.len());
                let source = &contents[source_start..source_end];
                // Make sure we don't try to highlight past the end of the line,
                // but also make sure we are highlighting at least one character
                let highlight_end = (column + contents[span].chars().count())
                    .min(source.len())
                    .max(column + 1);
                // Get the path to the manifest, relative to the cwd
                let manifest_path = diff_paths(manifest_file, config.cwd())
                    .unwrap_or_else(|| manifest_file.to_path_buf())
                    .display()
                    .to_string();
                let snippet = Snippet {
                    title: Some(Annotation {
                        id: None,
                        label: Some(e.message()),
                        annotation_type: AnnotationType::Error,
                    }),
                    footer: vec![],
                    slices: vec![Slice {
                        source: &source,
                        line_start: line_num + 1,
                        origin: Some(manifest_path.as_str()),
                        annotations: vec![SourceAnnotation {
                            range: (column, highlight_end),
                            label: "",
                            annotation_type: AnnotationType::Error,
                        }],
                        fold: false,
                    }],
                };
                let renderer = Renderer::styled();
                writeln!(config.shell().err(), "{}", renderer.render(snippet))?;
                return Err(AlreadyPrintedError::new(e.into()).into());
            }
        };
        let add_unused = |warnings: &mut Warnings| {
            for key in unused {
                warnings.add_warning(format!("unused manifest key: {}", key));
                if key == "profiles.debug" {
                    warnings.add_warning("use `[profile.dev]` to configure debug builds".to_string());
                }
            }
        };

        if let Some(deps) = manifest
            .workspace
            .as_ref()
            .and_then(|ws| ws.dependencies.as_ref())
        {
            for (name, dep) in deps {
                if dep.is_optional() {
                    bail!("{name} is optional, but workspace dependencies cannot be optional",);
                }
                if dep.is_public() {
                    bail!("{name} is public, but workspace dependencies cannot be public",);
                }
            }
        }
        return if manifest.project.is_some() || manifest.package.is_some() {
            let (mut manifest, paths) =
                to_real_manifest(manifest, embedded, source_id, package_root, config)?;
            add_unused(manifest.warnings_mut());
            if manifest.targets().iter().all(|t| t.is_custom_build()) {
                bail!(
                    "no targets specified in the manifest\n\
                     either src/lib.rs, src/main.rs, a [lib] section, or \
                     [[bin]] section must be present"
                )
            }
            Ok((EitherManifest::Real(manifest), paths))
        } else {
            let (mut m, paths) = to_virtual_manifest(manifest, source_id, package_root, config)?;
            add_unused(m.warnings_mut());
            Ok((EitherManifest::Virtual(m), paths))
        };

        fn stringify(dst: &mut String, path: &serde_ignored::Path<'_>) {
            use serde_ignored::Path;

            match *path {
                Path::Root => {}
                Path::Seq { parent, index } => {
                    stringify(dst, parent);
                    if !dst.is_empty() {
                        dst.push('.');
                    }
                    dst.push_str(&index.to_string());
                }
                Path::Map { parent, ref key } => {
                    stringify(dst, parent);
                    if !dst.is_empty() {
                        dst.push('.');
                    }
                    dst.push_str(key);
                }
                Path::Some { parent }
                | Path::NewtypeVariant { parent }
                | Path::NewtypeStruct { parent } => stringify(dst, parent),
            }
        }
    }

    /// Warn about paths that have been deprecated and may conflict.
    fn warn_on_deprecated(new_path: &str, name: &str, kind: &str, warnings: &mut Vec<String>) {
        let old_path = new_path.replace("-", "_");
        warnings.push(format!(
            "conflicting between `{new_path}` and `{old_path}` in the `{name}` {kind}.\n
            `{old_path}` is ignored and not recommended for use in the future"
        ))
    }

    /// Prepares the manifest for publishing.
    // - Path and git components of dependency specifications are removed.
    // - License path is updated to point within the package.
    pub fn prepare_for_publish(
        me: &manifest::TomlManifest,
        ws: &Workspace<'_>,
        package_root: &Path,
    ) -> CargoResult<manifest::TomlManifest> {
        let config = ws.config();
        let mut package = me.package().unwrap().clone();
        package.workspace = None;
        let current_resolver = package
            .resolver
            .as_ref()
            .map(|r| ResolveBehavior::from_manifest(r))
            .unwrap_or_else(|| {
                package
                    .edition
                    .as_ref()
                    .and_then(|e| e.as_value())
                    .map(|e| Edition::from_str(e))
                    .unwrap_or(Ok(Edition::Edition2015))
                    .map(|e| e.default_resolve_behavior())
            })?;
        if ws.resolve_behavior() != current_resolver {
            // This ensures the published crate if built as a root (e.g. `cargo install`) will
            // use the same resolver behavior it was tested with in the workspace.
            // To avoid forcing a higher MSRV we don't explicitly set this if it would implicitly
            // result in the same thing.
            package.resolver = Some(ws.resolve_behavior().to_manifest());
        }
        if let Some(license_file) = &package.license_file {
            let license_file = license_file
                .as_value()
                .context("license file should have been resolved before `prepare_for_publish()`")?;
            let license_path = Path::new(&license_file);
            let abs_license_path = paths::normalize_path(&package_root.join(license_path));
            if abs_license_path.strip_prefix(package_root).is_err() {
                // This path points outside of the package root. `cargo package`
                // will copy it into the root, so adjust the path to this location.
                package.license_file = Some(manifest::InheritableField::Value(
                    license_path
                        .file_name()
                        .unwrap()
                        .to_str()
                        .unwrap()
                        .to_string(),
                ));
            }
        }

        if let Some(readme) = &package.readme {
            let readme = readme
                .as_value()
                .context("readme should have been resolved before `prepare_for_publish()`")?;
            match readme {
                manifest::StringOrBool::String(readme) => {
                    let readme_path = Path::new(&readme);
                    let abs_readme_path = paths::normalize_path(&package_root.join(readme_path));
                    if abs_readme_path.strip_prefix(package_root).is_err() {
                        // This path points outside of the package root. `cargo package`
                        // will copy it into the root, so adjust the path to this location.
                        package.readme = Some(manifest::InheritableField::Value(
                            manifest::StringOrBool::String(
                                readme_path
                                    .file_name()
                                    .unwrap()
                                    .to_str()
                                    .unwrap()
                                    .to_string(),
                            ),
                        ));
                    }
                }
                manifest::StringOrBool::Bool(_) => {}
            }
        }
        let all = |_d: &manifest::TomlDependency| true;
        return Ok(manifest::TomlManifest {
            package: Some(package),
            project: None,
            profile: me.profile.clone(),
            lib: me.lib.clone(),
            bin: me.bin.clone(),
            example: me.example.clone(),
            test: me.test.clone(),
            bench: me.bench.clone(),
            dependencies: map_deps(config, me.dependencies.as_ref(), all)?,
            dev_dependencies: map_deps(
                config,
                me.dev_dependencies(),
                manifest::TomlDependency::is_version_specified,
            )?,
            dev_dependencies2: None,
            build_dependencies: map_deps(config, me.build_dependencies(), all)?,
            build_dependencies2: None,
            features: me.features.clone(),
            target: match me.target.as_ref().map(|target_map| {
                target_map
                    .iter()
                    .map(|(k, v)| {
                        Ok((
                            k.clone(),
                            manifest::TomlPlatform {
                                dependencies: map_deps(config, v.dependencies.as_ref(), all)?,
                                dev_dependencies: map_deps(
                                    config,
                                    v.dev_dependencies(),
                                    manifest::TomlDependency::is_version_specified,
                                )?,
                                dev_dependencies2: None,
                                build_dependencies: map_deps(config, v.build_dependencies(), all)?,
                                build_dependencies2: None,
                            },
                        ))
                    })
                    .collect()
            }) {
                Some(Ok(v)) => Some(v),
                Some(Err(e)) => return Err(e),
                None => None,
            },
            replace: None,
            patch: None,
            workspace: None,
            badges: me.badges.clone(),
            cargo_features: me.cargo_features.clone(),
            lints: me.lints.clone(),
        });

        fn map_deps(
            config: &Config,
            deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
            filter: impl Fn(&manifest::TomlDependency) -> bool,
        ) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
            let Some(deps) = deps else { return Ok(None) };
            let deps = deps
                .iter()
                .filter(|(_k, v)| {
                    if let manifest::InheritableDependency::Value(def) = v {
                        filter(def)
                    } else {
                        false
                    }
                })
                .map(|(k, v)| Ok((k.clone(), map_dependency(config, v)?)))
                .collect::<CargoResult<BTreeMap<_, _>>>()?;
            Ok(Some(deps))
        }

        fn map_dependency(
            config: &Config,
            dep: &manifest::InheritableDependency,
        ) -> CargoResult<manifest::InheritableDependency> {
            let dep = match dep {
                manifest::InheritableDependency::Value(manifest::TomlDependency::Detailed(d)) => {
                    let mut d = d.clone();
                    // Path dependencies become crates.io deps.
                    d.path.take();
                    // Same with git dependencies.
                    d.git.take();
                    d.branch.take();
                    d.tag.take();
                    d.rev.take();
                    // registry specifications are elaborated to the index URL
                    if let Some(registry) = d.registry.take() {
                        d.registry_index = Some(config.get_registry_index(&registry)?.to_string());
                    }
                    Ok(d)
                }
                manifest::InheritableDependency::Value(manifest::TomlDependency::Simple(s)) => {
                    Ok(manifest::TomlDetailedDependency {
                        version: Some(s.clone()),
                        ..Default::default()
                    })
                }
                _ => unreachable!(),
            };
            dep.map(manifest::TomlDependency::Detailed)
                .map(manifest::InheritableDependency::Value)
        }
    }

    pub fn to_real_manifest(
        me: manifest::TomlManifest,
        embedded: bool,
        source_id: SourceId,
        package_root: &Path,
        config: &Config,
    ) -> CargoResult<(Manifest, Vec<PathBuf>)> {
        fn get_ws(
            config: &Config,
            resolved_path: &Path,
            workspace_config: &WorkspaceConfig,
        ) -> CargoResult<InheritableFields> {
            match workspace_config {
                WorkspaceConfig::Root(root) => Ok(root.inheritable().clone()),
                WorkspaceConfig::Member {
                    root: Some(ref path_to_root),
                } => {
                    let path = resolved_path
                        .parent()
                        .unwrap()
                        .join(path_to_root)
                        .join("Cargo.toml");
                    let root_path = paths::normalize_path(&path);
                    inheritable_from_path(config, root_path)
                }
                WorkspaceConfig::Member { root: None } => {
                    match find_workspace_root(&resolved_path, config)? {
                        Some(path_to_root) => inheritable_from_path(config, path_to_root),
                        None => Err(anyhow!("failed to find a workspace root")),
                    }
                }
            }
        }

        if !package_root.is_dir() {
            bail!(
                "package root '{}' is not a directory",
                package_root.display()
            );
        };

        let mut nested_paths = vec![];
        let mut warnings = vec![];
        let mut errors = vec![];

        // Parse features first so they will be available when parsing other parts of the TOML.
        let empty = Vec::new();
        let cargo_features = me.cargo_features.as_ref().unwrap_or(&empty);
        let features = Features::new(cargo_features, config, &mut warnings, source_id.is_path())?;

        let mut package = match (&me.package, &me.project) {
            (Some(_), Some(project)) => {
                if source_id.is_path() {
                    config.shell().warn(format!(
                        "manifest at `{}` contains both `project` and `package`, \
                        this could become a hard error in the future",
                        package_root.display()
                    ))?;
                }
                project.clone()
            }
            (Some(package), None) => package.clone(),
            (None, Some(project)) => {
                if source_id.is_path() {
                    config.shell().warn(format!(
                        "manifest at `{}` contains `[project]` instead of `[package]`, \
                                    this could become a hard error in the future",
                        package_root.display()
                    ))?;
                }
                project.clone()
            }
            (None, None) => bail!("no `package` section found"),
        };

        let workspace_config = match (me.workspace.as_ref(), package.workspace.as_ref()) {
            (Some(toml_config), None) => {
                let lints = toml_config.lints.clone();
                let lints = verify_lints(lints)?;
                let inheritable = InheritableFields {
                    package: toml_config.package.clone(),
                    dependencies: toml_config.dependencies.clone(),
                    lints,
                    _ws_root: package_root.to_path_buf(),
                };
                if let Some(ws_deps) = &inheritable.dependencies {
                    for (name, dep) in ws_deps {
                        unused_dep_keys(
                            name,
                            "workspace.dependencies",
                            dep.unused_keys(),
                            &mut warnings,
                        );
                    }
                }
                let ws_root_config = WorkspaceRootConfig::new(
                    package_root,
                    &toml_config.members,
                    &toml_config.default_members,
                    &toml_config.exclude,
                    &Some(inheritable),
                    &toml_config.metadata,
                );
                config
                    .ws_roots
                    .borrow_mut()
                    .insert(package_root.to_path_buf(), ws_root_config.clone());
                WorkspaceConfig::Root(ws_root_config)
            }
            (None, root) => WorkspaceConfig::Member {
                root: root.cloned(),
            },
            (Some(..), Some(..)) => bail!(
                "cannot configure both `package.workspace` and \
                     `[workspace]`, only one can be specified"
            ),
        };

        let package_name = package.name.trim();

        let resolved_path = package_root.join("Cargo.toml");

        let inherit_cell: LazyCell<InheritableFields> = LazyCell::new();
        let inherit =
            || inherit_cell.try_borrow_with(|| get_ws(config, &resolved_path, &workspace_config));

        let version = package
            .version
            .clone()
            .map(|version| field_inherit_with(version, "version", || inherit()?.version()))
            .transpose()?;

        package.version = version.clone().map(manifest::InheritableField::Value);

        let pkgid = PackageId::new(
            package.name.as_str().into(),
            version
                .clone()
                .unwrap_or_else(|| semver::Version::new(0, 0, 0)),
            source_id,
        );

        let edition = if let Some(edition) = package.edition.clone() {
            let edition: Edition = field_inherit_with(edition, "edition", || inherit()?.edition())?
                .parse()
                .with_context(|| "failed to parse the `edition` key")?;
            package.edition = Some(manifest::InheritableField::Value(edition.to_string()));
            edition
        } else {
            Edition::Edition2015
        };
        // Add these lines if start a new unstable edition.
        // ```
        // if edition == Edition::Edition20xx {
        //     features.require(Feature::edition20xx())?;
        // }
        // ```
        if edition == Edition::Edition2024 {
            features.require(Feature::edition2024())?;
        } else if !edition.is_stable() {
            // Guard in case someone forgets to add .require()
            return Err(util::errors::internal(format!(
                "edition {} should be gated",
                edition
            )));
        }

        let rust_version = if let Some(rust_version) = &package.rust_version {
            let rust_version = field_inherit_with(rust_version.clone(), "rust_version", || {
                inherit()?.rust_version()
            })?;
            let req = rust_version.to_caret_req();
            if let Some(first_version) = edition.first_version() {
                let unsupported =
                    semver::Version::new(first_version.major, first_version.minor - 1, 9999);
                if req.matches(&unsupported) {
                    bail!(
                        "rust-version {} is older than first version ({}) required by \
                                the specified edition ({})",
                        rust_version,
                        first_version,
                        edition,
                    )
                }
            }
            Some(rust_version)
        } else {
            None
        };

        if package.metabuild.is_some() {
            features.require(Feature::metabuild())?;
        }

        let resolve_behavior = match (
            package.resolver.as_ref(),
            me.workspace.as_ref().and_then(|ws| ws.resolver.as_ref()),
        ) {
            (None, None) => None,
            (Some(s), None) | (None, Some(s)) => Some(ResolveBehavior::from_manifest(s)?),
            (Some(_), Some(_)) => {
                bail!("cannot specify `resolver` field in both `[workspace]` and `[package]`")
            }
        };

        // If we have no lib at all, use the inferred lib, if available.
        // If we have a lib with a path, we're done.
        // If we have a lib with no path, use the inferred lib or else the package name.
        let targets = targets(
            &features,
            &me,
            package_name,
            package_root,
            edition,
            &package.build,
            &package.metabuild,
            &mut warnings,
            &mut errors,
        )?;

        if targets.is_empty() {
            debug!("manifest has no build targets");
        }

        if let Err(conflict_targets) = unique_build_targets(&targets, package_root) {
            conflict_targets
                .iter()
                .for_each(|(target_path, conflicts)| {
                    warnings.push(format!(
                        "file `{}` found to be present in multiple \
                     build targets:\n{}",
                        target_path.display().to_string(),
                        conflicts
                            .iter()
                            .map(|t| format!("  * `{}` target `{}`", t.kind().description(), t.name(),))
                            .join("\n")
                    ));
                })
        }

        if let Some(links) = &package.links {
            if !targets.iter().any(|t| t.is_custom_build()) {
                bail!(
                    "package `{}` specifies that it links to `{}` but does not \
                         have a custom build script",
                    pkgid,
                    links
                )
            }
        }

        let mut deps = Vec::new();

        let mut cx = Context {
            deps: &mut deps,
            source_id,
            nested_paths: &mut nested_paths,
            config,
            warnings: &mut warnings,
            features: &features,
            platform: None,
            root: package_root,
        };

        fn process_dependencies(
            cx: &mut Context<'_, '_>,
            new_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
            kind: Option<DepKind>,
            workspace_config: &WorkspaceConfig,
            inherit_cell: &LazyCell<InheritableFields>,
        ) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
            let Some(dependencies) = new_deps else {
                return Ok(None);
            };

            let inheritable = || {
                inherit_cell.try_borrow_with(|| {
                    get_ws(cx.config, &cx.root.join("Cargo.toml"), &workspace_config)
                })
            };

            let mut deps: BTreeMap<manifest::PackageName, manifest::InheritableDependency> =
                BTreeMap::new();
            for (n, v) in dependencies.iter() {
                let resolved = dependency_inherit_with(v.clone(), n, inheritable, cx)?;
                let dep = dep_to_dependency(&resolved, n, cx, kind)?;
                let name_in_toml = dep.name_in_toml().as_str();
                let kind_name = match kind {
                    Some(k) => k.kind_table(),
                    None => "dependencies",
                };
                let table_in_toml = if let Some(platform) = &cx.platform {
                    format!("target.{}.{kind_name}", platform.to_string())
                } else {
                    kind_name.to_string()
                };
                unused_dep_keys(name_in_toml, &table_in_toml, v.unused_keys(), cx.warnings);
                cx.deps.push(dep);
                deps.insert(
                    n.clone(),
                    manifest::InheritableDependency::Value(resolved.clone()),
                );
            }
            Ok(Some(deps))
        }

        // Collect the dependencies.
        let dependencies = process_dependencies(
            &mut cx,
            me.dependencies.as_ref(),
            None,
            &workspace_config,
            &inherit_cell,
        )?;
        if me.dev_dependencies.is_some() && me.dev_dependencies2.is_some() {
            warn_on_deprecated("dev-dependencies", package_name, "package", cx.warnings);
        }
        let dev_deps = me.dev_dependencies();
        let dev_deps = process_dependencies(
            &mut cx,
            dev_deps,
            Some(DepKind::Development),
            &workspace_config,
            &inherit_cell,
        )?;
        if me.build_dependencies.is_some() && me.build_dependencies2.is_some() {
            warn_on_deprecated("build-dependencies", package_name, "package", cx.warnings);
        }
        let build_deps = me.build_dependencies();
        let build_deps = process_dependencies(
            &mut cx,
            build_deps,
            Some(DepKind::Build),
            &workspace_config,
            &inherit_cell,
        )?;

        let lints = me
            .lints
            .clone()
            .map(|mw| lints_inherit_with(mw, || inherit()?.lints()))
            .transpose()?;
        let lints = verify_lints(lints)?;
        let default = manifest::TomlLints::default();
        let rustflags = lints_to_rustflags(lints.as_ref().unwrap_or(&default));

        let mut target: BTreeMap<String, manifest::TomlPlatform> = BTreeMap::new();
        for (name, platform) in me.target.iter().flatten() {
            cx.platform = {
                let platform: Platform = name.parse()?;
                platform.check_cfg_attributes(cx.warnings);
                Some(platform)
            };
            let deps = process_dependencies(
                &mut cx,
                platform.dependencies.as_ref(),
                None,
                &workspace_config,
                &inherit_cell,
            )?;
            if platform.build_dependencies.is_some() && platform.build_dependencies2.is_some() {
                warn_on_deprecated("build-dependencies", name, "platform target", cx.warnings);
            }
            let build_deps = platform.build_dependencies();
            let build_deps = process_dependencies(
                &mut cx,
                build_deps,
                Some(DepKind::Build),
                &workspace_config,
                &inherit_cell,
            )?;
            if platform.dev_dependencies.is_some() && platform.dev_dependencies2.is_some() {
                warn_on_deprecated("dev-dependencies", name, "platform target", cx.warnings);
            }
            let dev_deps = platform.dev_dependencies();
            let dev_deps = process_dependencies(
                &mut cx,
                dev_deps,
                Some(DepKind::Development),
                &workspace_config,
                &inherit_cell,
            )?;
            target.insert(
                name.clone(),
                manifest::TomlPlatform {
                    dependencies: deps,
                    build_dependencies: build_deps,
                    build_dependencies2: None,
                    dev_dependencies: dev_deps,
                    dev_dependencies2: None,
                },
            );
        }

        let target = if target.is_empty() {
            None
        } else {
            Some(target)
        };
        let replace = replace(&me, &mut cx)?;
        let patch = patch(&me, &mut cx)?;

        {
            let mut names_sources = BTreeMap::new();
            for dep in &deps {
                let name = dep.name_in_toml();
                let prev = names_sources.insert(name, dep.source_id());
                if prev.is_some() && prev != Some(dep.source_id()) {
                    bail!(
                        "Dependency '{}' has different source paths depending on the build \
                             target. Each dependency must have a single canonical source path \
                             irrespective of build target.",
                        name
                    );
                }
            }
        }

        let exclude = package
            .exclude
            .clone()
            .map(|mw| field_inherit_with(mw, "exclude", || inherit()?.exclude()))
            .transpose()?
            .unwrap_or_default();
        let include = package
            .include
            .clone()
            .map(|mw| field_inherit_with(mw, "include", || inherit()?.include()))
            .transpose()?
            .unwrap_or_default();
        let empty_features = BTreeMap::new();

        let summary = Summary::new(
            pkgid,
            deps,
            &me.features
                .as_ref()
                .unwrap_or(&empty_features)
                .iter()
                .map(|(k, v)| {
                    (
                        InternedString::new(k),
                        v.iter().map(InternedString::from).collect(),
                    )
                })
                .collect(),
            package.links.as_deref(),
            rust_version.clone(),
        )?;

        let metadata = ManifestMetadata {
            description: package
                .description
                .clone()
                .map(|mw| field_inherit_with(mw, "description", || inherit()?.description()))
                .transpose()?,
            homepage: package
                .homepage
                .clone()
                .map(|mw| field_inherit_with(mw, "homepage", || inherit()?.homepage()))
                .transpose()?,
            documentation: package
                .documentation
                .clone()
                .map(|mw| field_inherit_with(mw, "documentation", || inherit()?.documentation()))
                .transpose()?,
            readme: readme_for_package(
                package_root,
                package
                    .readme
                    .clone()
                    .map(|mw| field_inherit_with(mw, "readme", || inherit()?.readme(package_root)))
                    .transpose()?
                    .as_ref(),
            ),
            authors: package
                .authors
                .clone()
                .map(|mw| field_inherit_with(mw, "authors", || inherit()?.authors()))
                .transpose()?
                .unwrap_or_default(),
            license: package
                .license
                .clone()
                .map(|mw| field_inherit_with(mw, "license", || inherit()?.license()))
                .transpose()?,
            license_file: package
                .license_file
                .clone()
                .map(|mw| field_inherit_with(mw, "license", || inherit()?.license_file(package_root)))
                .transpose()?,
            repository: package
                .repository
                .clone()
                .map(|mw| field_inherit_with(mw, "repository", || inherit()?.repository()))
                .transpose()?,
            keywords: package
                .keywords
                .clone()
                .map(|mw| field_inherit_with(mw, "keywords", || inherit()?.keywords()))
                .transpose()?
                .unwrap_or_default(),
            categories: package
                .categories
                .clone()
                .map(|mw| field_inherit_with(mw, "categories", || inherit()?.categories()))
                .transpose()?
                .unwrap_or_default(),
            badges: me
                .badges
                .clone()
                .map(|mw| field_inherit_with(mw, "badges", || inherit()?.badges()))
                .transpose()?
                .unwrap_or_default(),
            links: package.links.clone(),
            rust_version: package
                .rust_version
                .map(|mw| field_inherit_with(mw, "rust-version", || inherit()?.rust_version()))
                .transpose()?,
        };
        package.description = metadata
            .description
            .clone()
            .map(|description| manifest::InheritableField::Value(description));
        package.homepage = metadata
            .homepage
            .clone()
            .map(|homepage| manifest::InheritableField::Value(homepage));
        package.documentation = metadata
            .documentation
            .clone()
            .map(|documentation| manifest::InheritableField::Value(documentation));
        package.readme = metadata
            .readme
            .clone()
            .map(|readme| manifest::InheritableField::Value(manifest::StringOrBool::String(readme)));
        package.authors = package
            .authors
            .as_ref()
            .map(|_| manifest::InheritableField::Value(metadata.authors.clone()));
        package.license = metadata
            .license
            .clone()
            .map(|license| manifest::InheritableField::Value(license));
        package.license_file = metadata
            .license_file
            .clone()
            .map(|license_file| manifest::InheritableField::Value(license_file));
        package.repository = metadata
            .repository
            .clone()
            .map(|repository| manifest::InheritableField::Value(repository));
        package.keywords = package
            .keywords
            .as_ref()
            .map(|_| manifest::InheritableField::Value(metadata.keywords.clone()));
        package.categories = package
            .categories
            .as_ref()
            .map(|_| manifest::InheritableField::Value(metadata.categories.clone()));
        package.rust_version = rust_version
            .clone()
            .map(|rv| manifest::InheritableField::Value(rv));
        package.exclude = package
            .exclude
            .as_ref()
            .map(|_| manifest::InheritableField::Value(exclude.clone()));
        package.include = package
            .include
            .as_ref()
            .map(|_| manifest::InheritableField::Value(include.clone()));

        let profiles = me.profile.clone();
        if let Some(profiles) = &profiles {
            let cli_unstable = config.cli_unstable();
            validate_profiles(profiles, cli_unstable, &features, &mut warnings)?;
        }

        let publish = package
            .publish
            .clone()
            .map(|publish| field_inherit_with(publish, "publish", || inherit()?.publish()).unwrap());

        package.publish = publish
            .clone()
            .map(|p| manifest::InheritableField::Value(p));

        let publish = match publish {
            Some(manifest::VecStringOrBool::VecString(ref vecstring)) => Some(vecstring.clone()),
            Some(manifest::VecStringOrBool::Bool(false)) => Some(vec![]),
            Some(manifest::VecStringOrBool::Bool(true)) => None,
            None => version.is_none().then_some(vec![]),
        };

        if version.is_none() && publish != Some(vec![]) {
            bail!("`package.publish` requires `package.version` be specified");
        }

        if summary.features().contains_key("default-features") {
            warnings.push(
                "`default-features = [\"..\"]` was found in [features]. \
                     Did you mean to use `default = [\"..\"]`?"
                    .to_string(),
            )
        }

        if let Some(run) = &package.default_run {
            if !targets
                .iter()
                .filter(|t| t.is_bin())
                .any(|t| t.name() == run)
            {
                let suggestion =
                    util::closest_msg(run, targets.iter().filter(|t| t.is_bin()), |t| t.name());
                bail!("default-run target `{}` not found{}", run, suggestion);
            }
        }

        let default_kind = package
            .default_target
            .as_ref()
            .map(|t| CompileTarget::new(&*t))
            .transpose()?
            .map(CompileKind::Target);
        let forced_kind = package
            .forced_target
            .as_ref()
            .map(|t| CompileTarget::new(&*t))
            .transpose()?
            .map(CompileKind::Target);
        let custom_metadata = package.metadata.clone();
        let resolved_toml = manifest::TomlManifest {
            cargo_features: me.cargo_features.clone(),
            package: Some(package.clone()),
            project: None,
            profile: me.profile.clone(),
            lib: me.lib.clone(),
            bin: me.bin.clone(),
            example: me.example.clone(),
            test: me.test.clone(),
            bench: me.bench.clone(),
            dependencies,
            dev_dependencies: dev_deps,
            dev_dependencies2: None,
            build_dependencies: build_deps,
            build_dependencies2: None,
            features: me.features.clone(),
            target,
            replace: me.replace.clone(),
            patch: me.patch.clone(),
            workspace: me.workspace.clone(),
            badges: me
                .badges
                .as_ref()
                .map(|_| manifest::InheritableField::Value(metadata.badges.clone())),
            lints: lints.map(|lints| manifest::InheritableLints {
                workspace: false,
                lints,
            }),
        };
        let mut manifest = Manifest::new(
            summary,
            default_kind,
            forced_kind,
            targets,
            exclude,
            include,
            package.links.clone(),
            metadata,
            custom_metadata,
            profiles,
            publish,
            replace,
            patch,
            workspace_config,
            features,
            edition,
            rust_version,
            package.im_a_teapot,
            package.default_run.clone(),
            Rc::new(resolved_toml),
            package.metabuild.clone().map(|sov| sov.0),
            resolve_behavior,
            rustflags,
            embedded,
        );
        if package.license_file.is_some() && package.license.is_some() {
            manifest.warnings_mut().add_warning(
                    "only one of `license` or `license-file` is necessary\n\
                     `license` should be used if the package license can be expressed \
                     with a standard SPDX expression.\n\
                     `license-file` should be used if the package uses a non-standard license.\n\
                     See https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields \
                     for more information."
                        .to_string(),
                );
        }
        for warning in warnings {
            manifest.warnings_mut().add_warning(warning);
        }
        for error in errors {
            manifest.warnings_mut().add_critical_warning(error);
        }

        manifest.feature_gate()?;

        Ok((manifest, nested_paths))
    }

    fn to_virtual_manifest(
        me: manifest::TomlManifest,
        source_id: SourceId,
        root: &Path,
        config: &Config,
    ) -> CargoResult<(VirtualManifest, Vec<PathBuf>)> {
        for field in me.requires_package() {
            bail!("this virtual manifest specifies a `{field}` section, which is not allowed");
        }

        let mut nested_paths = Vec::new();
        let mut warnings = Vec::new();
        let mut deps = Vec::new();
        let empty = Vec::new();
        let cargo_features = me.cargo_features.as_ref().unwrap_or(&empty);
        let features = Features::new(cargo_features, config, &mut warnings, source_id.is_path())?;

        let (replace, patch) = {
            let mut cx = Context {
                deps: &mut deps,
                source_id,
                nested_paths: &mut nested_paths,
                config,
                warnings: &mut warnings,
                platform: None,
                features: &features,
                root,
            };
            (replace(&me, &mut cx)?, patch(&me, &mut cx)?)
        };
        let profiles = me.profile.clone();
        if let Some(profiles) = &profiles {
            validate_profiles(profiles, config.cli_unstable(), &features, &mut warnings)?;
        }
        let resolve_behavior = me
            .workspace
            .as_ref()
            .and_then(|ws| ws.resolver.as_deref())
            .map(|r| ResolveBehavior::from_manifest(r))
            .transpose()?;
        let workspace_config = match me.workspace {
            Some(ref toml_config) => {
                let lints = toml_config.lints.clone();
                let lints = verify_lints(lints)?;
                let inheritable = InheritableFields {
                    package: toml_config.package.clone(),
                    dependencies: toml_config.dependencies.clone(),
                    lints,
                    _ws_root: root.to_path_buf(),
                };
                let ws_root_config = WorkspaceRootConfig::new(
                    root,
                    &toml_config.members,
                    &toml_config.default_members,
                    &toml_config.exclude,
                    &Some(inheritable),
                    &toml_config.metadata,
                );
                config
                    .ws_roots
                    .borrow_mut()
                    .insert(root.to_path_buf(), ws_root_config.clone());
                WorkspaceConfig::Root(ws_root_config)
            }
            None => {
                bail!("virtual manifests must be configured with [workspace]");
            }
        };
        Ok((
            VirtualManifest::new(
                replace,
                patch,
                workspace_config,
                profiles,
                features,
                resolve_behavior,
            ),
            nested_paths,
        ))
    }

    fn replace(
        me: &manifest::TomlManifest,
        cx: &mut Context<'_, '_>,
    ) -> CargoResult<Vec<(PackageIdSpec, Dependency)>> {
        if me.patch.is_some() && me.replace.is_some() {
            bail!("cannot specify both [replace] and [patch]");
        }
        let mut replace = Vec::new();
        for (spec, replacement) in me.replace.iter().flatten() {
            let mut spec = PackageIdSpec::parse(spec).with_context(|| {
                format!(
                    "replacements must specify a valid semver \
                         version to replace, but `{}` does not",
                    spec
                )
            })?;
            if spec.url().is_none() {
                spec.set_url(CRATES_IO_INDEX.parse().unwrap());
            }

            if replacement.is_version_specified() {
                bail!(
                    "replacements cannot specify a version \
                         requirement, but found one for `{}`",
                    spec
                );
            }

            let mut dep = dep_to_dependency(replacement, spec.name(), cx, None)?;
            let version = spec.version().ok_or_else(|| {
                anyhow!(
                    "replacements must specify a version \
                         to replace, but `{}` does not",
                    spec
                )
            })?;
            unused_dep_keys(
                dep.name_in_toml().as_str(),
                "replace",
                replacement.unused_keys(),
                &mut cx.warnings,
            );
            dep.set_version_req(OptVersionReq::exact(&version));
            replace.push((spec, dep));
        }
        Ok(replace)
    }

    fn patch(
        me: &manifest::TomlManifest,
        cx: &mut Context<'_, '_>,
    ) -> CargoResult<HashMap<Url, Vec<Dependency>>> {
        let mut patch = HashMap::new();
        for (toml_url, deps) in me.patch.iter().flatten() {
            let url = match &toml_url[..] {
                CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
                _ => cx
                    .config
                    .get_registry_index(toml_url)
                    .or_else(|_| toml_url.into_url())
                    .with_context(|| {
                        format!(
                            "[patch] entry `{}` should be a URL or registry name",
                            toml_url
                        )
                    })?,
            };
            patch.insert(
                url,
                deps.iter()
                    .map(|(name, dep)| {
                        unused_dep_keys(
                            name,
                            &format!("patch.{toml_url}",),
                            dep.unused_keys(),
                            &mut cx.warnings,
                        );
                        dep_to_dependency(dep, name, cx, None)
                    })
                    .collect::<CargoResult<Vec<_>>>()?,
            );
        }
        Ok(patch)
    }

    struct Context<'a, 'b> {
        deps: &'a mut Vec<Dependency>,
        source_id: SourceId,
        nested_paths: &'a mut Vec<PathBuf>,
        config: &'b Config,
        warnings: &'a mut Vec<String>,
        platform: Option<Platform>,
        root: &'a Path,
        features: &'a Features,
    }

    fn verify_lints(lints: Option<manifest::TomlLints>) -> CargoResult<Option<manifest::TomlLints>> {
        let Some(lints) = lints else {
            return Ok(None);
        };

        for (tool, lints) in &lints {
            let supported = ["rust", "clippy", "rustdoc"];
            if !supported.contains(&tool.as_str()) {
                let supported = supported.join(", ");
                anyhow::bail!("unsupported `{tool}` in `[lints]`, must be one of {supported}")
            }
            for name in lints.keys() {
                if let Some((prefix, suffix)) = name.split_once("::") {
                    if tool == prefix {
                        anyhow::bail!(
                            "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
                        )
                    } else if tool == "rust" && supported.contains(&prefix) {
                        anyhow::bail!(
                            "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
                        )
                    } else {
                        anyhow::bail!("`lints.{tool}.{name}` is not a valid lint name")
                    }
                }
            }
        }

        Ok(Some(lints))
    }

    fn lints_to_rustflags(lints: &manifest::TomlLints) -> Vec<String> {
        let mut rustflags = lints
            .iter()
            .flat_map(|(tool, lints)| {
                lints.iter().map(move |(name, config)| {
                    let flag = match config.level() {
                        manifest::TomlLintLevel::Forbid => "--forbid",
                        manifest::TomlLintLevel::Deny => "--deny",
                        manifest::TomlLintLevel::Warn => "--warn",
                        manifest::TomlLintLevel::Allow => "--allow",
                    };

                    let option = if tool == "rust" {
                        format!("{flag}={name}")
                    } else {
                        format!("{flag}={tool}::{name}")
                    };
                    (
                        config.priority(),
                        // Since the most common group will be `all`, put it last so people are more
                        // likely to notice that they need to use `priority`.
                        std::cmp::Reverse(name),
                        option,
                    )
                })
            })
            .collect::<Vec<_>>();
        rustflags.sort();
        rustflags.into_iter().map(|(_, _, option)| option).collect()
    }

    fn unused_dep_keys(
        dep_name: &str,
        kind: &str,
        unused_keys: Vec<String>,
        warnings: &mut Vec<String>,
    ) {
        for unused in unused_keys {
            let key = format!("unused manifest key: {kind}.{dep_name}.{unused}");
            warnings.push(key);
        }
    }

    fn inheritable_from_path(
        config: &Config,
        workspace_path: PathBuf,
    ) -> CargoResult<InheritableFields> {
        // Workspace path should have Cargo.toml at the end
        let workspace_path_root = workspace_path.parent().unwrap();

        // Let the borrow exit scope so that it can be picked up if there is a need to
        // read a manifest
        if let Some(ws_root) = config.ws_roots.borrow().get(workspace_path_root) {
            return Ok(ws_root.inheritable().clone());
        };

        let source_id = SourceId::for_path(workspace_path_root)?;
        let (man, _) = read_manifest(&workspace_path, source_id, config)?;
        match man.workspace_config() {
            WorkspaceConfig::Root(root) => {
                config
                    .ws_roots
                    .borrow_mut()
                    .insert(workspace_path, root.clone());
                Ok(root.inheritable().clone())
            }
            _ => bail!(
                "root of a workspace inferred but wasn't a root: {}",
                workspace_path.display()
            ),
        }
    }

    /// Returns the name of the README file for a [`manifest::TomlPackage`].
    fn readme_for_package(
        package_root: &Path,
        readme: Option<&manifest::StringOrBool>,
    ) -> Option<String> {
        match &readme {
            None => default_readme_from_package_root(package_root),
            Some(value) => match value {
                manifest::StringOrBool::Bool(false) => None,
                manifest::StringOrBool::Bool(true) => Some("README.md".to_string()),
                manifest::StringOrBool::String(v) => Some(v.clone()),
            },
        }
    }

    const DEFAULT_README_FILES: [&str; 3] = ["README.md", "README.txt", "README"];

    /// Checks if a file with any of the default README file names exists in the package root.
    /// If so, returns a `String` representing that name.
    fn default_readme_from_package_root(package_root: &Path) -> Option<String> {
        for &readme_filename in DEFAULT_README_FILES.iter() {
            if package_root.join(readme_filename).is_file() {
                return Some(readme_filename.to_string());
            }
        }

        None
    }

    /// Checks a list of build targets, and ensures the target names are unique within a vector.
    /// If not, the name of the offending build target is returned.
    fn unique_build_targets(
        targets: &[Target],
        package_root: &Path,
    ) -> Result<(), HashMap<PathBuf, Vec<Target>>> {
        let mut source_targets = HashMap::<_, Vec<_>>::new();
        for target in targets {
            if let TargetSourcePath::Path(path) = target.src_path() {
                let full = package_root.join(path);
                source_targets.entry(full).or_default().push(target.clone());
            }
        }

        let conflict_targets = source_targets
            .into_iter()
            .filter(|(_, targets)| targets.len() > 1)
            .collect::<HashMap<_, _>>();

        if !conflict_targets.is_empty() {
            return Err(conflict_targets);
        }

        Ok(())
    }

    /// Defines simple getter methods for inheritable fields.
    macro_rules! package_field_getter {
        ( $(($key:literal, $field:ident -> $ret:ty),)* ) => (
            $(
                #[doc = concat!("Gets the field `workspace.package", $key, "`.")]
                fn $field(&self) -> CargoResult<$ret> {
                    let Some(val) = self.package.as_ref().and_then(|p| p.$field.as_ref()) else  {
                        bail!("`workspace.package.{}` was not defined", $key);
                    };
                    Ok(val.clone())
                }
            )*
        )
    }

    /// A group of fields that are inheritable by members of the workspace
    #[derive(Clone, Debug, Default)]
    pub struct InheritableFields {
        package: Option<manifest::InheritablePackage>,
        dependencies: Option<BTreeMap<manifest::PackageName, manifest::TomlDependency>>,
        lints: Option<manifest::TomlLints>,

        // Bookkeeping to help when resolving values from above
        _ws_root: PathBuf,
    }

    impl InheritableFields {
        package_field_getter! {
            // Please keep this list lexicographically ordered.
            ("authors",       authors       -> Vec<String>),
            ("badges",        badges        -> BTreeMap<String, BTreeMap<String, String>>),
            ("categories",    categories    -> Vec<String>),
            ("description",   description   -> String),
            ("documentation", documentation -> String),
            ("edition",       edition       -> String),
            ("exclude",       exclude       -> Vec<String>),
            ("homepage",      homepage      -> String),
            ("include",       include       -> Vec<String>),
            ("keywords",      keywords      -> Vec<String>),
            ("license",       license       -> String),
            ("publish",       publish       -> manifest::VecStringOrBool),
            ("repository",    repository    -> String),
            ("rust-version",  rust_version  -> RustVersion),
            ("version",       version       -> semver::Version),
        }

        /// Gets a workspace dependency with the `name`.
        fn get_dependency(
            &self,
            name: &str,
            package_root: &Path,
        ) -> CargoResult<manifest::TomlDependency> {
            let Some(deps) = &self.dependencies else {
                bail!("`workspace.dependencies` was not defined");
            };
            let Some(dep) = deps.get(name) else {
                bail!("`dependency.{name}` was not found in `workspace.dependencies`");
            };
            let mut dep = dep.clone();
            if let manifest::TomlDependency::Detailed(detailed) = &mut dep {
                if let Some(rel_path) = &detailed.path {
                    detailed.path = Some(resolve_relative_path(
                        name,
                        self.ws_root(),
                        package_root,
                        rel_path,
                    )?);
                }
            }
            Ok(dep)
        }

        /// Gets the field `workspace.lint`.
        fn lints(&self) -> CargoResult<manifest::TomlLints> {
            let Some(val) = &self.lints else {
                bail!("`workspace.lints` was not defined");
            };
            Ok(val.clone())
        }

        /// Gets the field `workspace.package.license-file`.
        fn license_file(&self, package_root: &Path) -> CargoResult<String> {
            let Some(license_file) = self.package.as_ref().and_then(|p| p.license_file.as_ref()) else {
                bail!("`workspace.package.license-file` was not defined");
            };
            resolve_relative_path("license-file", &self._ws_root, package_root, license_file)
        }

        /// Gets the field `workspace.package.readme`.
        fn readme(&self, package_root: &Path) -> CargoResult<manifest::StringOrBool> {
            let Some(readme) = readme_for_package(
                self._ws_root.as_path(),
                self.package.as_ref().and_then(|p| p.readme.as_ref()),
            ) else {
                bail!("`workspace.package.readme` was not defined");
            };
            resolve_relative_path("readme", &self._ws_root, package_root, &readme)
                .map(manifest::StringOrBool::String)
        }

        fn ws_root(&self) -> &PathBuf {
            &self._ws_root
        }
    }

    fn field_inherit_with<'a, T>(
        field: manifest::InheritableField<T>,
        label: &str,
        get_ws_inheritable: impl FnOnce() -> CargoResult<T>,
    ) -> CargoResult<T> {
        match field {
                manifest::InheritableField::Value(value) => Ok(value),
                manifest::InheritableField::Inherit(_) => get_ws_inheritable().with_context(|| {
                    format!(
                    "error inheriting `{label}` from workspace root manifest's `workspace.package.{label}`",
                )
                }),
            }
    }

    fn lints_inherit_with(
        lints: manifest::InheritableLints,
        get_ws_inheritable: impl FnOnce() -> CargoResult<manifest::TomlLints>,
    ) -> CargoResult<manifest::TomlLints> {
        if lints.workspace {
            if !lints.lints.is_empty() {
                anyhow::bail!("cannot override `workspace.lints` in `lints`, either remove the overrides or `lints.workspace = true` and manually specify the lints");
            }
            get_ws_inheritable().with_context(|| {
                "error inheriting `lints` from workspace root manifest's `workspace.lints`"
            })
        } else {
            Ok(lints.lints)
        }
    }

    fn dependency_inherit_with<'a>(
        dependency: manifest::InheritableDependency,
        name: &str,
        inheritable: impl FnOnce() -> CargoResult<&'a InheritableFields>,
        cx: &mut Context<'_, '_>,
    ) -> CargoResult<manifest::TomlDependency> {
        match dependency {
                manifest::InheritableDependency::Value(value) => Ok(value),
                manifest::InheritableDependency::Inherit(w) => {
                    inner_dependency_inherit_with(w, name, inheritable, cx).with_context(|| {
                        format!(
                            "error inheriting `{name}` from workspace root manifest's `workspace.dependencies.{name}`",
                        )
                    })
                }
            }
    }

    fn inner_dependency_inherit_with<'a>(
        dependency: manifest::TomlInheritedDependency,
        name: &str,
        inheritable: impl FnOnce() -> CargoResult<&'a InheritableFields>,
        cx: &mut Context<'_, '_>,
    ) -> CargoResult<manifest::TomlDependency> {
        fn default_features_msg(label: &str, ws_def_feat: Option<bool>, cx: &mut Context<'_, '_>) {
            let ws_def_feat = match ws_def_feat {
                Some(true) => "true",
                Some(false) => "false",
                None => "not specified",
            };
            cx.warnings.push(format!(
                "`default-features` is ignored for {label}, since `default-features` was \
                    {ws_def_feat} for `workspace.dependencies.{label}`, \
                    this could become a hard error in the future"
            ))
        }
        if dependency.default_features.is_some() && dependency.default_features2.is_some() {
            warn_on_deprecated("default-features", name, "dependency", cx.warnings);
        }
        inheritable()?.get_dependency(name, cx.root).map(|d| {
            match d {
                manifest::TomlDependency::Simple(s) => {
                    if let Some(false) = dependency.default_features() {
                        default_features_msg(name, None, cx);
                    }
                    if dependency.optional.is_some()
                        || dependency.features.is_some()
                        || dependency.public.is_some()
                    {
                        manifest::TomlDependency::Detailed(manifest::TomlDetailedDependency {
                            version: Some(s),
                            optional: dependency.optional,
                            features: dependency.features.clone(),
                            public: dependency.public,
                            ..Default::default()
                        })
                    } else {
                        manifest::TomlDependency::Simple(s)
                    }
                }
                manifest::TomlDependency::Detailed(d) => {
                    let mut d = d.clone();
                    match (dependency.default_features(), d.default_features()) {
                        // member: default-features = true and
                        // workspace: default-features = false should turn on
                        // default-features
                        (Some(true), Some(false)) => {
                            d.default_features = Some(true);
                        }
                        // member: default-features = false and
                        // workspace: default-features = true should ignore member
                        // default-features
                        (Some(false), Some(true)) => {
                            default_features_msg(name, Some(true), cx);
                        }
                        // member: default-features = false and
                        // workspace: dep = "1.0" should ignore member default-features
                        (Some(false), None) => {
                            default_features_msg(name, None, cx);
                        }
                        _ => {}
                    }
                    d.features = match (d.features.clone(), dependency.features.clone()) {
                        (Some(dep_feat), Some(inherit_feat)) => Some(
                            dep_feat
                                .into_iter()
                                .chain(inherit_feat)
                                .collect::<Vec<String>>(),
                        ),
                        (Some(dep_fet), None) => Some(dep_fet),
                        (None, Some(inherit_feat)) => Some(inherit_feat),
                        (None, None) => None,
                    };
                    d.optional = dependency.optional;
                    manifest::TomlDependency::Detailed(d)
                }
            }
        })
    }

    pub(crate) fn to_dependency<P: ResolveToPath + Clone>(
        dep: &manifest::TomlDependency<P>,
        name: &str,
        source_id: SourceId,
        nested_paths: &mut Vec<PathBuf>,
        config: &Config,
        warnings: &mut Vec<String>,
        platform: Option<Platform>,
        root: &Path,
        features: &Features,
        kind: Option<DepKind>,
    ) -> CargoResult<Dependency> {
        dep_to_dependency(
            dep,
            name,
            &mut Context {
                deps: &mut Vec::new(),
                source_id,
                nested_paths,
                config,
                warnings,
                platform,
                root,
                features,
            },
            kind,
        )
    }

    fn dep_to_dependency<P: ResolveToPath + Clone>(
        orig: &manifest::TomlDependency<P>,
        name: &str,
        cx: &mut Context<'_, '_>,
        kind: Option<DepKind>,
    ) -> CargoResult<Dependency> {
        match *orig {
            manifest::TomlDependency::Simple(ref version) => detailed_dep_to_dependency(
                &manifest::TomlDetailedDependency::<P> {
                    version: Some(version.clone()),
                    ..Default::default()
                },
                name,
                cx,
                kind,
            ),
            manifest::TomlDependency::Detailed(ref details) => {
                detailed_dep_to_dependency(details, name, cx, kind)
            }
        }
    }

    fn detailed_dep_to_dependency<P: ResolveToPath + Clone>(
        orig: &manifest::TomlDetailedDependency<P>,
        name_in_toml: &str,
        cx: &mut Context<'_, '_>,
        kind: Option<DepKind>,
    ) -> CargoResult<Dependency> {
        if orig.version.is_none() && orig.path.is_none() && orig.git.is_none() {
            let msg = format!(
                "dependency ({}) specified without \
                     providing a local path, Git repository, version, or \
                     workspace dependency to use. This will be considered an \
                     error in future versions",
                name_in_toml
            );
            cx.warnings.push(msg);
        }

        if let Some(version) = &orig.version {
            if version.contains('+') {
                cx.warnings.push(format!(
                    "version requirement `{}` for dependency `{}` \
                         includes semver metadata which will be ignored, removing the \
                         metadata is recommended to avoid confusion",
                    version, name_in_toml
                ));
            }
        }

        if orig.git.is_none() {
            let git_only_keys = [
                (&orig.branch, "branch"),
                (&orig.tag, "tag"),
                (&orig.rev, "rev"),
            ];

            for &(key, key_name) in &git_only_keys {
                if key.is_some() {
                    bail!(
                        "key `{}` is ignored for dependency ({}).",
                        key_name,
                        name_in_toml
                    );
                }
            }
        }

        // Early detection of potentially misused feature syntax
        // instead of generating a "feature not found" error.
        if let Some(features) = &orig.features {
            for feature in features {
                if feature.contains('/') {
                    bail!(
                        "feature `{}` in dependency `{}` is not allowed to contain slashes\n\
                             If you want to enable features of a transitive dependency, \
                             the direct dependency needs to re-export those features from \
                             the `[features]` table.",
                        feature,
                        name_in_toml
                    );
                }
                if feature.starts_with("dep:") {
                    bail!(
                        "feature `{}` in dependency `{}` is not allowed to use explicit \
                            `dep:` syntax\n\
                             If you want to enable an optional dependency, specify the name \
                             of the optional dependency without the `dep:` prefix, or specify \
                             a feature from the dependency's `[features]` table that enables \
                             the optional dependency.",
                        feature,
                        name_in_toml
                    );
                }
            }
        }

        let new_source_id = match (
            orig.git.as_ref(),
            orig.path.as_ref(),
            orig.registry.as_ref(),
            orig.registry_index.as_ref(),
        ) {
            (Some(_), _, Some(_), _) | (Some(_), _, _, Some(_)) => bail!(
                "dependency ({}) specification is ambiguous. \
                     Only one of `git` or `registry` is allowed.",
                name_in_toml
            ),
            (_, _, Some(_), Some(_)) => bail!(
                "dependency ({}) specification is ambiguous. \
                     Only one of `registry` or `registry-index` is allowed.",
                name_in_toml
            ),
            (Some(git), maybe_path, _, _) => {
                if maybe_path.is_some() {
                    bail!(
                        "dependency ({}) specification is ambiguous. \
                             Only one of `git` or `path` is allowed.",
                        name_in_toml
                    );
                }

                let n_details = [&orig.branch, &orig.tag, &orig.rev]
                    .iter()
                    .filter(|d| d.is_some())
                    .count();

                if n_details > 1 {
                    bail!(
                        "dependency ({}) specification is ambiguous. \
                             Only one of `branch`, `tag` or `rev` is allowed.",
                        name_in_toml
                    );
                }

                let reference = orig
                    .branch
                    .clone()
                    .map(GitReference::Branch)
                    .or_else(|| orig.tag.clone().map(GitReference::Tag))
                    .or_else(|| orig.rev.clone().map(GitReference::Rev))
                    .unwrap_or(GitReference::DefaultBranch);
                let loc = git.into_url()?;

                if let Some(fragment) = loc.fragment() {
                    let msg = format!(
                        "URL fragment `#{}` in git URL is ignored for dependency ({}). \
                            If you were trying to specify a specific git revision, \
                            use `rev = \"{}\"` in the dependency declaration.",
                        fragment, name_in_toml, fragment
                    );
                    cx.warnings.push(msg)
                }

                SourceId::for_git(&loc, reference)?
            }
            (None, Some(path), _, _) => {
                let path = path.resolve(cx.config);
                cx.nested_paths.push(path.clone());
                // If the source ID for the package we're parsing is a path
                // source, then we normalize the path here to get rid of
                // components like `..`.
                //
                // The purpose of this is to get a canonical ID for the package
                // that we're depending on to ensure that builds of this package
                // always end up hashing to the same value no matter where it's
                // built from.
                if cx.source_id.is_path() {
                    let path = cx.root.join(path);
                    let path = paths::normalize_path(&path);
                    SourceId::for_path(&path)?
                } else {
                    cx.source_id
                }
            }
            (None, None, Some(registry), None) => SourceId::alt_registry(cx.config, registry)?,
            (None, None, None, Some(registry_index)) => {
                let url = registry_index.into_url()?;
                SourceId::for_registry(&url)?
            }
            (None, None, None, None) => SourceId::crates_io(cx.config)?,
        };

        let (pkg_name, explicit_name_in_toml) = match orig.package {
            Some(ref s) => (&s[..], Some(name_in_toml)),
            None => (name_in_toml, None),
        };

        let version = orig.version.as_deref();
        let mut dep = Dependency::parse(pkg_name, version, new_source_id)?;
        if orig.default_features.is_some() && orig.default_features2.is_some() {
            warn_on_deprecated("default-features", name_in_toml, "dependency", cx.warnings);
        }
        dep.set_features(orig.features.iter().flatten())
            .set_default_features(orig.default_features().unwrap_or(true))
            .set_optional(orig.optional.unwrap_or(false))
            .set_platform(cx.platform.clone());
        if let Some(registry) = &orig.registry {
            let registry_id = SourceId::alt_registry(cx.config, registry)?;
            dep.set_registry_id(registry_id);
        }
        if let Some(registry_index) = &orig.registry_index {
            let url = registry_index.into_url()?;
            let registry_id = SourceId::for_registry(&url)?;
            dep.set_registry_id(registry_id);
        }

        if let Some(kind) = kind {
            dep.set_kind(kind);
        }
        if let Some(name_in_toml) = explicit_name_in_toml {
            dep.set_explicit_name_in_toml(name_in_toml);
        }

        if let Some(p) = orig.public {
            cx.features.require(Feature::public_dependency())?;

            if dep.kind() != DepKind::Normal {
                bail!("'public' specifier can only be used on regular dependencies, not {:?} dependencies", dep.kind());
            }

            dep.set_public(p);
        }

        if let (Some(artifact), is_lib, target) = (
            orig.artifact.as_ref(),
            orig.lib.unwrap_or(false),
            orig.target.as_deref(),
        ) {
            if cx.config.cli_unstable().bindeps {
                let artifact = Artifact::parse(&artifact.0, is_lib, target)?;
                if dep.kind() != DepKind::Build
                    && artifact.target() == Some(ArtifactTarget::BuildDependencyAssumeTarget)
                {
                    bail!(
                        r#"`target = "target"` in normal- or dev-dependencies has no effect ({})"#,
                        name_in_toml
                    );
                }
                dep.set_artifact(artifact)
            } else {
                bail!("`artifact = …` requires `-Z bindeps` ({})", name_in_toml);
            }
        } else if orig.lib.is_some() || orig.target.is_some() {
            for (is_set, specifier) in [
                (orig.lib.is_some(), "lib"),
                (orig.target.is_some(), "target"),
            ] {
                if !is_set {
                    continue;
                }
                bail!(
                    "'{}' specifier cannot be used without an 'artifact = …' value ({})",
                    specifier,
                    name_in_toml
                )
            }
        }
        Ok(dep)
    }

    /// Checks syntax validity and unstable feature gate for each profile.
    ///
    /// It's a bit unfortunate both `-Z` flags and `cargo-features` are required,
    /// because profiles can now be set in either `Cargo.toml` or `config.toml`.
    fn validate_profiles(
        profiles: &manifest::TomlProfiles,
        cli_unstable: &CliUnstable,
        features: &Features,
        warnings: &mut Vec<String>,
    ) -> CargoResult<()> {
        for (name, profile) in &profiles.0 {
            validate_profile(profile, name, cli_unstable, features, warnings)?;
        }
        Ok(())
    }

    /// Checks stytax validity and unstable feature gate for a given profile.
    pub fn validate_profile(
        root: &manifest::TomlProfile,
        name: &str,
        cli_unstable: &CliUnstable,
        features: &Features,
        warnings: &mut Vec<String>,
    ) -> CargoResult<()> {
        validate_profile_layer(root, name, cli_unstable, features)?;
        if let Some(ref profile) = root.build_override {
            validate_profile_override(profile, "build-override")?;
            validate_profile_layer(
                profile,
                &format!("{name}.build-override"),
                cli_unstable,
                features,
            )?;
        }
        if let Some(ref packages) = root.package {
            for (override_name, profile) in packages {
                validate_profile_override(profile, "package")?;
                validate_profile_layer(
                    profile,
                    &format!("{name}.package.{override_name}"),
                    cli_unstable,
                    features,
                )?;
            }
        }

        if let Some(dir_name) = &root.dir_name {
            // This is disabled for now, as we would like to stabilize named
            // profiles without this, and then decide in the future if it is
            // needed. This helps simplify the UI a little.
            bail!(
                "dir-name=\"{}\" in profile `{}` is not currently allowed, \
                     directory names are tied to the profile name for custom profiles",
                dir_name,
                name
            );
        }

        // `inherits` validation
        if matches!(root.inherits.as_deref(), Some("debug")) {
            bail!(
                "profile.{}.inherits=\"debug\" should be profile.{}.inherits=\"dev\"",
                name,
                name
            );
        }

        match name {
            "doc" => {
                warnings.push("profile `doc` is deprecated and has no effect".to_string());
            }
            "test" | "bench" => {
                if root.panic.is_some() {
                    warnings.push(format!("`panic` setting is ignored for `{}` profile", name))
                }
            }
            _ => {}
        }

        if let Some(panic) = &root.panic {
            if panic != "unwind" && panic != "abort" {
                bail!(
                    "`panic` setting of `{}` is not a valid setting, \
                         must be `unwind` or `abort`",
                    panic
                );
            }
        }

        if let Some(manifest::StringOrBool::String(arg)) = &root.lto {
            if arg == "true" || arg == "false" {
                bail!(
                    "`lto` setting of string `\"{arg}\"` for `{name}` profile is not \
                         a valid setting, must be a boolean (`true`/`false`) or a string \
                        (`\"thin\"`/`\"fat\"`/`\"off\"`) or omitted.",
                );
            }
        }

        Ok(())
    }

    /// Validates a profile.
    ///
    /// This is a shallow check, which is reused for the profile itself and any overrides.
    fn validate_profile_layer(
        profile: &manifest::TomlProfile,
        name: &str,
        cli_unstable: &CliUnstable,
        features: &Features,
    ) -> CargoResult<()> {
        if let Some(codegen_backend) = &profile.codegen_backend {
            match (
                features.require(Feature::codegen_backend()),
                cli_unstable.codegen_backend,
            ) {
                (Err(e), false) => return Err(e),
                _ => {}
            }

            if codegen_backend.contains(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
                bail!(
                    "`profile.{}.codegen-backend` setting of `{}` is not a valid backend name.",
                    name,
                    codegen_backend,
                );
            }
        }
        if profile.rustflags.is_some() {
            match (
                features.require(Feature::profile_rustflags()),
                cli_unstable.profile_rustflags,
            ) {
                (Err(e), false) => return Err(e),
                _ => {}
            }
        }
        if profile.trim_paths.is_some() {
            match (
                features.require(Feature::trim_paths()),
                cli_unstable.trim_paths,
            ) {
                (Err(e), false) => return Err(e),
                _ => {}
            }
        }
        Ok(())
    }

    /// Validation that is specific to an override.
    fn validate_profile_override(profile: &manifest::TomlProfile, which: &str) -> CargoResult<()> {
        if profile.package.is_some() {
            bail!("package-specific profiles cannot be nested");
        }
        if profile.build_override.is_some() {
            bail!("build-override profiles cannot be nested");
        }
        if profile.panic.is_some() {
            bail!("`panic` may not be specified in a `{}` profile", which)
        }
        if profile.lto.is_some() {
            bail!("`lto` may not be specified in a `{}` profile", which)
        }
        if profile.rpath.is_some() {
            bail!("`rpath` may not be specified in a `{}` profile", which)
        }
        Ok(())
    }

    pub trait ResolveToPath {
        fn resolve(&self, config: &Config) -> PathBuf;
    }

    impl ResolveToPath for String {
        fn resolve(&self, _: &Config) -> PathBuf {
            self.into()
        }
    }

    impl ResolveToPath for ConfigRelativePath {
        fn resolve(&self, c: &Config) -> PathBuf {
            self.resolve_path(c)
        }
    }

    fn translate_position(input: &str, index: usize) -> (usize, usize) {
        if input.is_empty() {
            return (0, index);
        }

        let safe_index = index.min(input.len() - 1);
        let column_offset = index - safe_index;

        let nl = input[0..safe_index]
            .as_bytes()
            .iter()
            .rev()
            .enumerate()
            .find(|(_, b)| **b == b'\n')
            .map(|(nl, _)| safe_index - nl - 1);
        let line_start = match nl {
            Some(nl) => nl + 1,
            None => 0,
        };
        let line = input[0..line_start]
            .as_bytes()
            .iter()
            .filter(|c| **c == b'\n')
            .count();
        let column = input[line_start..=safe_index].chars().count() - 1;
        let column = column + column_offset;

        (line, column)
    }