1use std::collections::BTreeSet;
122use std::env;
123use std::fmt::{self, Write};
124use std::path::PathBuf;
125use std::str::FromStr;
126
127use anyhow::{Error, bail};
128use cargo_util::ProcessBuilder;
129use serde::{Deserialize, Serialize};
130use tracing::debug;
131
132use crate::GlobalContext;
133use crate::core::resolver::ResolveBehavior;
134use crate::util::errors::CargoResult;
135use crate::util::indented_lines;
136
137pub const SEE_CHANNELS: &str = "See https://doc.rust-lang.org/book/appendix-07-nightly-rust.html for more information \
138 about Rust release channels.";
139
140pub type AllowFeatures = BTreeSet<String>;
142
143#[derive(
181 Default, Clone, Copy, Debug, Hash, PartialOrd, Ord, Eq, PartialEq, Serialize, Deserialize,
182)]
183pub enum Edition {
184 #[default]
186 Edition2015,
187 Edition2018,
189 Edition2021,
191 Edition2024,
193 EditionFuture,
195}
196
197impl Edition {
198 pub const LATEST_UNSTABLE: Option<Edition> = None;
205 pub const LATEST_STABLE: Edition = Edition::Edition2024;
207 pub const ALL: &'static [Edition] = &[
208 Self::Edition2015,
209 Self::Edition2018,
210 Self::Edition2021,
211 Self::Edition2024,
212 Self::EditionFuture,
213 ];
214 pub const CLI_VALUES: [&'static str; 4] = ["2015", "2018", "2021", "2024"];
222
223 pub(crate) fn first_version(&self) -> Option<semver::Version> {
226 use Edition::*;
227 match self {
228 Edition2015 => None,
229 Edition2018 => Some(semver::Version::new(1, 31, 0)),
230 Edition2021 => Some(semver::Version::new(1, 56, 0)),
231 Edition2024 => Some(semver::Version::new(1, 85, 0)),
232 EditionFuture => None,
233 }
234 }
235
236 pub fn is_stable(&self) -> bool {
238 use Edition::*;
239 match self {
240 Edition2015 => true,
241 Edition2018 => true,
242 Edition2021 => true,
243 Edition2024 => true,
244 EditionFuture => false,
245 }
246 }
247
248 pub fn previous(&self) -> Option<Edition> {
252 use Edition::*;
253 match self {
254 Edition2015 => None,
255 Edition2018 => Some(Edition2015),
256 Edition2021 => Some(Edition2018),
257 Edition2024 => Some(Edition2021),
258 EditionFuture => panic!("future does not have a previous edition"),
259 }
260 }
261
262 pub fn saturating_next(&self) -> Edition {
265 use Edition::*;
266 match self {
268 Edition2015 => Edition2018,
269 Edition2018 => Edition2021,
270 Edition2021 => Edition2024,
271 Edition2024 => Edition2024,
272 EditionFuture => EditionFuture,
273 }
274 }
275
276 pub(crate) fn cmd_edition_arg(&self, cmd: &mut ProcessBuilder) {
279 cmd.arg(format!("--edition={}", self));
280 if !self.is_stable() {
281 cmd.arg("-Z").arg("unstable-options");
282 }
283 }
284
285 pub(crate) fn force_warn_arg(&self, cmd: &mut ProcessBuilder) {
287 use Edition::*;
288 match self {
289 Edition2015 => {}
290 EditionFuture => {
291 cmd.arg("--force-warn=edition_future_compatibility");
292 }
293 e => {
294 cmd.arg(format!("--force-warn=rust-{e}-compatibility"));
301 }
302 }
303 }
304
305 pub(crate) fn supports_idiom_lint(&self) -> bool {
309 use Edition::*;
310 match self {
311 Edition2015 => false,
312 Edition2018 => true,
313 Edition2021 => false,
314 Edition2024 => false,
315 EditionFuture => false,
316 }
317 }
318
319 pub(crate) fn default_resolve_behavior(&self) -> ResolveBehavior {
320 if *self >= Edition::Edition2024 {
321 ResolveBehavior::V3
322 } else if *self >= Edition::Edition2021 {
323 ResolveBehavior::V2
324 } else {
325 ResolveBehavior::V1
326 }
327 }
328}
329
330impl fmt::Display for Edition {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 match *self {
333 Edition::Edition2015 => f.write_str("2015"),
334 Edition::Edition2018 => f.write_str("2018"),
335 Edition::Edition2021 => f.write_str("2021"),
336 Edition::Edition2024 => f.write_str("2024"),
337 Edition::EditionFuture => f.write_str("future"),
338 }
339 }
340}
341
342impl FromStr for Edition {
343 type Err = Error;
344 fn from_str(s: &str) -> Result<Self, Error> {
345 match s {
346 "2015" => Ok(Edition::Edition2015),
347 "2018" => Ok(Edition::Edition2018),
348 "2021" => Ok(Edition::Edition2021),
349 "2024" => Ok(Edition::Edition2024),
350 "future" => Ok(Edition::EditionFuture),
351 s if s.parse().map_or(false, |y: u16| y > 2024 && y < 2050) => bail!(
352 "this version of Cargo is older than the `{}` edition, \
353 and only supports `2015`, `2018`, `2021`, and `2024` editions.",
354 s
355 ),
356 s => bail!(
357 "supported edition values are `2015`, `2018`, `2021`, or `2024`, \
358 but `{}` is unknown",
359 s
360 ),
361 }
362 }
363}
364
365#[derive(Debug, Deserialize)]
367pub enum FixEdition {
368 Start(Edition),
375 End { initial: Edition, next: Edition },
383}
384
385impl FromStr for FixEdition {
386 type Err = anyhow::Error;
387 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
388 if let Some(start) = s.strip_prefix("start=") {
389 Ok(FixEdition::Start(start.parse()?))
390 } else if let Some(end) = s.strip_prefix("end=") {
391 let (initial, next) = end
392 .split_once(',')
393 .ok_or_else(|| anyhow::format_err!("expected `initial,next`"))?;
394 Ok(FixEdition::End {
395 initial: initial.parse()?,
396 next: next.parse()?,
397 })
398 } else {
399 bail!("invalid `-Zfix-edition, expected start= or end=, got `{s}`");
400 }
401 }
402}
403
404#[derive(Debug, PartialEq)]
405enum Status {
406 Stable,
407 Unstable,
408 Removed,
409}
410
411macro_rules! features {
423 (
424 $(
425 $(#[$attr:meta])*
426 ($stab:ident, $feature:ident, $version:expr, $docs:expr),
427 )*
428 ) => (
429 #[derive(Default, Clone, Debug)]
434 pub struct Features {
435 $($feature: bool,)*
436 activated: Vec<String>,
438 nightly_features_allowed: bool,
440 is_local: bool,
442 }
443
444 impl Feature {
445 $(
446 $(#[$attr])*
447 #[doc = concat!("\n\n\nSee <https://doc.rust-lang.org/nightly/cargo/", $docs, ">.")]
448 pub const fn $feature() -> &'static Feature {
449 fn get(features: &Features) -> bool {
450 stab!($stab) == Status::Stable || features.$feature
451 }
452 const FEAT: Feature = Feature {
453 name: stringify!($feature),
454 stability: stab!($stab),
455 version: $version,
456 docs: $docs,
457 get,
458 };
459 &FEAT
460 }
461 )*
462
463 fn is_enabled(&self, features: &Features) -> bool {
465 (self.get)(features)
466 }
467
468 pub(crate) fn name(&self) -> &str {
469 self.name
470 }
471 }
472
473 impl Features {
474 fn status(&mut self, feature: &str) -> Option<(&mut bool, &'static Feature)> {
475 if feature.contains("_") {
476 return None;
477 }
478 let feature = feature.replace("-", "_");
479 $(
480 if feature == stringify!($feature) {
481 return Some((&mut self.$feature, Feature::$feature()));
482 }
483 )*
484 None
485 }
486 }
487 )
488}
489
490macro_rules! stab {
491 (stable) => {
492 Status::Stable
493 };
494 (unstable) => {
495 Status::Unstable
496 };
497 (removed) => {
498 Status::Removed
499 };
500}
501
502features! {
504 (stable, test_dummy_stable, "1.0", ""),
507
508 (unstable, test_dummy_unstable, "", "reference/unstable.html"),
511
512 (stable, alternative_registries, "1.34", "reference/registries.html"),
514
515 (stable, edition, "1.31", "reference/manifest.html#the-edition-field"),
517
518 (stable, rename_dependency, "1.31", "reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml"),
520
521 (removed, publish_lockfile, "1.37", "reference/unstable.html#publish-lockfile"),
523
524 (stable, profile_overrides, "1.41", "reference/profiles.html#overrides"),
526
527 (stable, default_run, "1.37", "reference/manifest.html#the-default-run-field"),
529
530 (unstable, metabuild, "", "reference/unstable.html#metabuild"),
532
533 (unstable, public_dependency, "", "reference/unstable.html#public-dependency"),
535
536 (stable, named_profiles, "1.57", "reference/profiles.html#custom-profiles"),
538
539 (stable, resolver, "1.51", "reference/resolver.html#resolver-versions"),
541
542 (stable, strip, "1.58", "reference/profiles.html#strip-option"),
544
545 (stable, rust_version, "1.56", "reference/manifest.html#the-rust-version-field"),
547
548 (stable, edition2021, "1.56", "reference/manifest.html#the-edition-field"),
550
551 (unstable, per_package_target, "", "reference/unstable.html#per-package-target"),
553
554 (unstable, codegen_backend, "", "reference/unstable.html#codegen-backend"),
556
557 (unstable, different_binary_name, "", "reference/unstable.html#different-binary-name"),
559
560 (unstable, profile_rustflags, "", "reference/unstable.html#profile-rustflags-option"),
562
563 (stable, workspace_inheritance, "1.64", "reference/unstable.html#workspace-inheritance"),
565
566 (stable, edition2024, "1.85", "reference/manifest.html#the-edition-field"),
568
569 (unstable, trim_paths, "", "reference/unstable.html#profile-trim-paths-option"),
571
572 (unstable, open_namespaces, "", "reference/unstable.html#open-namespaces"),
574
575 (unstable, path_bases, "", "reference/unstable.html#path-bases"),
577
578 (unstable, unstable_editions, "", "reference/unstable.html#unstable-editions"),
580
581 (unstable, multiple_build_scripts, "", "reference/unstable.html#multiple-build-scripts"),
583
584 (unstable, panic_immediate_abort, "", "reference/unstable.html#panic-immediate-abort"),
586}
587
588#[derive(Debug)]
590pub struct Feature {
591 name: &'static str,
593 stability: Status,
594 version: &'static str,
596 docs: &'static str,
598 get: fn(&Features) -> bool,
599}
600
601impl Features {
602 pub fn new(
604 features: &[String],
605 gctx: &GlobalContext,
606 warnings: &mut Vec<String>,
607 is_local: bool,
608 ) -> CargoResult<Features> {
609 let mut ret = Features::default();
610 ret.nightly_features_allowed = gctx.nightly_features_allowed;
611 ret.is_local = is_local;
612 for feature in features {
613 ret.add(feature, gctx, warnings)?;
614 ret.activated.push(feature.to_string());
615 }
616 Ok(ret)
617 }
618
619 fn add(
620 &mut self,
621 feature_name: &str,
622 gctx: &GlobalContext,
623 warnings: &mut Vec<String>,
624 ) -> CargoResult<()> {
625 let nightly_features_allowed = self.nightly_features_allowed;
626 let Some((slot, feature)) = self.status(feature_name) else {
627 let mut msg = format!("unknown Cargo.toml feature `{feature_name}`\n\n");
628 let mut append_see_docs = true;
629
630 if feature_name.contains('_') {
631 let _ = writeln!(msg, "Feature names must use '-' instead of '_'.");
632 append_see_docs = false;
633 } else {
634 let underscore_name = feature_name.replace('-', "_");
635 if CliUnstable::help()
636 .iter()
637 .any(|(option, _)| *option == underscore_name)
638 {
639 let _ = writeln!(
640 msg,
641 "This feature can be enabled via -Z{feature_name} or the `[unstable]` section in config.toml."
642 );
643 }
644 }
645
646 if append_see_docs {
647 let _ = writeln!(
648 msg,
649 "See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html for more information."
650 );
651 }
652 bail!(msg)
653 };
654
655 if *slot {
656 bail!(
657 "the cargo feature `{}` has already been activated",
658 feature_name
659 );
660 }
661
662 let see_docs = || {
663 format!(
664 "See {} for more information about using this feature.",
665 cargo_docs_link(feature.docs)
666 )
667 };
668
669 match feature.stability {
670 Status::Stable => {
671 let warning = format!(
672 "the cargo feature `{}` has been stabilized in the {} \
673 release and is no longer necessary to be listed in the \
674 manifest\n {}",
675 feature_name,
676 feature.version,
677 see_docs()
678 );
679 warnings.push(warning);
680 }
681 Status::Unstable if !nightly_features_allowed => bail!(
682 "the cargo feature `{}` requires a nightly version of \
683 Cargo, but this is the `{}` channel\n\
684 {}\n{}",
685 feature_name,
686 channel(),
687 SEE_CHANNELS,
688 see_docs()
689 ),
690 Status::Unstable => {
691 if let Some(allow) = &gctx.cli_unstable().allow_features {
692 if !allow.contains(feature_name) {
693 bail!(
694 "the feature `{}` is not in the list of allowed features: [{}]",
695 feature_name,
696 itertools::join(allow, ", "),
697 );
698 }
699 }
700 }
701 Status::Removed => {
702 let mut msg = format!(
703 "the cargo feature `{}` has been removed in the {} release\n\n",
704 feature_name, feature.version
705 );
706 if self.is_local {
707 let _ = writeln!(
708 msg,
709 "Remove the feature from Cargo.toml to remove this error."
710 );
711 } else {
712 let _ = writeln!(
713 msg,
714 "This package cannot be used with this version of Cargo, \
715 as the unstable feature `{}` is no longer supported.",
716 feature_name
717 );
718 }
719 let _ = writeln!(msg, "{}", see_docs());
720 bail!(msg);
721 }
722 }
723
724 *slot = true;
725
726 Ok(())
727 }
728
729 pub fn activated(&self) -> &[String] {
731 &self.activated
732 }
733
734 pub fn require(&self, feature: &Feature) -> CargoResult<()> {
736 if feature.is_enabled(self) {
737 return Ok(());
738 }
739 let feature_name = feature.name.replace("_", "-");
740 let mut msg = format!(
741 "feature `{}` is required\n\
742 \n\
743 The package requires the Cargo feature called `{}`, but \
744 that feature is not stabilized in this version of Cargo ({}).\n\
745 ",
746 feature_name,
747 feature_name,
748 crate::version(),
749 );
750
751 if self.nightly_features_allowed {
752 if self.is_local {
753 let _ = writeln!(
754 msg,
755 "Consider adding `cargo-features = [\"{}\"]` \
756 to the top of Cargo.toml (above the [package] table) \
757 to tell Cargo you are opting in to use this unstable feature.",
758 feature_name
759 );
760 } else {
761 let _ = writeln!(msg, "Consider trying a more recent nightly release.");
762 }
763 } else {
764 let _ = writeln!(
765 msg,
766 "Consider trying a newer version of Cargo \
767 (this may require the nightly release)."
768 );
769 }
770 let _ = writeln!(
771 msg,
772 "See https://doc.rust-lang.org/nightly/cargo/{} for more information \
773 about the status of this feature.",
774 feature.docs
775 );
776
777 bail!("{}", msg);
778 }
779
780 pub fn is_enabled(&self, feature: &Feature) -> bool {
782 feature.is_enabled(self)
783 }
784}
785
786macro_rules! unstable_cli_options {
790 (
791 $(
792 $(#[$meta:meta])?
793 $element: ident: $ty: ty$( = ($help:literal))?,
794 )*
795 ) => {
796 #[derive(Default, Debug, Deserialize)]
802 #[serde(default, rename_all = "kebab-case")]
803 pub struct CliUnstable {
804 $(
805 $(#[doc = $help])?
806 $(#[$meta])?
807 pub $element: $ty
808 ),*
809 }
810 impl CliUnstable {
811 pub fn help() -> Vec<(&'static str, Option<&'static str>)> {
813 let fields = vec![$((stringify!($element), None$(.or(Some($help)))?)),*];
814 fields
815 }
816 }
817
818 #[cfg(test)]
819 mod test {
820 #[test]
821 fn ensure_sorted() {
822 let location = std::panic::Location::caller();
824 println!(
825 "\nTo fix this test, sort the features inside the macro at {}:{}\n",
826 location.file(),
827 location.line()
828 );
829 let mut expected = vec![$(stringify!($element)),*];
830 expected[2..].sort();
831 let expected = format!("{:#?}", expected);
832 let actual = format!("{:#?}", vec![$(stringify!($element)),*]);
833 snapbox::assert_data_eq!(actual, expected);
834 }
835 }
836 }
837}
838
839unstable_cli_options!(
840 allow_features: Option<AllowFeatures> = ("Allow *only* the listed unstable features"),
842 print_im_a_teapot: bool,
843
844 advanced_env: bool,
847 asymmetric_token: bool = ("Allows authenticating with asymmetric tokens"),
848 avoid_dev_deps: bool = ("Avoid installing dev-dependencies if possible"),
849 binary_dep_depinfo: bool = ("Track changes to dependency artifacts"),
850 bindeps: bool = ("Allow Cargo packages to depend on bin, cdylib, and staticlib crates, and use the artifacts built by those crates"),
851 build_analysis: bool = ("Record and persist build metrics across runs, with commands to query past builds."),
852 build_dir_new_layout: bool = ("Use the new build-dir filesystem layout"),
853 #[serde(deserialize_with = "deserialize_comma_separated_list")]
854 build_std: Option<Vec<String>> = ("Enable Cargo to compile the standard library itself as part of a crate graph compilation"),
855 #[serde(deserialize_with = "deserialize_comma_separated_list")]
856 build_std_features: Option<Vec<String>> = ("Configure features enabled for the standard library itself when building the standard library"),
857 cargo_lints: bool = ("Enable the `[lints.cargo]` table"),
858 checksum_freshness: bool = ("Use a checksum to determine if output is fresh rather than filesystem mtime"),
859 codegen_backend: bool = ("Enable the `codegen-backend` option in profiles in .cargo/config.toml file"),
860 direct_minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum (direct dependencies only)"),
861 dual_proc_macros: bool = ("Build proc-macros for both the host and the target"),
862 feature_unification: bool = ("Enable new feature unification modes in workspaces"),
863 features: Option<Vec<String>>,
864 fine_grain_locking: bool = ("Use fine grain locking instead of locking the entire build cache"),
865 fix_edition: Option<FixEdition> = ("Permanently unstable edition migration helper"),
866 gc: bool = ("Track cache usage and \"garbage collect\" unused files"),
867 #[serde(deserialize_with = "deserialize_git_features")]
868 git: Option<GitFeatures> = ("Enable support for shallow git fetch operations"),
869 #[serde(deserialize_with = "deserialize_gitoxide_features")]
870 gitoxide: Option<GitoxideFeatures> = ("Use gitoxide for the given git interactions, or all of them if no argument is given"),
871 host_config: bool = ("Enable the `[host]` section in the .cargo/config.toml file"),
872 minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum"),
873 msrv_policy: bool = ("Enable rust-version aware policy within cargo"),
874 mtime_on_use: bool = ("Configure Cargo to update the mtime of used files"),
875 next_lockfile_bump: bool,
876 no_embed_metadata: bool = ("Avoid embedding metadata in library artifacts"),
877 no_index_update: bool = ("Do not update the registry index even if the cache is outdated"),
878 panic_abort_tests: bool = ("Enable support to run tests with -Cpanic=abort"),
879 panic_immediate_abort: bool = ("Enable setting `panic = \"immediate-abort\"` in profiles"),
880 profile_hint_mostly_unused: bool = ("Enable the `hint-mostly-unused` setting in profiles to mark a crate as mostly unused."),
881 profile_rustflags: bool = ("Enable the `rustflags` option in profiles in .cargo/config.toml file"),
882 public_dependency: bool = ("Respect a dependency's `public` field in Cargo.toml to control public/private dependencies"),
883 publish_timeout: bool = ("Enable the `publish.timeout` key in .cargo/config.toml file"),
884 root_dir: Option<PathBuf> = ("Set the root directory relative to which paths are printed (defaults to workspace root)"),
885 rustc_unicode: bool = ("Enable `rustc`'s unicode error format in Cargo's error messages"),
886 rustdoc_depinfo: bool = ("Use dep-info files in rustdoc rebuild detection"),
887 rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"),
888 rustdoc_mergeable_info: bool = ("Use rustdoc mergeable cross-crate-info files"),
889 rustdoc_scrape_examples: bool = ("Allows Rustdoc to scrape code examples from reverse-dependencies"),
890 sbom: bool = ("Enable the `sbom` option in build config in .cargo/config.toml file"),
891 script: bool = ("Enable support for single-file, `.rs` packages"),
892 section_timings: bool = ("Enable support for extended compilation sections in --timings output"),
893 separate_nightlies: bool,
894 skip_rustdoc_fingerprint: bool,
895 target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
896 trim_paths: bool = ("Enable the `trim-paths` option in profiles"),
897 unstable_options: bool = ("Allow the usage of unstable options"),
898 warnings: bool = ("Allow use of the build.warnings config key"),
899);
900
901const STABILIZED_COMPILE_PROGRESS: &str = "The progress bar is now always \
902 enabled when used on an interactive console.\n\
903 See https://doc.rust-lang.org/cargo/reference/config.html#termprogresswhen \
904 for information on controlling the progress bar.";
905
906const STABILIZED_OFFLINE: &str = "Offline mode is now available via the \
907 --offline CLI option";
908
909const STABILIZED_CACHE_MESSAGES: &str = "Message caching is now always enabled.";
910
911const STABILIZED_INSTALL_UPGRADE: &str = "Packages are now always upgraded if \
912 they appear out of date.\n\
913 See https://doc.rust-lang.org/cargo/commands/cargo-install.html for more \
914 information on how upgrading works.";
915
916const STABILIZED_CONFIG_PROFILE: &str = "See \
917 https://doc.rust-lang.org/cargo/reference/config.html#profile for more \
918 information about specifying profiles in config.";
919
920const STABILIZED_CRATE_VERSIONS: &str = "The crate version is now \
921 automatically added to the documentation.";
922
923const STABILIZED_PACKAGE_FEATURES: &str = "Enhanced feature flag behavior is now \
924 available in virtual workspaces, and `member/feature-name` syntax is also \
925 always available. Other extensions require setting `resolver = \"2\"` in \
926 Cargo.toml.\n\
927 See https://doc.rust-lang.org/nightly/cargo/reference/features.html#resolver-version-2-command-line-flags \
928 for more information.";
929
930const STABILIZED_FEATURES: &str = "The new feature resolver is now available \
931 by specifying `resolver = \"2\"` in Cargo.toml.\n\
932 See https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2 \
933 for more information.";
934
935const STABILIZED_EXTRA_LINK_ARG: &str = "Additional linker arguments are now \
936 supported without passing this flag.";
937
938const STABILIZED_CONFIGURABLE_ENV: &str = "The [env] section is now always enabled.";
939
940const STABILIZED_PATCH_IN_CONFIG: &str = "The patch-in-config feature is now always enabled.";
941
942const STABILIZED_NAMED_PROFILES: &str = "The named-profiles feature is now always enabled.\n\
943 See https://doc.rust-lang.org/nightly/cargo/reference/profiles.html#custom-profiles \
944 for more information";
945
946const STABILIZED_DOCTEST_IN_WORKSPACE: &str =
947 "The doctest-in-workspace feature is now always enabled.";
948
949const STABILIZED_FUTURE_INCOMPAT_REPORT: &str =
950 "The future-incompat-report feature is now always enabled.";
951
952const STABILIZED_WEAK_DEP_FEATURES: &str = "Weak dependency features are now always available.";
953
954const STABILISED_NAMESPACED_FEATURES: &str = "Namespaced features are now always available.";
955
956const STABILIZED_TIMINGS: &str = "The -Ztimings option has been stabilized as --timings.";
957
958const STABILISED_MULTITARGET: &str = "Multiple `--target` options are now always available.";
959
960const STABILIZED_TERMINAL_WIDTH: &str =
961 "The -Zterminal-width option is now always enabled for terminal output.";
962
963const STABILISED_SPARSE_REGISTRY: &str = "The sparse protocol is now the default for crates.io";
964
965const STABILIZED_CREDENTIAL_PROCESS: &str =
966 "Authentication with a credential provider is always available.";
967
968const STABILIZED_REGISTRY_AUTH: &str =
969 "Authenticated registries are available if a credential provider is configured.";
970
971const STABILIZED_LINTS: &str = "The `[lints]` table is now always available.";
972
973const STABILIZED_CHECK_CFG: &str =
974 "Compile-time checking of conditional (a.k.a. `-Zcheck-cfg`) is now always enabled.";
975
976const STABILIZED_DOCTEST_XCOMPILE: &str = "Doctest cross-compiling is now always enabled.";
977
978const STABILIZED_PACKAGE_WORKSPACE: &str =
979 "Workspace packaging and publishing (a.k.a. `-Zpackage-workspace`) is now always enabled.";
980
981const STABILIZED_BUILD_DIR: &str = "build.build-dir is now always enabled.";
982
983const STABILIZED_CONFIG_INCLUDE: &str = "The `include` config key is now always available";
984
985fn deserialize_comma_separated_list<'de, D>(
986 deserializer: D,
987) -> Result<Option<Vec<String>>, D::Error>
988where
989 D: serde::Deserializer<'de>,
990{
991 let Some(list) = <Option<Vec<String>>>::deserialize(deserializer)? else {
992 return Ok(None);
993 };
994 let v = list
995 .iter()
996 .flat_map(|s| s.split(','))
997 .filter(|s| !s.is_empty())
998 .map(String::from)
999 .collect();
1000 Ok(Some(v))
1001}
1002
1003#[derive(Debug, Copy, Clone, Default, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
1004#[serde(default)]
1005pub struct GitFeatures {
1006 pub shallow_index: bool,
1008 pub shallow_deps: bool,
1010}
1011
1012impl GitFeatures {
1013 pub fn all() -> Self {
1014 GitFeatures {
1015 shallow_index: true,
1016 shallow_deps: true,
1017 }
1018 }
1019
1020 fn expecting() -> String {
1021 let fields = ["`shallow-index`", "`shallow-deps`"];
1022 format!(
1023 "unstable 'git' only takes {} as valid inputs",
1024 fields.join(" and ")
1025 )
1026 }
1027}
1028
1029fn deserialize_git_features<'de, D>(deserializer: D) -> Result<Option<GitFeatures>, D::Error>
1030where
1031 D: serde::de::Deserializer<'de>,
1032{
1033 struct GitFeaturesVisitor;
1034
1035 impl<'de> serde::de::Visitor<'de> for GitFeaturesVisitor {
1036 type Value = Option<GitFeatures>;
1037
1038 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1039 formatter.write_str(&GitFeatures::expecting())
1040 }
1041
1042 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1043 where
1044 E: serde::de::Error,
1045 {
1046 if v {
1047 Ok(Some(GitFeatures::all()))
1048 } else {
1049 Ok(None)
1050 }
1051 }
1052
1053 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1054 where
1055 E: serde::de::Error,
1056 {
1057 Ok(parse_git(s.split(",")).map_err(serde::de::Error::custom)?)
1058 }
1059
1060 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1061 where
1062 D: serde::de::Deserializer<'de>,
1063 {
1064 let git = GitFeatures::deserialize(deserializer)?;
1065 Ok(Some(git))
1066 }
1067
1068 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
1069 where
1070 V: serde::de::MapAccess<'de>,
1071 {
1072 let mvd = serde::de::value::MapAccessDeserializer::new(map);
1073 Ok(Some(GitFeatures::deserialize(mvd)?))
1074 }
1075 }
1076
1077 deserializer.deserialize_any(GitFeaturesVisitor)
1078}
1079
1080fn parse_git(it: impl Iterator<Item = impl AsRef<str>>) -> CargoResult<Option<GitFeatures>> {
1081 let mut out = GitFeatures::default();
1082 let GitFeatures {
1083 shallow_index,
1084 shallow_deps,
1085 } = &mut out;
1086
1087 for e in it {
1088 match e.as_ref() {
1089 "shallow-index" => *shallow_index = true,
1090 "shallow-deps" => *shallow_deps = true,
1091 _ => {
1092 bail!(GitFeatures::expecting())
1093 }
1094 }
1095 }
1096 Ok(Some(out))
1097}
1098
1099#[derive(Debug, Copy, Clone, Default, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
1100#[serde(default)]
1101pub struct GitoxideFeatures {
1102 pub fetch: bool,
1104 pub checkout: bool,
1107 pub internal_use_git2: bool,
1111}
1112
1113impl GitoxideFeatures {
1114 pub fn all() -> Self {
1115 GitoxideFeatures {
1116 fetch: true,
1117 checkout: true,
1118 internal_use_git2: false,
1119 }
1120 }
1121
1122 fn safe() -> Self {
1125 GitoxideFeatures {
1126 fetch: true,
1127 checkout: true,
1128 internal_use_git2: false,
1129 }
1130 }
1131
1132 fn expecting() -> String {
1133 let fields = ["`fetch`", "`checkout`", "`internal-use-git2`"];
1134 format!(
1135 "unstable 'gitoxide' only takes {} as valid inputs, for shallow fetches see `-Zgit=shallow-index,shallow-deps`",
1136 fields.join(" and ")
1137 )
1138 }
1139}
1140
1141fn deserialize_gitoxide_features<'de, D>(
1142 deserializer: D,
1143) -> Result<Option<GitoxideFeatures>, D::Error>
1144where
1145 D: serde::de::Deserializer<'de>,
1146{
1147 struct GitoxideFeaturesVisitor;
1148
1149 impl<'de> serde::de::Visitor<'de> for GitoxideFeaturesVisitor {
1150 type Value = Option<GitoxideFeatures>;
1151
1152 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1153 formatter.write_str(&GitoxideFeatures::expecting())
1154 }
1155
1156 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
1157 where
1158 E: serde::de::Error,
1159 {
1160 Ok(parse_gitoxide(s.split(",")).map_err(serde::de::Error::custom)?)
1161 }
1162
1163 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1164 where
1165 E: serde::de::Error,
1166 {
1167 if v {
1168 Ok(Some(GitoxideFeatures::all()))
1169 } else {
1170 Ok(None)
1171 }
1172 }
1173
1174 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1175 where
1176 D: serde::de::Deserializer<'de>,
1177 {
1178 let gitoxide = GitoxideFeatures::deserialize(deserializer)?;
1179 Ok(Some(gitoxide))
1180 }
1181
1182 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
1183 where
1184 V: serde::de::MapAccess<'de>,
1185 {
1186 let mvd = serde::de::value::MapAccessDeserializer::new(map);
1187 Ok(Some(GitoxideFeatures::deserialize(mvd)?))
1188 }
1189 }
1190
1191 deserializer.deserialize_any(GitoxideFeaturesVisitor)
1192}
1193
1194fn parse_gitoxide(
1195 it: impl Iterator<Item = impl AsRef<str>>,
1196) -> CargoResult<Option<GitoxideFeatures>> {
1197 let mut out = GitoxideFeatures::default();
1198 let GitoxideFeatures {
1199 fetch,
1200 checkout,
1201 internal_use_git2,
1202 } = &mut out;
1203
1204 for e in it {
1205 match e.as_ref() {
1206 "fetch" => *fetch = true,
1207 "checkout" => *checkout = true,
1208 "internal-use-git2" => *internal_use_git2 = true,
1209 _ => {
1210 bail!(GitoxideFeatures::expecting())
1211 }
1212 }
1213 }
1214 Ok(Some(out))
1215}
1216
1217impl CliUnstable {
1218 pub fn parse(
1221 &mut self,
1222 flags: &[String],
1223 nightly_features_allowed: bool,
1224 ) -> CargoResult<Vec<String>> {
1225 if !flags.is_empty() && !nightly_features_allowed {
1226 bail!(
1227 "the `-Z` flag is only accepted on the nightly channel of Cargo, \
1228 but this is the `{}` channel\n\
1229 {}",
1230 channel(),
1231 SEE_CHANNELS
1232 );
1233 }
1234 let mut warnings = Vec::new();
1235 for flag in flags {
1238 if flag.starts_with("allow-features=") {
1239 self.add(flag, &mut warnings)?;
1240 }
1241 }
1242 for flag in flags {
1243 self.add(flag, &mut warnings)?;
1244 }
1245
1246 if self.gitoxide.is_none() && cargo_use_gitoxide_instead_of_git2() {
1247 self.gitoxide = GitoxideFeatures::safe().into();
1248 }
1249
1250 self.implicitly_enable_features_if_needed();
1251
1252 Ok(warnings)
1253 }
1254
1255 fn add(&mut self, flag: &str, warnings: &mut Vec<String>) -> CargoResult<()> {
1256 let mut parts = flag.splitn(2, '=');
1257 let k = parts.next().unwrap();
1258 let v = parts.next();
1259
1260 fn parse_bool(key: &str, value: Option<&str>) -> CargoResult<bool> {
1261 match value {
1262 None | Some("yes") => Ok(true),
1263 Some("no") => Ok(false),
1264 Some(s) => bail!("flag -Z{} expected `no` or `yes`, found: `{}`", key, s),
1265 }
1266 }
1267
1268 fn parse_list(value: Option<&str>) -> Vec<String> {
1270 match value {
1271 None => Vec::new(),
1272 Some("") => Vec::new(),
1273 Some(v) => v.split(',').map(|s| s.to_string()).collect(),
1274 }
1275 }
1276
1277 fn parse_empty(key: &str, value: Option<&str>) -> CargoResult<bool> {
1279 if let Some(v) = value {
1280 bail!("flag -Z{} does not take a value, found: `{}`", key, v);
1281 }
1282 Ok(true)
1283 }
1284
1285 let mut stabilized_warn = |key: &str, version: &str, message: &str| {
1286 warnings.push(format!(
1287 "flag `-Z {}` has been stabilized in the {} release, \
1288 and is no longer necessary\n{}",
1289 key,
1290 version,
1291 indented_lines(message)
1292 ));
1293 };
1294
1295 let stabilized_err = |key: &str, version: &str, message: &str| {
1297 Err(anyhow::format_err!(
1298 "flag `-Z {}` has been stabilized in the {} release\n{}",
1299 key,
1300 version,
1301 indented_lines(message)
1302 ))
1303 };
1304
1305 if let Some(allowed) = &self.allow_features {
1306 if k != "allow-features" && !allowed.contains(k) {
1307 bail!(
1308 "the feature `{}` is not in the list of allowed features: [{}]",
1309 k,
1310 itertools::join(allowed, ", ")
1311 );
1312 }
1313 }
1314
1315 match k {
1316 "allow-features" => self.allow_features = Some(parse_list(v).into_iter().collect()),
1319 "print-im-a-teapot" => self.print_im_a_teapot = parse_bool(k, v)?,
1320
1321 "compile-progress" => stabilized_warn(k, "1.30", STABILIZED_COMPILE_PROGRESS),
1324 "offline" => stabilized_err(k, "1.36", STABILIZED_OFFLINE)?,
1325 "cache-messages" => stabilized_warn(k, "1.40", STABILIZED_CACHE_MESSAGES),
1326 "install-upgrade" => stabilized_warn(k, "1.41", STABILIZED_INSTALL_UPGRADE),
1327 "config-profile" => stabilized_warn(k, "1.43", STABILIZED_CONFIG_PROFILE),
1328 "crate-versions" => stabilized_warn(k, "1.47", STABILIZED_CRATE_VERSIONS),
1329 "features" => {
1330 let feats = parse_list(v);
1338 let stab_is_not_empty = feats.iter().any(|feat| {
1339 matches!(
1340 feat.as_str(),
1341 "build_dep" | "host_dep" | "dev_dep" | "itarget" | "all"
1342 )
1343 });
1344 if stab_is_not_empty || feats.is_empty() {
1345 stabilized_warn(k, "1.51", STABILIZED_FEATURES);
1347 }
1348 self.features = Some(feats);
1349 }
1350 "package-features" => stabilized_warn(k, "1.51", STABILIZED_PACKAGE_FEATURES),
1351 "configurable-env" => stabilized_warn(k, "1.56", STABILIZED_CONFIGURABLE_ENV),
1352 "extra-link-arg" => stabilized_warn(k, "1.56", STABILIZED_EXTRA_LINK_ARG),
1353 "patch-in-config" => stabilized_warn(k, "1.56", STABILIZED_PATCH_IN_CONFIG),
1354 "named-profiles" => stabilized_warn(k, "1.57", STABILIZED_NAMED_PROFILES),
1355 "future-incompat-report" => {
1356 stabilized_warn(k, "1.59.0", STABILIZED_FUTURE_INCOMPAT_REPORT)
1357 }
1358 "namespaced-features" => stabilized_warn(k, "1.60", STABILISED_NAMESPACED_FEATURES),
1359 "timings" => stabilized_warn(k, "1.60", STABILIZED_TIMINGS),
1360 "weak-dep-features" => stabilized_warn(k, "1.60", STABILIZED_WEAK_DEP_FEATURES),
1361 "multitarget" => stabilized_warn(k, "1.64", STABILISED_MULTITARGET),
1362 "sparse-registry" => stabilized_warn(k, "1.68", STABILISED_SPARSE_REGISTRY),
1363 "terminal-width" => stabilized_warn(k, "1.68", STABILIZED_TERMINAL_WIDTH),
1364 "doctest-in-workspace" => stabilized_warn(k, "1.72", STABILIZED_DOCTEST_IN_WORKSPACE),
1365 "credential-process" => stabilized_warn(k, "1.74", STABILIZED_CREDENTIAL_PROCESS),
1366 "lints" => stabilized_warn(k, "1.74", STABILIZED_LINTS),
1367 "registry-auth" => stabilized_warn(k, "1.74", STABILIZED_REGISTRY_AUTH),
1368 "check-cfg" => stabilized_warn(k, "1.80", STABILIZED_CHECK_CFG),
1369 "doctest-xcompile" => stabilized_warn(k, "1.89", STABILIZED_DOCTEST_XCOMPILE),
1370 "package-workspace" => stabilized_warn(k, "1.89", STABILIZED_PACKAGE_WORKSPACE),
1371 "build-dir" => stabilized_warn(k, "1.91", STABILIZED_BUILD_DIR),
1372 "config-include" => stabilized_warn(k, "1.93", STABILIZED_CONFIG_INCLUDE),
1373
1374 "advanced-env" => self.advanced_env = parse_empty(k, v)?,
1377 "asymmetric-token" => self.asymmetric_token = parse_empty(k, v)?,
1378 "avoid-dev-deps" => self.avoid_dev_deps = parse_empty(k, v)?,
1379 "binary-dep-depinfo" => self.binary_dep_depinfo = parse_empty(k, v)?,
1380 "bindeps" => self.bindeps = parse_empty(k, v)?,
1381 "build-analysis" => self.build_analysis = parse_empty(k, v)?,
1382 "build-dir-new-layout" => self.build_dir_new_layout = parse_empty(k, v)?,
1383 "build-std" => self.build_std = Some(parse_list(v)),
1384 "build-std-features" => self.build_std_features = Some(parse_list(v)),
1385 "cargo-lints" => self.cargo_lints = parse_empty(k, v)?,
1386 "codegen-backend" => self.codegen_backend = parse_empty(k, v)?,
1387 "direct-minimal-versions" => self.direct_minimal_versions = parse_empty(k, v)?,
1388 "dual-proc-macros" => self.dual_proc_macros = parse_empty(k, v)?,
1389 "feature-unification" => self.feature_unification = parse_empty(k, v)?,
1390 "fine-grain-locking" => self.fine_grain_locking = parse_empty(k, v)?,
1391 "fix-edition" => {
1392 let fe = v
1393 .ok_or_else(|| anyhow::anyhow!("-Zfix-edition expected a value"))?
1394 .parse()?;
1395 self.fix_edition = Some(fe);
1396 }
1397 "gc" => self.gc = parse_empty(k, v)?,
1398 "git" => {
1399 self.git =
1400 v.map_or_else(|| Ok(Some(GitFeatures::all())), |v| parse_git(v.split(',')))?
1401 }
1402 "gitoxide" => {
1403 self.gitoxide = v.map_or_else(
1404 || Ok(Some(GitoxideFeatures::all())),
1405 |v| parse_gitoxide(v.split(',')),
1406 )?
1407 }
1408 "host-config" => self.host_config = parse_empty(k, v)?,
1409 "next-lockfile-bump" => self.next_lockfile_bump = parse_empty(k, v)?,
1410 "minimal-versions" => self.minimal_versions = parse_empty(k, v)?,
1411 "msrv-policy" => self.msrv_policy = parse_empty(k, v)?,
1412 "mtime-on-use" => self.mtime_on_use = parse_empty(k, v)?,
1414 "no-embed-metadata" => self.no_embed_metadata = parse_empty(k, v)?,
1415 "no-index-update" => self.no_index_update = parse_empty(k, v)?,
1416 "panic-abort-tests" => self.panic_abort_tests = parse_empty(k, v)?,
1417 "public-dependency" => self.public_dependency = parse_empty(k, v)?,
1418 "profile-hint-mostly-unused" => self.profile_hint_mostly_unused = parse_empty(k, v)?,
1419 "profile-rustflags" => self.profile_rustflags = parse_empty(k, v)?,
1420 "trim-paths" => self.trim_paths = parse_empty(k, v)?,
1421 "publish-timeout" => self.publish_timeout = parse_empty(k, v)?,
1422 "root-dir" => self.root_dir = v.map(|v| v.into()),
1423 "rustc-unicode" => self.rustc_unicode = parse_empty(k, v)?,
1424 "rustdoc-depinfo" => self.rustdoc_depinfo = parse_empty(k, v)?,
1425 "rustdoc-map" => self.rustdoc_map = parse_empty(k, v)?,
1426 "rustdoc-mergeable-info" => self.rustdoc_mergeable_info = parse_empty(k, v)?,
1427 "rustdoc-scrape-examples" => self.rustdoc_scrape_examples = parse_empty(k, v)?,
1428 "sbom" => self.sbom = parse_empty(k, v)?,
1429 "section-timings" => self.section_timings = parse_empty(k, v)?,
1430 "separate-nightlies" => self.separate_nightlies = parse_empty(k, v)?,
1431 "checksum-freshness" => self.checksum_freshness = parse_empty(k, v)?,
1432 "skip-rustdoc-fingerprint" => self.skip_rustdoc_fingerprint = parse_empty(k, v)?,
1433 "script" => self.script = parse_empty(k, v)?,
1434 "target-applies-to-host" => self.target_applies_to_host = parse_empty(k, v)?,
1435 "panic-immediate-abort" => self.panic_immediate_abort = parse_empty(k, v)?,
1436 "unstable-options" => self.unstable_options = parse_empty(k, v)?,
1437 "warnings" => self.warnings = parse_empty(k, v)?,
1438 _ => bail!(
1439 "\
1440 unknown `-Z` flag specified: {k}\n\n\
1441 For available unstable features, see \
1442 https://doc.rust-lang.org/nightly/cargo/reference/unstable.html\n\
1443 If you intended to use an unstable rustc feature, try setting `RUSTFLAGS=\"-Z{k}\"`"
1444 ),
1445 }
1446
1447 Ok(())
1448 }
1449
1450 pub fn fail_if_stable_opt(&self, flag: &str, issue: u32) -> CargoResult<()> {
1453 self.fail_if_stable_opt_custom_z(flag, issue, "unstable-options", self.unstable_options)
1454 }
1455
1456 pub fn fail_if_stable_opt_custom_z(
1457 &self,
1458 flag: &str,
1459 issue: u32,
1460 z_name: &str,
1461 enabled: bool,
1462 ) -> CargoResult<()> {
1463 if !enabled {
1464 let see = format!(
1465 "See https://github.com/rust-lang/cargo/issues/{issue} for more \
1466 information about the `{flag}` flag."
1467 );
1468 let channel = channel();
1470 if channel == "nightly" || channel == "dev" {
1471 bail!(
1472 "the `{flag}` flag is unstable, pass `-Z {z_name}` to enable it\n\
1473 {see}"
1474 );
1475 } else {
1476 bail!(
1477 "the `{flag}` flag is unstable, and only available on the nightly channel \
1478 of Cargo, but this is the `{channel}` channel\n\
1479 {SEE_CHANNELS}\n\
1480 {see}"
1481 );
1482 }
1483 }
1484 Ok(())
1485 }
1486
1487 pub fn fail_if_stable_command(
1490 &self,
1491 gctx: &GlobalContext,
1492 command: &str,
1493 issue: u32,
1494 z_name: &str,
1495 enabled: bool,
1496 ) -> CargoResult<()> {
1497 if enabled {
1498 return Ok(());
1499 }
1500 let see = format!(
1501 "See https://github.com/rust-lang/cargo/issues/{} for more \
1502 information about the `cargo {}` command.",
1503 issue, command
1504 );
1505 if gctx.nightly_features_allowed {
1506 bail!(
1507 "the `cargo {command}` command is unstable, pass `-Z {z_name}` \
1508 to enable it\n\
1509 {see}",
1510 );
1511 } else {
1512 bail!(
1513 "the `cargo {}` command is unstable, and only available on the \
1514 nightly channel of Cargo, but this is the `{}` channel\n\
1515 {}\n\
1516 {}",
1517 command,
1518 channel(),
1519 SEE_CHANNELS,
1520 see
1521 );
1522 }
1523 }
1524
1525 fn implicitly_enable_features_if_needed(&mut self) {
1526 if self.fine_grain_locking && !self.build_dir_new_layout {
1527 debug!("-Zbuild-dir-new-layout implicitly enabled by -Zfine-grain-locking");
1528 self.build_dir_new_layout = true;
1529 }
1530 }
1531}
1532
1533pub fn channel() -> String {
1535 #[allow(clippy::disallowed_methods)]
1537 if let Ok(override_channel) = env::var("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS") {
1538 return override_channel;
1539 }
1540 #[allow(clippy::disallowed_methods)]
1544 if let Ok(staging) = env::var("RUSTC_BOOTSTRAP") {
1545 if staging == "1" {
1546 return "dev".to_string();
1547 }
1548 }
1549 crate::version()
1550 .release_channel
1551 .unwrap_or_else(|| String::from("dev"))
1552}
1553
1554#[allow(clippy::disallowed_methods)]
1559fn cargo_use_gitoxide_instead_of_git2() -> bool {
1560 std::env::var_os("__CARGO_USE_GITOXIDE_INSTEAD_OF_GIT2").map_or(false, |value| value == "1")
1561}
1562
1563pub fn cargo_docs_link(path: &str) -> String {
1566 let url_channel = match channel().as_str() {
1567 "dev" | "nightly" => "nightly/",
1568 "beta" => "beta/",
1569 _ => "",
1570 };
1571 format!("https://doc.rust-lang.org/{url_channel}cargo/{path}")
1572}