Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(unstable): doc comments for items and fields #13274

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/bin/cargo/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use super::commands;
use super::list_commands;
use crate::command_prelude::*;
use crate::util::is_rustup;
use cargo::core::features::HIDDEN;
use cargo::util::style;

pub fn main(config: &mut LazyConfig) -> CliResult {
Expand Down Expand Up @@ -63,15 +62,16 @@ pub fn main(config: &mut LazyConfig) -> CliResult {
let options = CliUnstable::help();
let max_length = options
.iter()
.filter(|(_, help)| *help != HIDDEN)
.filter(|(_, help)| help.is_some())
.map(|(option_name, _)| option_name.len())
.max()
.unwrap_or(0);
let z_flags = options
.iter()
.filter(|(_, help)| *help != HIDDEN)
.filter(|(_, help)| help.is_some())
.map(|(opt, help)| {
let opt = opt.replace("_", "-");
let help = help.unwrap();
format!(" {literal}-Z {opt:<max_length$}{reset} {help}")
})
.join("\n");
Expand Down
132 changes: 81 additions & 51 deletions src/cargo/core/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
//! not yet been designed, or for more complex features that affect multiple
//! parts of Cargo should use a new `-Z` flag.
//!
//! See below for more details.
//!
//! When adding new tests for your feature, usually the tests should go into a
//! new module of the testsuite. See
//! <https://doc.crates.io/contrib/tests/writing.html> for more information on
Expand Down Expand Up @@ -63,8 +61,8 @@
//!
//! The steps to add a new `-Z` option are:
//!
//! 1. Add the option to the [`CliUnstable`] struct below. Flags can take an
//! optional value if you want.
//! 1. Add the option to the [`CliUnstable`] struct in the macro invocation of
//! [`unstable_cli_options!`]. Flags can take an optional value if you want.
//! 2. Update the [`CliUnstable::add`] function to parse the flag.
//! 3. Wherever the new functionality is implemented, call
//! [`Config::cli_unstable`] to get an instance of [`CliUnstable`]
Expand Down Expand Up @@ -136,6 +134,7 @@
//! [`Config::cli_unstable`]: crate::util::config::Config::cli_unstable
//! [`fail_if_stable_opt`]: CliUnstable::fail_if_stable_opt
//! [`features!`]: macro.features.html
//! [`unstable_cli_options!`]: macro.unstable_cli_options.html

use std::collections::BTreeSet;
use std::env;
Expand All @@ -151,11 +150,13 @@ use crate::util::errors::CargoResult;
use crate::util::{indented_lines, iter_join};
use crate::Config;

pub const HIDDEN: &str = "";
pub const SEE_CHANNELS: &str =
"See https://doc.rust-lang.org/book/appendix-07-nightly-rust.html for more information \
about Rust release channels.";

/// Value of [`allow-features`](CliUnstable::allow_features]
pub type AllowFeatures = BTreeSet<String>;

/// The edition of the compiler ([RFC 2052])
///
/// The following sections will guide you how to add and stabilize an edition.
Expand Down Expand Up @@ -357,20 +358,43 @@ enum Status {
Removed,
}

/// A listing of stable and unstable new syntax in Cargo.toml.
///
/// This generates definitions and impls for [`Features`] and [`Feature`]
/// for each new syntax.
///
/// Note that all feature names in the macro invocation are valid Rust
/// identifiers, but the `_` character is translated to `-` when specified in
/// the `cargo-features` manifest entry in `Cargo.toml`.
///
/// See the [module-level documentation](self#new-cargotoml-syntax)
/// for the process of adding a new syntax.
macro_rules! features {
(
$(($stab:ident, $feature:ident, $version:expr, $docs:expr),)*
$(
$(#[$attr:meta])*
($stab:ident, $feature:ident, $version:expr, $docs:expr),
)*
) => (
/// Unstable feature context for querying if a new Cargo.toml syntax
/// is allowed to use.
///
/// See the [module-level documentation](self#new-cargotoml-syntax) for the usage.
#[derive(Default, Clone, Debug)]
pub struct Features {
$($feature: bool,)*
/// The current activated features.
activated: Vec<String>,
/// Whether is allowed to use any unstable features.
nightly_features_allowed: bool,
/// Whether the source mainfest is from a local package.
is_local: bool,
}

impl Feature {
$(
$(#[$attr])*
#[doc = concat!("\n\n\nSee <https://doc.rust-lang.org/nightly/cargo/", $docs, ">.")]
pub fn $feature() -> &'static Feature {
fn get(features: &Features) -> bool {
stab!($stab) == Status::Stable || features.$feature
Expand All @@ -386,6 +410,7 @@ macro_rules! features {
}
)*

/// Whether this feature is allowed to use in the given [`Features`] context.
fn is_enabled(&self, features: &Features) -> bool {
(self.get)(features)
}
Expand Down Expand Up @@ -420,96 +445,91 @@ macro_rules! stab {
};
}

// A listing of all features in Cargo.
//
// "look here"
//
// This is the macro that lists all stable and unstable features in Cargo.
// You'll want to add to this macro whenever you add a feature to Cargo, also
// following the directions above.
//
// Note that all feature names here are valid Rust identifiers, but the `_`
// character is translated to `-` when specified in the `cargo-features`
// manifest entry in `Cargo.toml`.
features! {
// A dummy feature that doesn't actually gate anything, but it's used in
// testing to ensure that we can enable stable features.
/// A dummy feature that doesn't actually gate anything, but it's used in
/// testing to ensure that we can enable stable features.
(stable, test_dummy_stable, "1.0", ""),

// A dummy feature that gates the usage of the `im-a-teapot` manifest
// entry. This is basically just intended for tests.
/// A dummy feature that gates the usage of the `im-a-teapot` manifest
/// entry. This is basically just intended for tests.
(unstable, test_dummy_unstable, "", "reference/unstable.html"),

// Downloading packages from alternative registry indexes.
/// Downloading packages from alternative registry indexes.
(stable, alternative_registries, "1.34", "reference/registries.html"),

// Using editions
/// Using editions
(stable, edition, "1.31", "reference/manifest.html#the-edition-field"),

// Renaming a package in the manifest via the `package` key
/// Renaming a package in the manifest via the `package` key.
(stable, rename_dependency, "1.31", "reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml"),

// Whether a lock file is published with this crate
/// Whether a lock file is published with this crate.
(removed, publish_lockfile, "1.37", "reference/unstable.html#publish-lockfile"),

// Overriding profiles for dependencies.
/// Overriding profiles for dependencies.
(stable, profile_overrides, "1.41", "reference/profiles.html#overrides"),

// "default-run" manifest option,
/// "default-run" manifest option.
(stable, default_run, "1.37", "reference/manifest.html#the-default-run-field"),

// Declarative build scripts.
/// Declarative build scripts.
(unstable, metabuild, "", "reference/unstable.html#metabuild"),

// Specifying the 'public' attribute on dependencies
/// Specifying the 'public' attribute on dependencies.
(unstable, public_dependency, "", "reference/unstable.html#public-dependency"),

// Allow to specify profiles other than 'dev', 'release', 'test', etc.
/// Allow to specify profiles other than 'dev', 'release', 'test', etc.
(stable, named_profiles, "1.57", "reference/profiles.html#custom-profiles"),

// Opt-in new-resolver behavior.
/// Opt-in new-resolver behavior.
(stable, resolver, "1.51", "reference/resolver.html#resolver-versions"),

// Allow to specify whether binaries should be stripped.
/// Allow to specify whether binaries should be stripped.
(stable, strip, "1.58", "reference/profiles.html#strip-option"),

// Specifying a minimal 'rust-version' attribute for crates
/// Specifying a minimal 'rust-version' attribute for crates.
(stable, rust_version, "1.56", "reference/manifest.html#the-rust-version-field"),

// Support for 2021 edition.
/// Support for 2021 edition.
(stable, edition2021, "1.56", "reference/manifest.html#the-edition-field"),

// Allow to specify per-package targets (compile kinds)
/// Allow to specify per-package targets (compile kinds).
(unstable, per_package_target, "", "reference/unstable.html#per-package-target"),

// Allow to specify which codegen backend should be used.
/// Allow to specify which codegen backend should be used.
(unstable, codegen_backend, "", "reference/unstable.html#codegen-backend"),

// Allow specifying different binary name apart from the crate name
/// Allow specifying different binary name apart from the crate name.
(unstable, different_binary_name, "", "reference/unstable.html#different-binary-name"),

// Allow specifying rustflags directly in a profile
/// Allow specifying rustflags directly in a profile.
(unstable, profile_rustflags, "", "reference/unstable.html#profile-rustflags-option"),

// Allow specifying rustflags directly in a profile
/// Allow workspace members to inherit fields and dependencies from a workspace.
(stable, workspace_inheritance, "1.64", "reference/unstable.html#workspace-inheritance"),

// Support for 2024 edition.
/// Support for 2024 edition.
(unstable, edition2024, "", "reference/unstable.html#edition-2024"),

// Allow setting trim-paths in a profile to control the sanitisation of file paths in build outputs.
/// Allow setting trim-paths in a profile to control the sanitisation of file paths in build outputs.
(unstable, trim_paths, "", "reference/unstable.html#profile-trim-paths-option"),
}

/// Status and metadata for a single unstable feature.
pub struct Feature {
/// Feature name. This is valid Rust identifer so no dash only underscore.
name: &'static str,
stability: Status,
/// Version that this feature was stabilized or removed.
version: &'static str,
/// Link to the unstable documentation.
docs: &'static str,
get: fn(&Features) -> bool,
}

impl Features {
/// Creates a new unstable features context.
pub fn new(
features: &[String],
config: &Config,
Expand Down Expand Up @@ -616,10 +636,12 @@ impl Features {
Ok(())
}

/// Gets the current activated features.
pub fn activated(&self) -> &[String] {
&self.activated
}

/// Checks if the given feature is enabled.
pub fn require(&self, feature: &Feature) -> CargoResult<()> {
if feature.is_enabled(self) {
return Ok(());
Expand Down Expand Up @@ -665,16 +687,20 @@ impl Features {
bail!("{}", msg);
}

/// Whether the given feature is allowed to use in this context.
pub fn is_enabled(&self, feature: &Feature) -> bool {
feature.is_enabled(self)
}
}

/// Generates `-Z` flags as fields of [`CliUnstable`].
///
/// See the [module-level documentation](self#-z-options) for details.
macro_rules! unstable_cli_options {
(
$(
$(#[$meta:meta])?
$element: ident: $ty: ty = ($help: expr ),
$element: ident: $ty: ty$( = ($help:literal))?,
)*
) => {
/// A parsed representation of all unstable flags that Cargo accepts.
Expand All @@ -686,13 +712,15 @@ macro_rules! unstable_cli_options {
#[serde(default, rename_all = "kebab-case")]
pub struct CliUnstable {
$(
$(#[doc = $help])?
$(#[$meta])?
pub $element: $ty
),*
}
impl CliUnstable {
pub fn help() -> Vec<(&'static str, &'static str)> {
let fields = vec![$((stringify!($element), $help)),*];
/// Returns a list of `(<option-name>, <help-text>)`.
pub fn help() -> Vec<(&'static str, Option<&'static str>)> {
let fields = vec![$((stringify!($element), None$(.or(Some($help)))?)),*];
fields
}
}
Expand Down Expand Up @@ -721,12 +749,12 @@ macro_rules! unstable_cli_options {

unstable_cli_options!(
// Permanently unstable features:
allow_features: Option<BTreeSet<String>> = ("Allow *only* the listed unstable features"),
print_im_a_teapot: bool = (HIDDEN),
allow_features: Option<AllowFeatures> = ("Allow *only* the listed unstable features"),
print_im_a_teapot: bool,

// All other unstable features.
// Please keep this list lexicographically ordered.
advanced_env: bool = (HIDDEN),
advanced_env: bool,
asymmetric_token: bool = ("Allows authenticating with asymmetric tokens"),
avoid_dev_deps: bool = ("Avoid installing dev-dependencies if possible"),
binary_dep_depinfo: bool = ("Track changes to dependency artifacts"),
Expand All @@ -740,24 +768,24 @@ unstable_cli_options!(
direct_minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum (direct dependencies only)"),
doctest_xcompile: bool = ("Compile and run doctests for non-host target using runner config"),
dual_proc_macros: bool = ("Build proc-macros for both the host and the target"),
features: Option<Vec<String>> = (HIDDEN),
features: Option<Vec<String>>,
gc: bool = ("Track cache usage and \"garbage collect\" unused files"),
gitoxide: Option<GitoxideFeatures> = ("Use gitoxide for the given git interactions, or all of them if no argument is given"),
host_config: bool = ("Enable the [host] section in the .cargo/config.toml file"),
host_config: bool = ("Enable the `[host]` section in the .cargo/config.toml file"),
lints: bool = ("Pass `[lints]` to the linting tools"),
minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum"),
msrv_policy: bool = ("Enable rust-version aware policy within cargo"),
mtime_on_use: bool = ("Configure Cargo to update the mtime of used files"),
next_lockfile_bump: bool = (HIDDEN),
next_lockfile_bump: bool,
no_index_update: bool = ("Do not update the registry index even if the cache is outdated"),
panic_abort_tests: bool = ("Enable support to run tests with -Cpanic=abort"),
profile_rustflags: bool = ("Enable the `rustflags` option in profiles in .cargo/config.toml file"),
publish_timeout: bool = ("Enable the `publish.timeout` key in .cargo/config.toml file"),
rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"),
rustdoc_scrape_examples: bool = ("Allows Rustdoc to scrape code examples from reverse-dependencies"),
script: bool = ("Enable support for single-file, `.rs` packages"),
separate_nightlies: bool = (HIDDEN),
skip_rustdoc_fingerprint: bool = (HIDDEN),
separate_nightlies: bool,
skip_rustdoc_fingerprint: bool,
target_applies_to_host: bool = ("Enable the `target-applies-to-host` key in the .cargo/config.toml file"),
trim_paths: bool = ("Enable the `trim-paths` option in profiles"),
unstable_options: bool = ("Allow the usage of unstable options"),
Expand Down Expand Up @@ -915,6 +943,8 @@ fn parse_gitoxide(
}

impl CliUnstable {
/// Parses `-Z` flags from the command line, and returns messages that warn
/// if any flag has alreardy been stabilized.
pub fn parse(
&mut self,
flags: &[String],
Expand Down
2 changes: 1 addition & 1 deletion tests/testsuite/cargo/z_help/stdout.log
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Available unstable (nightly-only) flags:
-Z dual-proc-macros Build proc-macros for both the host and the target
-Z gc Track cache usage and "garbage collect" unused files
-Z gitoxide Use gitoxide for the given git interactions, or all of them if no argument is given
-Z host-config Enable the [host] section in the .cargo/config.toml file
-Z host-config Enable the `[host]` section in the .cargo/config.toml file
-Z lints Pass `[lints]` to the linting tools
-Z minimal-versions Resolve minimal dependency versions instead of maximum
-Z msrv-policy Enable rust-version aware policy within cargo
Expand Down