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
use super::{
args::NonZeroUsizePlus1,
cargo::{Toolchain, ToolchainErr},
};
use alloc::borrow::Cow;
use core::cmp::Ordering;
use std::{
fs::{File, TryLockError},
io::{Error, ErrorKind, Read as _, StderrLock, Write as _},
path::{Path, PathBuf},
};
use toml::{
Spanned,
de::{DeArray, DeValue, Error as TomlErr},
map::Map,
};
/// Unit tests.
#[cfg(test)]
mod tests;
/// `"workspace"`.
const WORKSPACE: &str = "workspace";
/// `"package"`.
const PACKAGE: &str = "package";
/// `"rust-version"`.
const RUST_VERSION: &str = "rust-version";
/// Error returned from extracting `"workspace"`.
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Copy)]
pub(crate) enum WorkspaceErr {
/// Variant returned when there is no `"workspace"` key.
Missing,
/// Variant returned when `"workspace"` is not a table.
InvalidType,
/// Variant returned when `workspace.package` does not exist.
MissingPackage,
/// Variant returned when `workspace.package` is not a table.
InvalidPackageType,
/// Variant returned when `workspace.package.rust-version` does not exist.
MissingPackageMsrv,
/// Variant returned when `workspace.package.rust-version` is not a string.
InvalidPackageMsrvType,
/// Variant returned when `workspace.package.rust-version` is not a valid MSRV.
Msrv,
}
impl WorkspaceErr {
/// Writes `self` to `stderr`.
fn write(self, mut stderr: StderrLock<'_>, file: &Path) -> Result<(), Error> {
match self {
Self::Missing => writeln!(
stderr,
"'{WORKSPACE}' does not exist in {}.",
file.display()
),
Self::InvalidType => writeln!(
stderr,
"'{WORKSPACE}' exists but is not a table in {}.",
file.display()
),
Self::MissingPackage => writeln!(
stderr,
"'{WORKSPACE}.{PACKAGE}' does not exist in {}.",
file.display()
),
Self::InvalidPackageType => writeln!(
stderr,
"'{WORKSPACE}.{PACKAGE}' exists but is not a table in {}.",
file.display()
),
Self::MissingPackageMsrv => writeln!(
stderr,
"'{WORKSPACE}.{PACKAGE}.{RUST_VERSION}' does not exist in {}.",
file.display()
),
Self::InvalidPackageMsrvType => writeln!(
stderr,
"'{WORKSPACE}.{PACKAGE}.{RUST_VERSION}' exists but is not a string in {}.",
file.display()
),
Self::Msrv => writeln!(
stderr,
"'{WORKSPACE}.{PACKAGE}.{RUST_VERSION}' exists but is not a valid MSRV in {}.",
file.display()
),
}
}
}
/// `"name"`.
const NAME: &str = "name";
/// Error returned from extracting `"package"`.
#[cfg_attr(test, derive(Debug))]
pub(crate) enum PackageErr {
/// Variant returned when there is no `"package"` key.
Missing,
/// Variant returned when `"package"` is not a table.
InvalidType,
/// Variant returned when `packagen.name` does not exist.
MissingName,
/// Variant returned when `package.name` is not a string.
InvalidNameType,
/// Variant returned when `package.rust-version` is not a string nor table.
InvalidMsrvType,
/// Variant returned when `package.rust-version` is not a valid MSRV.
Msrv,
/// Variant returned when `package.rust-version` is table that doesn't contain the `"workspace"` key.
MsrvWorkspaceMissing,
/// Variant returned when `package.rust-version.workspace` is not a Boolean with value `true`.
MsrvWorkspaceVal,
/// Variant returned when `package.workspace` is not a string.
InvalidWorkspaceType,
/// Variant returned when searching for the workspace file errors.
WorkspaceIo(Error),
/// Variant when locking the workspace file errors.
WorkspaceLock(TryLockError),
/// Variant when the length of the workspace file does not match the length reported from the file system.
WorkspaceLenMismatch,
/// Variant returned when there is no workspace `Cargo.toml`.
///
/// This is only returned if the package's MSRV is inherited from the workspace, there is no
/// `workspace` key in the package's `Cargo.toml`, and there is no `workspace` key in the table
/// `package` (i.e., this is only returned when we must search for it by crawling up the directory).
WorkspaceDoesNotExist,
/// Variant returned when the file located at `package.workspace` could not be read.
///
/// This is only returned if the table `package` had a key `workspace` that was a string, or we searched
/// for the workspace and found a `Cargo.toml`.
WorkspaceRead(Error, PathBuf),
/// Variant returned when the file located at `package.workspace` could not be locked.
///
/// This is only returned if the table `package` had a key `workspace` that was a string, or we searched
/// for the workspace and found a `Cargo.toml`.
WorkspaceReadLock(TryLockError, PathBuf),
/// Variant returned when the length of the file located at `package.workspace` does not match the length
/// reported by the file system.
///
/// This is only returned if the table `package` had a key `workspace` that was a string, or we searched
/// for the workspace and found a `Cargo.toml`.
WorkspaceReadLenMismatch(PathBuf),
/// Variant returned when the file located at `package.workspace` is not valid TOML.
///
/// This is only returned if the table `package` had a key `workspace` that was a string, or we searched
/// for the workspace and found a `Cargo.toml`.
WorkspaceToml(TomlErr, PathBuf),
/// Variant returned when `package.rust-version` defers to the workspace MSRV, but there was an error
/// extracting the workspace MSRV from the file located at the contained `PathBuf`.
Workspace(WorkspaceErr, PathBuf),
}
impl PackageErr {
/// Writes `self` to `stderr`.
#[expect(clippy::unreachable, reason = "want to crash when there is a bug")]
fn write(self, mut stderr: StderrLock<'_>, file: &Path) -> Result<(), Error> {
match self {
Self::Missing => writeln!(stderr, "'{PACKAGE}' does not exist in {}.", file.display()),
Self::InvalidType => writeln!(
stderr,
"'{PACKAGE}' exists but is not a table in {}.",
file.display()
),
Self::MissingName => writeln!(stderr, "'{PACKAGE}.{NAME}' does not exist in {}.", file.display()),
Self::InvalidNameType => writeln!(
stderr,
"'{PACKAGE}.{NAME}' exists but is not a string in {}.",
file.display()
),
Self::InvalidMsrvType => writeln!(
stderr,
"'{PACKAGE}.{RUST_VERSION}' exists but is not a string nor table in {}.",
file.display()
),
Self::Msrv => writeln!(
stderr,
"'{PACKAGE}.{RUST_VERSION}' is a string but is not a valid MSRV in {}.",
file.display()
),
Self::MsrvWorkspaceMissing => writeln!(
stderr,
"'{PACKAGE}.{RUST_VERSION}' is a table but does not contain the key '{WORKSPACE}' in {}.",
file.display()
),
Self::MsrvWorkspaceVal => writeln!(
stderr,
"'{PACKAGE}.{RUST_VERSION}.{WORKSPACE}' exists but is not a Boolean or is not true in {}.",
file.display()
),
Self::WorkspaceIo(e) => writeln!(
stderr,
"There was an error looking for the workspace Cargo.toml in {} and its ancestor directories: {e}.",
file.parent().unwrap_or_else(|| unreachable!("there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.")).display(),
),
Self::WorkspaceLock(e) => writeln!(
stderr,
"There was an error locking the workspace Cargo.toml in {} and its ancestor directories: {e}.",
file.parent().unwrap_or_else(|| unreachable!("there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.")).display(),
),
Self::WorkspaceLenMismatch=> writeln!(
stderr,
"The length of the workspace Cargo.toml in {} does not match the length reported by the file systemn.",
file.parent().unwrap_or_else(|| unreachable!("there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.")).display(),
),
Self::WorkspaceDoesNotExist => writeln!(
stderr,
"There is no workspace Cargo.toml in {} nor its ancestor directories.",
file.parent().unwrap_or_else(|| unreachable!("there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.")).display(),
),
Self::InvalidWorkspaceType => writeln!(
stderr,
"'{PACKAGE}.{WORKSPACE}' exists but is not a string in {}.",
file.display()
),
Self::WorkspaceRead(e, p) => {
writeln!(stderr, "There was an issue reading the workspace file {}: {e}.", p.display())
}
Self::WorkspaceReadLock(e, p) => {
writeln!(stderr, "There was an issue locking the workspace file {}: {e}.", p.display())
}
Self::WorkspaceReadLenMismatch(p) => {
writeln!(stderr, "The length of the workspace file {} does not match the length reported by the file system.", p.display())
}
Self::WorkspaceToml(e, p) => write!(
stderr,
"Error parsing workspace file {} as TOML: {e}.",
p.display()
),
Self::Workspace(e, p) => e.write(stderr, &p),
}
}
}
/// `"features"`.
const FEATURES: &str = "features";
/// Error returned from extracting feature dependencies.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) enum FeatureDependenciesErr {
/// Variant returned when a feature is not an array.
///
/// The contained `String` is the name of the feature.
InvalidFeatureType(String),
/// Variant returned when a feature dependency is not a string.
///
/// The contained `String` is the name of the feature.
InvalidDependencyType(String),
/// Variant returned when a feature dependency is not a feature nor dependency.
///
/// The first contained `String` is the name of the feature, and the second `String` is the name of the invalid
/// feature dependency.
///
/// Note this is only possible when `allow_implied_features` is `false` when passed to
/// [`Features::validate_dependencies`].
InvalidDependency(String, String),
/// Variant returned when a feature is cyclic.
///
/// The contained `String` is the name of the feature.
CyclicFeature(String),
/// Variant returned when a feature dependency is redundant.
///
/// The first contained `String` is the name of the feature, and the second `String` is the name of the
/// redundant feature dependency.
RedundantDependency(String, String),
}
impl FeatureDependenciesErr {
/// Writes `self` to `stderr`.
fn write(self, mut stderr: StderrLock<'_>, file: &Path) -> Result<(), Error> {
match self {
Self::InvalidFeatureType(name) => {
writeln!(
stderr,
"'{FEATURES}.{name}' is not an array in {}.",
file.display()
)
}
Self::InvalidDependencyType(name) => writeln!(
stderr,
"'{FEATURES}.{name}' contains a value that is not a string in {}.",
file.display()
),
Self::InvalidDependency(name, dep_name) => writeln!(
stderr,
"'{FEATURES}.{name}' contains '{dep_name}' which is neither a feature nor dependency in {}. It may be an implied feature from an optional dependency, but --allow-implied-features was not passed.",
file.display()
),
Self::CyclicFeature(name) => writeln!(
stderr,
"'{FEATURES}.{name}' is a cyclic feature in {}.",
file.display()
),
Self::RedundantDependency(name, dep_name) => writeln!(
stderr,
"'{FEATURES}.{name}' contains the redundant dependency '{dep_name}' in {}.",
file.display()
),
}
}
}
/// Error returned from extracting `"features"`.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) enum FeaturesErr {
/// Variant returned when `features` is not a table in Cargo.toml.
InvalidType,
/// Variant returned when `features` contains a feature with an invalid name.
///
/// The contained `String` is the name of the feature.
InvalidName(String),
/// Variant returned when there is an issue with a feature's dependencies.
FeatureDependencies(FeatureDependenciesErr),
}
impl FeaturesErr {
/// Writes `self` to `stderr`.
fn write(self, mut stderr: StderrLock<'_>, file: &Path) -> Result<(), Error> {
match self {
Self::InvalidType => {
writeln!(
stderr,
"'{FEATURES}' exists but is not a table in {}.",
file.display()
)
}
Self::InvalidName(name) => {
writeln!(
stderr,
"'{FEATURES}.{name}' is not a valid feature name in {}.",
file.display()
)
}
Self::FeatureDependencies(e) => e.write(stderr, file),
}
}
}
/// Error returned from extracting dependencies.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) enum DependenciesErr {
/// Variant returned when the dependencies is not a table.
///
/// The contained `str` is the name of the dependencies (e.g., `"dependencies"`).
Type(&'static str),
/// Variant returned when a dependency has an invalid name.
///
/// The contained `str` is the name of dependencies (e.g., `"dependencies"`), and the `String` is the
/// name of the dependency.
Name(&'static str, String),
/// Variant returned when a dependency is not a string or table.
///
/// The contained `str` is the name of dependencies (e.g., `"dependencies"`), and the `String` is the
/// name of the dependency.
DependencyType(&'static str, String),
/// Variant returned when a dependency contains an `"optional"` key whose value is not a Boolean.
///
/// The contained `str` is the name of dependencies (e.g., `"dependencies"`), and the `String` is the
/// name of the dependency.
OptionalType(&'static str, String),
/// Variant returned when an optional dependency would cause an implied feature to be created.
///
/// Note this is only possible when `allow_implied_features` is `false` when passed to
/// [`Features::add_optional_dependencies`].
///
/// The contained `str` is the name of dependencies (e.g., `"dependencies"`), and the `String` is the
/// name of the dependency.
ImpliedFeature(&'static str, String),
}
/// Error returned from extracting dependencies to add implied features.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) enum ImpliedFeaturesErr {
/// Variant returned from extracting dependencies.
Dependencies(DependenciesErr),
/// Variant returned when `target` is not a table in Cargo.toml.
TargetType,
/// Variant returned when `target` contains a key whose value is not a table.
///
/// The contained `String` is the name of the key.
TargetPlatformType(String),
/// Variant returned when a target platform contains an issue with dependencies.
///
/// The contained `String` is the name of the target platform.
TagetPlatformDependencies(String, DependenciesErr),
/// Variant returned when a feature dependency is not a feature nor dependency.
///
/// The first contained `String` is the name of the feature, and the second `String` is the name of the invalid
/// feature dependency.
///
/// Note this is only possible when `allow_implied_features` is `true` when passed to
/// [`Features::validate_dependencies`] since when `false` we verify the the dependency
/// is defined as a feature.
InvalidDependency(String, String),
}
/// `"optional"`.
const OPTIONAL: &str = "optional";
/// `"target"`.
const TARGET: &str = "target";
impl ImpliedFeaturesErr {
/// Writes `self` to `stderr`.
fn write(self, mut stderr: StderrLock<'_>, file: &Path) -> Result<(), Error> {
match self {
Self::Dependencies(e) => match e {
DependenciesErr::Type(name) => {
writeln!(
stderr,
"'{name}' exists but is not a table in {}.",
file.display()
)
}
DependenciesErr::Name(name, dep_name) => {
writeln!(
stderr,
"'{name}.{dep_name}' is not a valid dependency name in {}.",
file.display()
)
}
DependenciesErr::DependencyType(name, dep_name) => {
writeln!(
stderr,
"'{name}.{dep_name}' exists but is not a string nor table in {}.",
file.display()
)
}
DependenciesErr::OptionalType(name, dep_name) => {
writeln!(
stderr,
"'{name}.{dep_name}.{OPTIONAL}' exists but is not a Boolean in {}.",
file.display()
)
}
DependenciesErr::ImpliedFeature(name, dep_name) => {
writeln!(
stderr,
"'{name}.{dep_name}' causes an implied feature to be defined in {}, but implied features were forbidden. --allow-implied-features can be passed to allow it.",
file.display()
)
}
},
Self::TargetType => {
writeln!(
stderr,
"'{TARGET}' exists but is not a table in {}.",
file.display()
)
}
Self::TargetPlatformType(name) => {
writeln!(
stderr,
"'{TARGET}.{name}' exists but is not a table in {}.",
file.display()
)
}
Self::TagetPlatformDependencies(name, e) => match e {
DependenciesErr::Type(table_name) => {
writeln!(
stderr,
"'{TARGET}.{name}.{table_name}' exists but is not a table in {}.",
file.display()
)
}
DependenciesErr::Name(table_name, dep_name) => {
writeln!(
stderr,
"'{TARGET}.{name}.{table_name}.{dep_name}' is not a valid dependency name in {}.",
file.display()
)
}
DependenciesErr::DependencyType(table_name, dep_name) => writeln!(
stderr,
"'{TARGET}.{name}.{table_name}.{dep_name}' exists but is not a string nor table in {}.",
file.display()
),
DependenciesErr::OptionalType(table_name, dep_name) => writeln!(
stderr,
"'{TARGET}.{name}.{table_name}.{dep_name}.{OPTIONAL}' exists but is not a Boolean in {}.",
file.display()
),
DependenciesErr::ImpliedFeature(table_name, dep_name) => {
writeln!(
stderr,
"'{TARGET}.{name}.{table_name}.{dep_name}' causes an implied feature to be defined in {}, but implied features were forbidden. --allow-implied-features can be passed to allow it.",
file.display()
)
}
},
Self::InvalidDependency(name, dep_name) => writeln!(
stderr,
"'{FEATURES}.{name}' contains '{dep_name}' which is neither a feature nor dependency in {}.",
file.display()
),
}
}
}
/// Error returned from parsing Cargo.toml.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) enum ManifestErr {
/// Variant returned when Cargo.toml is not valid TOML.
Toml(TomlErr, PathBuf),
/// Variant returned when extracting `package`.
Package(PackageErr, PathBuf),
/// Variant returned when extracting `features`.
Features(FeaturesErr, PathBuf),
/// Variant returned when extracting dependencies in order to add implied features.
ImpliedFeatures(ImpliedFeaturesErr, PathBuf),
/// Variant returned when ignoring a feature that does not exist.
UndefinedIgnoreFeature(String, PathBuf),
}
impl ManifestErr {
/// Writes `self` to `stderr`.
pub(crate) fn write(self, mut stderr: StderrLock<'_>) -> Result<(), Error> {
match self {
Self::Toml(e, file) => write!(
stderr,
"Error parsing package file {} as TOML: {e}.",
file.display()
),
Self::Package(e, file) => e.write(stderr, &file),
Self::Features(e, file) => e.write(stderr, &file),
Self::ImpliedFeatures(e, file) => e.write(stderr, &file),
Self::UndefinedIgnoreFeature(feature, file) => writeln!(
stderr,
"The feature '{feature}' was requested to be ignored, but it is not a feature in the package file {}.",
file.display()
),
}
}
}
/// Error when there are too many features to create the power set.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct TooManyFeaturesErr;
/// Parses `val` as a `u64` in decimal notation without leading 0s.
///
/// # Errors
///
/// Errors iff `val` is not a valid `u64` in decimal notation without leading 0s.
pub(crate) fn parse_int(val: &str) -> Result<u64, ()> {
val.as_bytes().first().ok_or(()).and_then(|fst| {
if *fst == b'0' {
if val.len() == 1 { Ok(0) } else { Err(()) }
} else {
val.parse().map_err(|_e| ())
}
})
}
/// MSRV in Cargo.toml.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct Msrv {
/// Major version.
major: u64,
/// Minor version.
minor: Option<u64>,
/// Patch version.
patch: Option<u64>,
}
impl Msrv {
/// Converts `msrv` into `Self` based on a valid MSRV string.
#[expect(unsafe_code, reason = "comments justify their correctness")]
fn extract_msrv(msrv: &str) -> Result<Self, ()> {
let mut iter = msrv.as_bytes().split(|b| *b == b'.');
iter.next().ok_or(()).and_then(|fst| {
// SAFETY:
// The original input is a `str` and we split on `b'.'` which is a single-byte
// UTF-8 code unit; thus we don't have to worry about splitting a multi-byte
// UTF-8 code unit.
let major_utf8 = unsafe { str::from_utf8_unchecked(fst) };
parse_int(major_utf8).and_then(|major| {
iter.next().map_or_else(
|| {
Ok(Self {
major,
minor: None,
patch: None,
})
},
|snd| {
// SAFETY:
// The original input is a `str` and we split on `b'.'` which is
// a single-byte UTF-8 code unit; thus we don't have to worry
// about splitting a multi-byte UTF-8 code unit.
let minor_utf8 = unsafe { str::from_utf8_unchecked(snd) };
parse_int(minor_utf8).and_then(|minor_val| {
iter.next().map_or_else(
|| {
Ok(Self {
major,
minor: Some(minor_val),
patch: None,
})
},
|lst| {
// SAFETY:
// The original input is a `str` and we split on
// `b'.'` which is a single-byte UTF-8 code
// unit; thus we don't have to worry about
// splitting a multi-byte UTF-8 code unit.
let patch_utf8 = unsafe { str::from_utf8_unchecked(lst) };
parse_int(patch_utf8).and_then(|patch_val| {
iter.next().map_or_else(
|| {
Ok(Self {
major,
minor: Some(minor_val),
patch: Some(patch_val),
})
},
|_| Err(()),
)
})
},
)
})
},
)
})
})
}
/// Reads `workspace` from `toml` extracting the MSRV.
fn extract_workspace(
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
) -> Result<Self, WorkspaceErr> {
toml.get(WORKSPACE)
.ok_or(WorkspaceErr::Missing)
.and_then(|work_span| {
if let DeValue::Table(ref workspace) = *work_span.get_ref() {
workspace
.get(PACKAGE)
.ok_or(WorkspaceErr::MissingPackage)
.and_then(|pack_span| {
if let DeValue::Table(ref package) = *pack_span.get_ref() {
package
.get(RUST_VERSION)
.ok_or(WorkspaceErr::MissingPackageMsrv)
.and_then(|msrv_span| {
if let DeValue::String(ref msrv) = *msrv_span.get_ref() {
Self::extract_msrv(msrv)
.map_err(|()| WorkspaceErr::Msrv)
} else {
Err(WorkspaceErr::InvalidPackageMsrvType)
}
})
} else {
Err(WorkspaceErr::InvalidPackageType)
}
})
} else {
Err(WorkspaceErr::InvalidType)
}
})
}
/// Recursively looks for `Cargo.toml` in `cur_dir` and ancestor directories until one is found
/// that contains a key named [`WORKSPACE`]. Once found, it's MSRV will be parsed and returned.
///
/// We make this recursive in case the (impossible?) path traversal becomes cyclic; in which
/// we want a stack overflow to occur.
///
/// Note if any error occurs not related to a not found file error, then this will error.
#[expect(
clippy::verbose_file_reads,
reason = "false positive since we want to lock the file"
)]
fn get_workspace_toml(mut cur_dir: PathBuf) -> Result<Self, PackageErr> {
cur_dir.push(super::cargo_toml());
match File::options()
.read(true)
.open(&cur_dir)
{
Ok(mut file) => {
file.try_lock_shared()
.map_err(PackageErr::WorkspaceLock)
.and_then(|()| {
file.metadata()
.map_err(PackageErr::WorkspaceIo)
.and_then(|meta| {
let meta_len = usize::try_from(meta.len()).unwrap_or(usize::MAX);
let mut data_utf8 = Vec::with_capacity(meta_len);
file.read_to_end(&mut data_utf8)
.map_err(PackageErr::WorkspaceIo)
.and_then(|len| {
drop(file);
if meta_len == len {
String::from_utf8(data_utf8)
.map_err(|e| PackageErr::WorkspaceIo(Error::other(e)))
.and_then(|data| {
Map::parse(&data)
.map_err(|e| PackageErr::WorkspaceToml(e, cur_dir.clone()))
.and_then(|toml| {
let t = toml.into_inner();
if t.contains_key(WORKSPACE) {
Self::extract_workspace(&t)
.map_err(|e| PackageErr::Workspace(e, cur_dir))
} else {
_ = cur_dir.pop();
if cur_dir.pop() {
Self::get_workspace_toml(cur_dir)
} else {
Err(PackageErr::WorkspaceDoesNotExist)
}
}
})
})
} else {
Err(PackageErr::WorkspaceLenMismatch)
}
})
})
})
}
Err(e) => {
if matches!(e.kind(), ErrorKind::NotFound) {
_ = cur_dir.pop();
if cur_dir.pop() {
Self::get_workspace_toml(cur_dir)
} else {
Err(PackageErr::WorkspaceIo(e))
}
} else {
Err(PackageErr::WorkspaceIo(e))
}
}
}
}
/// Extracts `"rust-version"` from `"package"` or `toml` in the case it's defined in a workspace.
#[expect(
clippy::panic_in_result_fn,
reason = "want to crash when there is a bug"
)]
#[expect(
clippy::verbose_file_reads,
reason = "false positive since we want to lock the file"
)]
fn extract_from_toml(
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
package: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
cargo_toml: &Path,
) -> Result<Option<Self>, PackageErr> {
package.get(RUST_VERSION).map_or(Ok(None), |msrv_span| {
match *msrv_span.get_ref() {
DeValue::String(ref msrv) => Self::extract_msrv(msrv)
.map_err(|()| PackageErr::Msrv)
.map(Some),
DeValue::Table(ref msrv) => msrv
.get(WORKSPACE)
.ok_or(PackageErr::MsrvWorkspaceMissing)
.and_then(|work| {
if matches!(*work.get_ref(), DeValue::Boolean(b) if b) {
package.get(WORKSPACE).map_or_else(
|| if toml.contains_key(WORKSPACE) {
Self::extract_workspace(toml).map_err(|e| PackageErr::Workspace(e, cargo_toml.to_path_buf())).map(Some)
} else {
let mut search_path = cargo_toml.to_path_buf();
assert!(search_path.pop(), "there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.");
if search_path.pop() {
Self::get_workspace_toml(search_path).map(Some)
} else {
Err(PackageErr::WorkspaceDoesNotExist)
}
},
|path_span| {
if let DeValue::String(ref workspace_path) = *path_span.get_ref() {
let mut path = cargo_toml.to_path_buf();
assert!(path.pop(), "there is a bug in main. manifest::Manifest::from_toml must be passed the absolute path to the package's Cargo.toml.");
path.push(workspace_path.as_ref());
path.push(super::cargo_toml());
File::options().read(true).open(&path).map_err(|e| PackageErr::WorkspaceRead(e, path.clone())).and_then(|mut workspace_file| {
workspace_file.try_lock_shared().map_err(|e| PackageErr::WorkspaceReadLock(e, path.clone())).and_then(|()| {
workspace_file.metadata().map_err(|e| PackageErr::WorkspaceRead(e, path.clone())).and_then(|meta| {
let meta_len = usize::try_from(meta.len()).unwrap_or(usize::MAX);
let mut workspace_utf8 = Vec::with_capacity(meta_len);
workspace_file.read_to_end(&mut workspace_utf8).map_err(|e| PackageErr::WorkspaceRead(e, path.clone())).and_then(|len| {
drop(workspace_file);
if meta_len == len {
String::from_utf8(workspace_utf8).map_err(|e| PackageErr::WorkspaceRead(Error::other(e), path.clone())).and_then(|workspace_data| {
Map::parse(&workspace_data).map_err(|e| PackageErr::WorkspaceToml(e, path.clone())).and_then(|workspace_toml| Self::extract_workspace(workspace_toml.get_ref()).map_err(|e| PackageErr::Workspace(e, path)).map(Some))
})
} else {
Err(PackageErr::WorkspaceReadLenMismatch(path))
}
})
})
})
})
} else {
Err(PackageErr::InvalidWorkspaceType)
}
},
)
} else {
Err(PackageErr::MsrvWorkspaceVal)
}
}),
DeValue::Integer(_)
| DeValue::Float(_)
| DeValue::Boolean(_)
| DeValue::Datetime(_)
| DeValue::Array(_) => Err(PackageErr::InvalidMsrvType),
}
})
}
/// Returns `Some` containing the MSRV with `'+'` prepended iff `stable` is semantically greater than `self`
/// or the default toolchan is semantically not equivalent to `self`; otherwise returns `None`.
///
/// When `stable` is semantically less than the MSRV, an error is returned.
pub(crate) fn compare_to_other(
&self,
default: bool,
rustup_home: Option<&Path>,
cargo_path: &Path,
cargo_home: Option<&Path>,
) -> Result<Option<String>, Box<ToolchainErr>> {
if default {
Toolchain::Default(false)
} else {
Toolchain::Stable
}
.get_version(rustup_home, cargo_path, cargo_home)
.and_then(|stable_dflt_version| {
match self.major.cmp(&stable_dflt_version.major) {
Ordering::Less => Ok(true),
Ordering::Equal => self.minor.map_or_else(
|| Ok(false),
|min| match min.cmp(&stable_dflt_version.minor) {
Ordering::Less => Ok(true),
Ordering::Equal => self.patch.map_or_else(
|| Ok(false),
|pat| match pat.cmp(&stable_dflt_version.patch) {
Ordering::Less => Ok(true),
Ordering::Equal => Ok(false),
Ordering::Greater => {
if default {
Ok(true)
} else {
Err(Box::new(ToolchainErr::MsrvTooHigh))
}
}
},
),
Ordering::Greater => {
if default {
Ok(true)
} else {
Err(Box::new(ToolchainErr::MsrvTooHigh))
}
}
},
),
Ordering::Greater => {
if default {
Ok(true)
} else {
Err(Box::new(ToolchainErr::MsrvTooHigh))
}
}
}
.and_then(|get_msrv| {
if get_msrv {
Toolchain::Msrv(&self.minor.map_or_else(
|| format!("+{}", self.major),
|min| {
self.patch.map_or_else(
|| format!("+{}.{min}", self.major),
|pat| format!("+{}.{min}.{pat}", self.major),
)
},
))
.get_version(rustup_home, cargo_path, cargo_home)
.and_then(|msrv_version| {
if msrv_version.major == self.major
&& self.minor.is_none_or(|minor| {
msrv_version.minor == minor
&& self.patch.is_none_or(|patch| msrv_version.patch == patch)
})
{
Ok(Some(format!(
"+{}.{}.{}",
msrv_version.major, msrv_version.minor, msrv_version.patch
)))
} else {
Err(Box::new(ToolchainErr::MsrvNotCompatibleWithInstalledMsrv(
msrv_version,
)))
}
})
} else {
Ok(None)
}
})
})
}
}
/// `package` info.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct Package {
/// `rust-version`.
msrv: Option<Msrv>,
/// `name`.
name: String,
}
impl Package {
/// MSRV.
pub(crate) const fn msrv(&self) -> Option<&Msrv> {
self.msrv.as_ref()
}
/// Name.
pub(crate) const fn name(&self) -> &str {
self.name.as_str()
}
/// Extracts `"package"` from `toml`.
fn extract_from_toml(
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
cargo_toml: &Path,
) -> Result<Self, PackageErr> {
toml.get(PACKAGE)
.ok_or(PackageErr::Missing)
.and_then(|pack_span| {
if let DeValue::Table(ref package) = *pack_span.get_ref() {
package
.get(NAME)
.ok_or(PackageErr::MissingName)
.and_then(|name_span| {
if let DeValue::String(ref name) = *name_span.get_ref() {
Msrv::extract_from_toml(toml, package, cargo_toml).map(|msrv| {
Self {
msrv,
name: name.clone().into_owned(),
}
})
} else {
Err(PackageErr::InvalidNameType)
}
})
} else {
Err(PackageErr::InvalidType)
}
})
}
}
/// Returns `true` iff `nodes` is pairwise disconnected.
#[expect(
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
reason = "comment justifies correctness"
)]
fn pairwise_disconnected(nodes: &[&str], features: &[(String, Vec<String>)]) -> bool {
/// `panic`s with a static message about the existence of a bug in [`Manifest::deserialize`].
#[expect(clippy::unreachable, reason = "want to crash when there is a bug")]
fn impossible<T>() -> T {
unreachable!(
"there is a bug in manifest::Manifest::deserialize where feature dependencies are not only features."
)
}
/// Returns `true` iff `feature_deps` directly contains `feature` or indirectly in the `Vec<String>`
/// associated with it.
fn contains(
feature_deps: &[String],
feature: &str,
features: &[(String, Vec<String>)],
) -> bool {
feature_deps.iter().any(|feat| {
feat == feature
|| contains(
&features
.iter()
.find(|val| val.0 == *feat)
.unwrap_or_else(impossible)
.1,
feature,
features,
)
})
}
!nodes.iter().enumerate().any(|(idx, feature)| {
let feature_info = &features
.iter()
.find(|val| val.0 == **feature)
.unwrap_or_else(impossible)
.1;
// `idx < nodes.len()`, so overflow is not possible and indexing is fine.
nodes[idx + 1..].iter().any(|feat| {
contains(feature_info, feat, features)
|| contains(
features
.iter()
.find(|val| val.0 == **feat)
.unwrap_or_else(impossible)
.1
.as_slice(),
feature,
features,
)
})
})
}
/// Power set of [`Features`] returned from [`Features::power_set`].
///
/// Note this is technically not the power set of features since semantically equivalent sets are ignored.
///
/// The last set iterated will always be the empty set. If no features in [`Features`] depend on another
/// feature, then this will always return the entire set of features first; otherwise the entire set will
/// never be returned. The expected cardinality of a set iterated decreases; thus while it will almost always
/// be possible for a set _A_ to have larger cardinality than a set _B_ even when _A_ is iterated before _B_,
/// the expected value is smaller.
///
/// The reason we attempt, but don't guarantee, that the first set iterated corresponds to a semantically
/// equivalent set as the original set is to take advantage of the parallel compiliation that occurs. Typically
/// the more features one enables, the more dependencies and functionality is added. By compiling code that
/// maximizes this first, we take better advantage of how code is compiled; in contrast if we compiled fewer
/// features first, subsequent compilations with more features will have to happen. We don't guarantee this
/// though since it slightly complicates code; instead we iterate based on the _expected_ cardinality in
/// descending order.
///
/// We don't implement `Iterator` since we want to re-use the same `String` that represents the set we are
/// returning.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct PowerSet<'a> {
/// The set of features.
feats: &'a [(String, Vec<String>)],
/// `true` iff there are more sets to iterate.
has_remaining: bool,
/// `true` iff `feats` has redundant features; thus requiring us to check if a given set should be returned.
check_overlap: bool,
/// The current element of the power set that we are to return.
///
/// This gets decremented as we iterate sets.
idx: usize,
/// Intermediate buffer we use to check if a set contains redundant features.
buffer: Vec<&'a str>,
/// The set we return.
///
/// This is of the form `"<feat_1>,<feat_2>,...,<feat_n>"`.
set: String,
/// Number of sets skipped due to an equivalence with a smaller set.
skipped_sets_counter: usize,
/// `true` iff they empty set should be skipped.
///
/// This doesn't contribute to [`Self::skipped_sets_counter`].
skip_empty_set: bool,
}
impl<'a> PowerSet<'a> {
/// Max cardinality of a set we allow to take the power set of.
// usize::MAX = 2^usize::BITS - 1 >= usize::BITS since usize::MAX >= 0;
// thus `usize::BITS as usize` is free from truncation.
#[expect(clippy::as_conversions, reason = "comment justifies correctness")]
const MAX_SET_LEN: usize = usize::BITS as usize;
/// Returns the cardinality less one of the power set of a set
/// whose cardinality is `set_len`.
///
/// `set_len` MUST not be greater than [`Self::MAX_SET_LEN`].
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
const fn len_minus_one(set_len: usize) -> usize {
assert!(
set_len <= Self::MAX_SET_LEN,
"manifest::PowerSet::len_minus_one must be passed a `usize` no larger than PowerSet::MAX_SET_LEN"
);
if set_len == Self::MAX_SET_LEN {
usize::MAX
} else {
// We verified that `set_len <= usize::BITS`; thus
// this won't overflow nor underflow since 2^0 = 1.
(1 << set_len) - 1
}
}
/// Returns the cardinality of `self`.
///
/// Note this is constant and is not affected by iteration of
/// `self`. This isn't the remaining length. [`Self::skip_empty_set`]
/// contributes towards this value.
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
pub(crate) fn len(&self) -> NonZeroUsizePlus1 {
// We don't allow construction of `PowerSet` unless the set of features
// is no more than [`Self::MAX_SET_LEN`]; thus this won't `panic`.
// Underflow won't occur either since we don't allow construction when the
// set of features is empty and when we must skip the empty set.
// `NonZeroUsizePlus1` treats `0` as `usize::MAX + 1`, so we use wrapping addition.
// This will only wrapp when `self.features.len() == Self::MAX_SET_LEN` and `!self.skip_empty_set`.
NonZeroUsizePlus1::new(
(Self::len_minus_one(self.feats.len()) - usize::from(self.skip_empty_set))
.wrapping_add(1),
)
}
/// Contructs `Self` based on `features`.
///
/// When iterating the sets, the empty set will be skipped iff `skip_empty_set`;
/// but this _won't_ contribute to `skipped_sets_counter`.
///
/// Returns `None` iff `features` is empty and `skip_empty_set`.
fn new(
features: &'a Features,
skip_empty_set: bool,
) -> Result<Option<Self>, TooManyFeaturesErr> {
let len = features.0.len();
match len {
0 if skip_empty_set => Ok(None),
..=Self::MAX_SET_LEN => {
let mut buffer = Vec::with_capacity(len);
features.0.iter().fold((), |(), key| {
buffer.push(key.0.as_ref());
});
let check_overlap = !pairwise_disconnected(buffer.as_slice(), &features.0);
Ok(Some(Self {
feats: &features.0,
has_remaining: true,
check_overlap,
// We verified `len <= Self::MAX_SET_LEN`, so this won't `panic`.
idx: Self::len_minus_one(len),
buffer,
// This won't overflow since `usize::MAX = 2^usize::BITS - 1`, `usize::BITS >= 16`, the max
// value of `len` is `usize::BITS`.
// 16 * usize::BITS < 2^usize::BITS for `usize::BITS > 6`.
set: String::with_capacity(len << 4),
skipped_sets_counter: 0,
skip_empty_set,
}))
}
_ => Err(TooManyFeaturesErr),
}
}
/// Resets `self` such that iteration returns to the beginning.
pub(crate) const fn reset(&mut self) {
// We don't allow construction of `PowerSet` when the number of
// features exceeds [`Self::MAX_SET_LEN`], so this won't `panic`.
self.idx = Self::len_minus_one(self.feats.len());
self.has_remaining = true;
self.skipped_sets_counter = 0;
}
/// Writes the next element into `self.buffer` even if the set contains overlapping features.
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
fn inner_next_set(&mut self) {
self.buffer.clear();
self.feats.iter().enumerate().fold((), |(), (i, feat)| {
if self.idx & (1 << i) != 0 {
self.buffer.push(feat.0.as_str());
}
});
if self.idx == 0 {
self.has_remaining = false;
// The empty set is always the last set.
} else if self.idx == 1 && self.skip_empty_set {
self.idx = 0;
self.has_remaining = false;
} else {
// This won't underflow since `idx > 0`.
self.idx -= 1;
}
}
/// Transforms the current element into its string form.
fn current_set(&mut self) {
self.set.clear();
self.buffer.iter().fold((), |(), s| {
self.set.push_str(s);
self.set.push(',');
});
// We remove the trailing comma. In the event `self.set` is empty, this does nothing.
_ = self.set.pop();
}
/// Returns the next set.
///
/// This returns `None` iff there are no more sets to return. It will continue to return `None`
/// unless [`Self::reset`] is called.
pub(crate) fn next_set(&mut self) -> Option<&str> {
self.next_set_with_skip_count().map(|tup| tup.0)
}
/// Returns the next set along with the number of set skipped thus far.
///
/// This returns `None` iff there are no more sets to return. It will continue to return `None`
/// unless [`Self::reset`] is called.
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
pub(crate) fn next_set_with_skip_count(&mut self) -> Option<(&str, usize)> {
if self.has_remaining {
if self.check_overlap {
while self.has_remaining {
self.inner_next_set();
if pairwise_disconnected(self.buffer.as_slice(), self.feats) {
self.current_set();
return Some((&self.set, self.skipped_sets_counter));
}
// This maxes at `usize::MAX` since we ensure a power set is not created on a
// set with more than `usize::BITS` elements.
// We set to set every time [`Self::reset`] is called as well.
self.skipped_sets_counter += 1;
}
None
} else {
self.inner_next_set();
self.current_set();
Some((&self.set, self.skipped_sets_counter))
}
} else {
None
}
}
}
/// Dependency table.
enum DepTable {
/// Library dependencies.
Dependencies,
/// Build dependencies.
BuildDependencies,
}
impl DepTable {
/// Returns the string representation of `self`.
const fn into_str(self) -> &'static str {
match self {
Self::Dependencies => "dependencies",
Self::BuildDependencies => "build-dependencies",
}
}
}
/// `"dep:"`.
const DEP: &[u8; 4] = b"dep:";
/// Returns `true` iff `utf8` begins with [`DEP`].
fn is_feature_dependency_a_dependency(utf8: &[u8]) -> bool {
utf8.starts_with(DEP)
}
/// Returns `true` iff `name` does not contain a `'/'` nor begins with [`DEP`].
fn is_feature_dependency_a_feature(name: &str) -> bool {
let utf8 = name.as_bytes();
!(utf8.contains(&b'/') || is_feature_dependency_a_dependency(utf8))
}
/// Features in Cargo.toml.
///
/// Note this contains a `Vec` instead of a `HashMap` or `BTreeMap` since we enforce that very few entries exist
/// due to the exponential nature of generating the power set; thus making a `Vec` more efficient and faster.
/// This size is so small that we don't even sort and perform a binary search.
///
/// The `String` in the tuple represents the name of the feature, and the `Vec` in the tuple represents the
/// feature dependencies. The feature dependencies will not contain any dependency that contains a `'/'`
/// but will contain all others. The name of each feature will not contain a `'/'` nor begin with [`DEP`].
/// Each dependency that is a feature (i.e., does not begin with [`DEP`]) is well-defined (i.e., is a feature
/// itself) when `false` is passed to [`Self::extract_from_toml`]; when `true` is passed, then feature dependencies
/// that are features are not verified to be defined in `self` since implied features still have to be added.
/// Each feature does not contain any cycles nor redundant dependencies.
///
/// One must still add implied features caused from any optional dependencies iff `true` is passed to
/// [`Self::extract_from_toml`]; after which, one needs to remove all dependencies that are not features and verify
/// all dependencies that are features are defined in `self` in order for [`PowerSet`] to work correctly. A feature
/// with name `<dependency>` needs to be added with an empty `Vec` of dependencies iff no features exist that have a
/// dependency whose name is `"dep:<dependency>"` _and_ there doesn't already exist a feature with that name.
/// An error MUST NOT happen if there is such a feature since different kinds of dependencies can have the
/// same name. While this will allow for the situation where a feature is defined with the same name as
/// an implied feature, that won't matter once `cargo` is run since it will error anyway.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct Features(Vec<(String, Vec<String>)>);
impl Features {
/// Returns `true` iff `self` contains a feature named `"default"`.
pub(crate) fn contains_default(&self) -> bool {
self.0.iter().any(|f| f.0 == "default")
}
/// `panic`s with a static message about the existence of a bug in `validate_dependencies`.
///
/// This is used in lieu of `unreachable` in `validate_dependencies`, `check_redundant_features`
/// and `extract_feature_dependencies`.
#[expect(clippy::unreachable, reason = "want to crash when there is a bug")]
fn impossible<T>() -> T {
unreachable!("there is a bug in manifest::Features::validate_dependencies.")
}
/// Verifies dependencies associated with `feature` is valid.
///
/// `dependencies` are assumed to be associated with `feature` which the pair of is checked to be
/// a key-value pair from `features` iff `allow_implied_features`. This verifies the following:
///
/// * `dependencies` is an array that only contains strings.
/// * Each string in `dependencies` that does not contain a `'/'` nor begins with [`DEP`] is a key
/// in `features` iff `allow_implied_features`.
/// * `feature` nor any dependency that is a feature in `dependencies` is cyclic.
///
/// `cycle_detection` MUST contain only `feature` when this is called externally.
///
/// This MUST only be called by itself or [`Self::extract_feature_dependencies`].
fn validate_dependencies<'a>(
feature: &str,
dependencies: &'a DeValue<'_>,
features: &'a Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
cycle_detection: &mut Vec<&'a str>,
allow_implied_features: bool,
) -> Result<(), FeatureDependenciesErr> {
if let DeValue::Array(ref info) = *dependencies {
info.iter().try_fold((), |(), dep_span| {
if let DeValue::String(ref dep_name) = *dep_span.get_ref() {
if is_feature_dependency_a_feature(dep_name) {
if cycle_detection.contains(&dep_name.as_ref()) {
Err(FeatureDependenciesErr::CyclicFeature(
dep_name.clone().into_owned(),
))
} else if let Some(next_feature) = features.get(dep_name.as_ref()) {
cycle_detection.push(dep_name);
Self::validate_dependencies(
dep_name,
next_feature.get_ref(),
features,
cycle_detection,
allow_implied_features,
)
.map(|()| {
// We require calling code to add `feature` before calling this function. We
// always add the most recent feature dependency. Therefore this is not empty.
_ = cycle_detection.pop().unwrap_or_else(Self::impossible);
})
} else if allow_implied_features {
// `dep_name` may be an implied feature which we have yet to add.
Ok(())
} else {
// We require calling code to add `feature` before calling this function. We always
// add the most recent feature dependency. Therefore this is not empty.
Err(FeatureDependenciesErr::InvalidDependency(
cycle_detection
.pop()
.unwrap_or_else(Self::impossible)
.to_owned(),
dep_name.clone().into_owned(),
))
}
} else {
Ok(())
}
} else {
Err(FeatureDependenciesErr::InvalidDependencyType(
feature.to_owned(),
))
}
})
} else {
Err(FeatureDependenciesErr::InvalidFeatureType(
feature.to_owned(),
))
}
}
/// Verifies there are no redundant dependencies that are features in `dependencies`.
///
/// Returns `true` iff there is a redundant dependency.
///
/// This must be called _after_ `validate_dependencies` is called on the same arguments.
fn check_redundant_dependencies(
feature: &str,
dependencies: &DeArray<'_>,
features: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
allow_implied_features: bool,
) -> bool {
dependencies.iter().any(|dep_span| {
if let DeValue::String(ref dep_name) = *dep_span.get_ref() {
is_feature_dependency_a_feature(dep_name)
&& (feature == dep_name
|| features.get(dep_name.as_ref()).map_or_else(
|| {
if allow_implied_features {
false
} else {
// We require `validate_dependencies` to be called before this function which
// ensures all features recursively in the `dependencies` are defined as features iff `!allow_implied_features`.
Self::impossible()
}
},
|next_feature_span| {
Self::check_redundant_dependencies(
feature,
next_feature_span
.get_ref()
.as_array()
// We require `validate_dependencies` to be called before this function
// which ensures all feature dependencies recursively are arrays.
.unwrap_or_else(Self::impossible),
features,
allow_implied_features,
)
},
))
} else {
// We require `validate_dependencies` to be called before this function which ensures all
// dependencies recursivley in `dependencies` are strings.
Self::impossible()
}
})
}
/// Extracts the feature dependencies associated with `feature`.
///
/// `dependencies` are assumed to be associated with `feature` which the pair of is checked to be
/// a key-value pair from `features` iff `allow_implied_features`. This verifies the following:
///
/// * `dependencies` is an array that only contains strings.
/// * Each string in `dependencies` that does not contain a `'/'` nor begins with [`DEP`] is a key
/// in `features` iff `allow_implied_features`.
/// * There is no redundant feature in `dependencies` where "redundant" means the following:
/// * There are no cycles (e.g., feature = \["feature"] or feature = \["a"], a = \["b"], b = \["a"]).
/// * No unnecessary dependencies that are features (e.g., feature = \["a", "a"] or feature = \["a", "b"]
/// a = \["b"], b = \[]).
/// * There are no duplicate dependencies in `dependencies` that beging with [`DEP`].
///
/// Note since all dependencies that contain a `'/'` are ignored, there may be duplicates of them.
/// Also when checking for redundant features in `dependencies`, _only_ features are considered; thus
/// something like the following is allowed: feature = \["dep:a", "a"], a = \["dep:a"].
///
/// This must only be called from [`Self::extract_from_toml`].
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
fn extract_feature_dependencies<'a>(
feature: &'a str,
dependencies: &'a DeValue<'_>,
features: &'a Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
cycle_buffer: &mut Vec<&'a str>,
allow_implied_features: bool,
) -> Result<Vec<String>, FeatureDependenciesErr> {
// `Self::validate_dependencies` requires `cycle_buffer` to contain, and only contain, `feature`.
cycle_buffer.clear();
cycle_buffer.push(feature);
Self::validate_dependencies(feature, dependencies, features, cycle_buffer, allow_implied_features).and_then(|()| {
// `validate_dependencies` ensures `dependencies` is an array.
let deps = dependencies.as_array().unwrap_or_else(Self::impossible);
let mut vec_deps = Vec::with_capacity(deps.len());
deps.iter().enumerate().try_fold((), |(), (idx, dep_span)| if let DeValue::String(ref dep_name) = *dep_span.get_ref() {
let dep_utf8 = dep_name.as_bytes();
if dep_utf8.contains(&b'/') {
Ok(())
} else if is_feature_dependency_a_dependency(dep_utf8) {
if vec_deps.iter().any(|d| d == dep_name) {
Err(FeatureDependenciesErr::RedundantDependency(feature.to_owned(), dep_name.clone().into_owned()))
} else {
vec_deps.push(dep_name.clone().into_owned());
Ok(())
}
} else if let Some(next_feature_span) = features.get(dep_name.as_ref()) {
// `validate_dependencies` ensures all feature
// dependencies recursively are arrays.
let feat_info = next_feature_span.get_ref().as_array().unwrap_or_else(Self::impossible);
// `idx < deps.iter().len()`; thus this won't overflow.
deps.iter().skip(idx + 1).try_fold((), |(), next_dep_span| if let DeValue::String(ref next_dep_name) = *next_dep_span.get_ref() {
if is_feature_dependency_a_feature(next_dep_name) {
if dep_name == next_dep_name {
Err(FeatureDependenciesErr::RedundantDependency(feature.to_owned(), dep_name.clone().into_owned()))
} else if Self::check_redundant_dependencies(next_dep_name, feat_info, features, allow_implied_features) {
Err(FeatureDependenciesErr::RedundantDependency(feature.to_owned(), next_dep_name.clone().into_owned()))
} else {
features.get(next_dep_name.as_ref()).map_or_else(
|| {
if allow_implied_features {
Ok(())
} else {
// `validate_dependencies` ensures all features
// recursively in the feature dependencies are defined
// as features iff `!allow_implied_features`.
Self::impossible()
}
},
|next_dep_feature_span| {
// `validate_dependencies` ensures all feature
// dependencies recursively are arrays.
if Self::check_redundant_dependencies(dep_name, next_dep_feature_span.get_ref().as_array().unwrap_or_else(Self::impossible), features, allow_implied_features) {
Err(FeatureDependenciesErr::RedundantDependency(feature.to_owned(), dep_name.clone().into_owned()))
} else {
Ok(())
}
}
)
}
} else {
Ok(())
}
} else {
// `validate_dependencies` ensures all dependencies recursively in `dependencies` are
// strings.
Self::impossible()
}).map(|()| vec_deps.push(dep_name.clone().into_owned()))
} else if allow_implied_features {
vec_deps.push(dep_name.clone().into_owned());
Ok(())
} else {
// `validate_dependencies` ensures all features
// recursively in `dependencies` are defined as features
// iff `!allow_implied_features`.
Self::impossible()
}
} else {
// `validate_dependencies` ensures all dependencies recursively in `dependencies` are strings.
Self::impossible()
}).map(|()| vec_deps)
})
}
/// Extracts `"features"` from `toml`.
fn extract_from_toml(
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
allow_implied_features: bool,
) -> Result<Self, FeaturesErr> {
toml.get(FEATURES).map_or_else(
|| Ok(Self(Vec::new())),
|features_span| {
if let DeValue::Table(ref features) = *features_span.get_ref() {
let mut cycle_buffer = Vec::with_capacity(features.len());
let mut feats = Vec::with_capacity(features.len());
features
.iter()
.try_fold((), |(), (name_span, feature_span)| {
let name = name_span.get_ref();
if is_feature_dependency_a_feature(name) {
Self::extract_feature_dependencies(
name,
feature_span.get_ref(),
features,
&mut cycle_buffer,
allow_implied_features,
)
.map_err(FeaturesErr::FeatureDependencies)
.map(|deps| {
feats.push((name.clone().into_owned(), deps));
})
} else {
Err(FeaturesErr::InvalidName(name.clone().into_owned()))
}
})
.map(|()| Self(feats))
} else {
Err(FeaturesErr::InvalidType)
}
},
)
}
/// Extracts optional dependencies and adds their corresponding implied feature to `self` iff
/// `allow_implied_features` and it's appropriate to do so.
///
/// This must only be called from [`Self::add_implied_features`].
fn add_optional_dependencies(
&mut self,
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
table: DepTable,
allow_implied_features: bool,
) -> Result<(), DependenciesErr> {
let table_name = table.into_str();
toml.get(table_name).map_or(Ok(()), |deps_span| {
if let DeValue::Table(ref deps) = *deps_span.get_ref() {
deps.iter().try_fold((), |(), dep_span| {
let dep_name = dep_span.0.get_ref();
if is_feature_dependency_a_feature(dep_name) {
match *dep_span.1.get_ref() {
DeValue::String(_) => Ok(()),
DeValue::Table(ref dep_info) => {
dep_info.get(OPTIONAL).map_or(Ok(()), |opt_span| {
if let DeValue::Boolean(ref optional) = *opt_span.get_ref() {
if *optional {
self.0
.iter()
.try_fold((), |(), feat| {
if feat.0 == *dep_name {
// We already have a feature with the same name,
// so we don't need to continue.
Err(())
} else if feat.1.iter().any(|feat_dep| {
feat_dep
.as_bytes()
.split_at_checked(DEP.len())
.is_some_and(|(pref, rem)| {
pref == DEP
&& dep_name.as_bytes() == rem
})
}) {
// The feature dependencies contain `"dep:<dep_name>"`,
// so we don't need to add an implied feature.
Err(())
} else {
// The feature name is not `<dep_name>` and all of
// feature dependencies of all features are not named
// `"dep:<dep_name>"`; thus we need to continue our
// search.
Ok(())
}
})
.map_or(Ok(()), |()| {
if allow_implied_features {
// There is no feature with the name `<dep_name>` nor
// are there any features that contain a feature
// dependency named `"dep:<dep_name>"`; thus we must
// insert an implied feature.
self.0.push((
dep_name.clone().into_owned(),
Vec::new(),
));
Ok(())
} else {
Err(DependenciesErr::ImpliedFeature(
table_name,
dep_name.clone().into_owned(),
))
}
})
} else {
Ok(())
}
} else {
Err(DependenciesErr::OptionalType(
table_name,
dep_name.clone().into_owned(),
))
}
})
}
DeValue::Integer(_)
| DeValue::Float(_)
| DeValue::Boolean(_)
| DeValue::Datetime(_)
| DeValue::Array(_) => Err(DependenciesErr::DependencyType(
table_name,
dep_name.clone().into_owned(),
)),
}
} else {
Err(DependenciesErr::Name(
table_name,
dep_name.clone().into_owned(),
))
}
})
} else {
Err(DependenciesErr::Type(table_name))
}
})
}
/// Adds implied features to `self` based on the optional dependencies in `toml` iff `allow_implied_features`.
fn add_implied_features(
&mut self,
toml: &Map<Spanned<Cow<'_, str>>, Spanned<DeValue<'_>>>,
allow_implied_features: bool,
) -> Result<(), ImpliedFeaturesErr> {
self.add_optional_dependencies(toml, DepTable::Dependencies, allow_implied_features).map_err(ImpliedFeaturesErr::Dependencies).and_then(|()| self.add_optional_dependencies(toml, DepTable::BuildDependencies, allow_implied_features).map_err(ImpliedFeaturesErr::Dependencies).and_then(|()| toml.get(TARGET).map_or_else(
|| Ok(()),
|target_span| {
if let DeValue::Table(ref target) = *target_span.get_ref() {
target.iter().try_fold((), |(), target_platform_span| {
if let DeValue::Table(ref target_platform) = *target_platform_span.1.get_ref() {
self.add_optional_dependencies(target_platform, DepTable::Dependencies, allow_implied_features).map_err(|e| ImpliedFeaturesErr::TagetPlatformDependencies(target_platform_span.0.get_ref().clone().into_owned(), e)).and_then(|()| self.add_optional_dependencies(target_platform, DepTable::BuildDependencies, allow_implied_features).map_err(|e| ImpliedFeaturesErr::TagetPlatformDependencies(target_platform_span.0.get_ref().clone().into_owned(), e)))
} else {
Err(ImpliedFeaturesErr::TargetPlatformType(target_platform_span.0.get_ref().clone().into_owned()))
}
})
} else {
Err(ImpliedFeaturesErr::TargetType)
}
}
).and_then(|()| {
if allow_implied_features {
// We don't have to worry about cyclic features or anything other than the lack of a feature with
// the name of the feature dependency.
self.0.iter().try_fold((), |(), feature| feature.1.iter().try_fold((), |(), dep| {
// We didn't save any feature dependencies that contain `'/'`, so we simply have to check if
// a dependency begins with [`DEP`] to skip it.
if is_feature_dependency_a_dependency(dep.as_bytes()) || self.0.iter().any(|other_feature| other_feature.0 == *dep) {
Ok(())
} else {
Err(ImpliedFeaturesErr::InvalidDependency(feature.0.clone(), dep.clone()))
}
}))
} else {
// When `!allowed_implied_features`, [`Self::validate_dependencies`] verifies non-dependency
// feature dependencies are defined as features.
Ok(())
}
})))
}
/// Returns the power set of `self` with semantically equivalent sets removed.
///
/// The empty set of features is skipped iff `skip_no_feats`. None is only
/// returned if there are no sets of features. This is only possible iff
/// `self` contains no features and `skip_no_feats`.
pub(crate) fn power_set(
&self,
skip_no_feats: bool,
) -> Result<Option<PowerSet<'_>>, TooManyFeaturesErr> {
PowerSet::new(self, skip_no_feats)
}
}
/// Package and features in `Cargo.toml`.
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct Manifest {
/// The package.
package: Package,
/// The features.
features: Features,
}
impl Manifest {
/// Returns the defined MSRV iff there was one defined.
pub(crate) const fn package(&self) -> &Package {
&self.package
}
/// Returns the defined features.
///
/// Note the returned `Features` doesn't have any cyclic features, each feature dependency for a given
/// feature is a feature itself, and there are no redundant feature dependencies for a given feature.
pub(crate) const fn features(&self) -> &Features {
&self.features
}
/// Returns the data needed from `Cargo.toml`.
///
/// Note `ignore_features` MUST not contain an empty `String`.
#[expect(
clippy::arithmetic_side_effects,
reason = "comments justify correctness"
)]
#[expect(
clippy::needless_pass_by_value,
reason = "want to drop `val` as soon as possible"
)]
pub(crate) fn from_toml(
val: String,
allow_implied_features: bool,
cargo_toml: &Path,
ignore_features: &[String],
) -> Result<Self, Box<ManifestErr>> {
Map::parse(val.as_str())
.map_err(|e| Box::new(ManifestErr::Toml(e, cargo_toml.to_path_buf())))
.and_then(|span| {
let cargo = span.get_ref();
Package::extract_from_toml(cargo, cargo_toml)
.map_err(|e| Box::new(ManifestErr::Package(e, cargo_toml.to_path_buf())))
.and_then(|package| {
Features::extract_from_toml(cargo, allow_implied_features)
.map_err(|e| {
Box::new(ManifestErr::Features(e, cargo_toml.to_path_buf()))
})
.and_then(|mut features| {
features
.add_implied_features(cargo, allow_implied_features)
.map_err(|e| {
Box::new(ManifestErr::ImpliedFeatures(
e,
cargo_toml.to_path_buf(),
))
})
.and_then(|()| {
features.0.iter_mut().fold(
(),
|(), &mut (_, ref mut deps)| {
deps.retain(|d| {
// We retain only features. Since we didn't save any
// dependencies that contain `'/'`, it's slightly faster to just
// check that a feature dependency is not a dependency.
!is_feature_dependency_a_dependency(
d.as_bytes(),
)
});
},
);
// First we ensure all features we are to ignore are defined;
// while doing this, we remove the feature. Note `ignore_features`
// and `features` only contain distinct features, so we simply
// have to check for the first occurrence.
// Note calling code is required to have removed the empty
// string if it had existed.
ignore_features
.iter()
.try_fold((), |(), ig_feat| {
features
.0
.iter()
.try_fold(0, |idx, info| {
if info.0 == *ig_feat {
Err(idx)
} else {
// Clearly free from overflow.
Ok(idx + 1)
}
})
.map_or_else(
|idx| {
drop(features.0.swap_remove(idx));
Ok(())
},
|_| {
Err(Box::new(
ManifestErr::UndefinedIgnoreFeature(
ig_feat.clone(),
cargo_toml.to_path_buf(),
),
))
},
)
})
.map(|()| {
// Now we remove all features that depend on the
// features we are to ignore.
ignore_features.iter().fold((), |(), ig_feat| {
features.0.retain(|info| {
!info.1.iter().any(|d| d == ig_feat)
});
});
Self { package, features }
})
})
})
})
})
}
}