Skip to content

Commit 7ebc065

Browse files
committed
Auto merge of #13571 - Urgau:stabilize-check-cfg, r=weihanglo
Stabilize `-Zcheck-cfg` as always enabled This PR stabilize the `-Zcheck-cfg` option as always enabled. ~~Waiting on rust-lang/rust#82450 (comment) to complete, but is otherwise ready to be reviewed (in particular the documentation changes).~~ (rust-lang/rust#123501) Fixes #10554
2 parents cf7b3c4 + 388a17f commit 7ebc065

File tree

19 files changed

+184
-332
lines changed

19 files changed

+184
-332
lines changed

src/cargo/core/compiler/build_context/target_info.rs

+13
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@ pub struct TargetInfo {
5555
pub rustflags: Vec<String>,
5656
/// Extra flags to pass to `rustdoc`, see [`extra_args`].
5757
pub rustdocflags: Vec<String>,
58+
/// Whether or not rustc (stably) supports the `--check-cfg` flag.
59+
///
60+
/// Can be removed once the minimum supported rustc version of Cargo is
61+
/// at minimum 1.80.0.
62+
pub support_check_cfg: bool,
5863
}
5964

6065
/// Kind of each file generated by a Unit, part of `FileType`.
@@ -199,6 +204,13 @@ impl TargetInfo {
199204
process.arg("--crate-type").arg(crate_type.as_str());
200205
}
201206

207+
let support_check_cfg = rustc
208+
.cached_output(
209+
process.clone().arg("--check-cfg").arg("cfg()"),
210+
extra_fingerprint,
211+
)
212+
.is_ok();
213+
202214
process.arg("--print=sysroot");
203215
process.arg("--print=split-debuginfo");
204216
process.arg("--print=crate-name"); // `___` as a delimiter.
@@ -310,6 +322,7 @@ impl TargetInfo {
310322
)?,
311323
cfg,
312324
support_split_debuginfo,
325+
support_check_cfg,
313326
});
314327
}
315328
}

src/cargo/core/compiler/build_runner/mod.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -256,12 +256,9 @@ impl<'a, 'gctx> BuildRunner<'a, 'gctx> {
256256
args.push(cfg.into());
257257
}
258258

259-
if !output.check_cfgs.is_empty() {
260-
args.push("-Zunstable-options".into());
261-
for check_cfg in &output.check_cfgs {
262-
args.push("--check-cfg".into());
263-
args.push(check_cfg.into());
264-
}
259+
for check_cfg in &output.check_cfgs {
260+
args.push("--check-cfg".into());
261+
args.push(check_cfg.into());
265262
}
266263

267264
for (lt, arg) in &output.linker_args {

src/cargo/core/compiler/custom_build.rs

+13-7
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,11 @@ fn build_work(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResul
408408
paths::create_dir_all(&script_out_dir)?;
409409

410410
let nightly_features_allowed = build_runner.bcx.gctx.nightly_features_allowed;
411-
let extra_check_cfg = build_runner.bcx.gctx.cli_unstable().check_cfg;
411+
let extra_check_cfg = build_runner
412+
.bcx
413+
.target_data
414+
.info(unit.kind)
415+
.support_check_cfg;
412416
let targets: Vec<Target> = unit.pkg.targets().to_vec();
413417
let msrv = unit.pkg.rust_version().cloned();
414418
// Need a separate copy for the fresh closure.
@@ -665,9 +669,7 @@ impl BuildOutput {
665669
///
666670
/// * `pkg_descr` --- for error messages
667671
/// * `library_name` --- for determining if `RUSTC_BOOTSTRAP` should be allowed
668-
/// * `extra_check_cfg` --- for unstable feature [`-Zcheck-cfg`]
669-
///
670-
/// [`-Zcheck-cfg`]: https://doc.rust-lang.org/cargo/reference/unstable.html#check-cfg
672+
/// * `extra_check_cfg` --- for `--check-cfg` (if supported)
671673
pub fn parse(
672674
input: &[u8],
673675
// Takes String instead of InternedString so passing `unit.pkg.name()` will give a compile error.
@@ -910,8 +912,8 @@ impl BuildOutput {
910912
if extra_check_cfg {
911913
check_cfgs.push(value.to_string());
912914
} else {
913-
// silently ignoring the instruction to try to
914-
// minimise MSRV annoyance when stabilizing -Zcheck-cfg
915+
// silently ignoring the instruction because the rustc version
916+
// we are using does not support --check-cfg stably
915917
}
916918
}
917919
"rustc-env" => {
@@ -1254,7 +1256,11 @@ fn prev_build_output(
12541256
&unit.pkg.to_string(),
12551257
&prev_script_out_dir,
12561258
&script_out_dir,
1257-
build_runner.bcx.gctx.cli_unstable().check_cfg,
1259+
build_runner
1260+
.bcx
1261+
.target_data
1262+
.info(unit.kind)
1263+
.support_check_cfg,
12581264
build_runner.bcx.gctx.nightly_features_allowed,
12591265
unit.pkg.targets(),
12601266
&unit.pkg.rust_version().cloned(),

src/cargo/core/compiler/fingerprint/mod.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -1454,14 +1454,7 @@ fn calculate_normal(
14541454
// actually affect the output artifact so there's no need to hash it.
14551455
path: util::hash_u64(path_args(build_runner.bcx.ws, unit).0),
14561456
features: format!("{:?}", unit.features),
1457-
// Note we curently only populate `declared_features` when `-Zcheck-cfg`
1458-
// is passed since it's the only user-facing toggle that will make this
1459-
// fingerprint relevant.
1460-
declared_features: if build_runner.bcx.gctx.cli_unstable().check_cfg {
1461-
format!("{declared_features:?}")
1462-
} else {
1463-
"".to_string()
1464-
},
1457+
declared_features: format!("{declared_features:?}"),
14651458
deps,
14661459
local: Mutex::new(local),
14671460
memoized_hash: Mutex::new(None),

src/cargo/core/compiler/mod.rs

+8-10
Original file line numberDiff line numberDiff line change
@@ -1310,11 +1310,13 @@ fn trim_paths_args(
13101310
}
13111311

13121312
/// Generates the `--check-cfg` arguments for the `unit`.
1313-
/// See unstable feature [`check-cfg`].
1314-
///
1315-
/// [`check-cfg`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg
13161313
fn check_cfg_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1317-
if build_runner.bcx.gctx.cli_unstable().check_cfg {
1314+
if build_runner
1315+
.bcx
1316+
.target_data
1317+
.info(unit.kind)
1318+
.support_check_cfg
1319+
{
13181320
// The routine below generates the --check-cfg arguments. Our goals here are to
13191321
// enable the checking of conditionals and pass the list of declared features.
13201322
//
@@ -1352,7 +1354,6 @@ fn check_cfg_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsStri
13521354
// Cargo, but not all users of rustc (like Rust-for-Linux) use docs.rs.
13531355

13541356
vec![
1355-
OsString::from("-Zunstable-options"),
13561357
OsString::from("--check-cfg"),
13571358
OsString::from("cfg(docsrs)"),
13581359
OsString::from("--check-cfg"),
@@ -1476,11 +1477,8 @@ fn add_custom_flags(
14761477
for cfg in output.cfgs.iter() {
14771478
cmd.arg("--cfg").arg(cfg);
14781479
}
1479-
if !output.check_cfgs.is_empty() {
1480-
cmd.arg("-Zunstable-options");
1481-
for check_cfg in &output.check_cfgs {
1482-
cmd.arg("--check-cfg").arg(check_cfg);
1483-
}
1480+
for check_cfg in &output.check_cfgs {
1481+
cmd.arg("--check-cfg").arg(check_cfg);
14841482
}
14851483
for (name, value) in output.env.iter() {
14861484
cmd.env(name, value);

src/cargo/core/features.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -758,7 +758,6 @@ unstable_cli_options!(
758758
build_std: Option<Vec<String>> = ("Enable Cargo to compile the standard library itself as part of a crate graph compilation"),
759759
build_std_features: Option<Vec<String>> = ("Configure features enabled for the standard library itself when building the standard library"),
760760
cargo_lints: bool = ("Enable the `[lints.cargo]` table"),
761-
check_cfg: bool = ("Enable compile-time checking of `cfg` names/values/features"),
762761
codegen_backend: bool = ("Enable the `codegen-backend` option in profiles in .cargo/config.toml file"),
763762
config_include: bool = ("Enable the `include` key in config files"),
764763
direct_minimal_versions: bool = ("Resolve minimal dependency versions instead of maximum (direct dependencies only)"),
@@ -860,6 +859,9 @@ const STABILIZED_REGISTRY_AUTH: &str =
860859

861860
const STABILIZED_LINTS: &str = "The `[lints]` table is now always available.";
862861

862+
const STABILIZED_CHECK_CFG: &str =
863+
"Compile-time checking of conditional (a.k.a. `-Zcheck-cfg`) is now always enabled.";
864+
863865
fn deserialize_build_std<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
864866
where
865867
D: serde::Deserializer<'de>,
@@ -1114,6 +1116,7 @@ impl CliUnstable {
11141116
"credential-process" => stabilized_warn(k, "1.74", STABILIZED_CREDENTIAL_PROCESS),
11151117
"lints" => stabilized_warn(k, "1.74", STABILIZED_LINTS),
11161118
"registry-auth" => stabilized_warn(k, "1.74", STABILIZED_REGISTRY_AUTH),
1119+
"check-cfg" => stabilized_warn(k, "1.80", STABILIZED_CHECK_CFG),
11171120

11181121
// Unstable features
11191122
// Sorted alphabetically:
@@ -1127,9 +1130,6 @@ impl CliUnstable {
11271130
}
11281131
"build-std-features" => self.build_std_features = Some(parse_features(v)),
11291132
"cargo-lints" => self.cargo_lints = parse_empty(k, v)?,
1130-
"check-cfg" => {
1131-
self.check_cfg = parse_empty(k, v)?;
1132-
}
11331133
"codegen-backend" => self.codegen_backend = parse_empty(k, v)?,
11341134
"config-include" => self.config_include = parse_empty(k, v)?,
11351135
"direct-minimal-versions" => self.direct_minimal_versions = parse_empty(k, v)?,

src/cargo/util/context/target.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ fn load_config_table(gctx: &GlobalContext, prefix: &str) -> CargoResult<TargetCo
120120
// Links do not support environment variables.
121121
let target_key = ConfigKey::from_str(prefix);
122122
let links_overrides = match gctx.get_table(&target_key)? {
123-
Some(links) => parse_links_overrides(&target_key, links.val, gctx)?,
123+
Some(links) => parse_links_overrides(&target_key, links.val)?,
124124
None => BTreeMap::new(),
125125
};
126126
Ok(TargetConfig {
@@ -135,7 +135,6 @@ fn load_config_table(gctx: &GlobalContext, prefix: &str) -> CargoResult<TargetCo
135135
fn parse_links_overrides(
136136
target_key: &ConfigKey,
137137
links: HashMap<String, CV>,
138-
gctx: &GlobalContext,
139138
) -> CargoResult<BTreeMap<String, BuildOutput>> {
140139
let mut links_overrides = BTreeMap::new();
141140

@@ -204,13 +203,8 @@ fn parse_links_overrides(
204203
output.cfgs.extend(list.iter().map(|v| v.0.clone()));
205204
}
206205
"rustc-check-cfg" => {
207-
if gctx.cli_unstable().check_cfg {
208-
let list = value.list(key)?;
209-
output.check_cfgs.extend(list.iter().map(|v| v.0.clone()));
210-
} else {
211-
// silently ignoring the instruction to try to
212-
// minimise MSRV annoyance when stabilizing -Zcheck-cfg
213-
}
206+
let list = value.list(key)?;
207+
output.check_cfgs.extend(list.iter().map(|v| v.0.clone()));
214208
}
215209
"rustc-env" => {
216210
for (name, val) in value.table(key)?.0 {

src/doc/src/reference/build-script-examples.md

+3
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,9 @@ values](https://github.com/sfackler/rust-openssl/blob/dc72a8e2c429e46c275e528b61
456456
```rust,ignore
457457
// (portion of build.rs)
458458
459+
println!("cargo::rustc-check-cfg=cfg(ossl101,ossl102)");
460+
println!("cargo::rustc-check-cfg=cfg(ossl110,ossl110g,ossl111)");
461+
459462
if let Ok(version) = env::var("DEP_OPENSSL_VERSION_NUMBER") {
460463
let version = u64::from_str_radix(&version, 16).unwrap();
461464

src/doc/src/reference/build-scripts.md

+41-1
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ one detailed below.
130130
compiler.
131131
* [`cargo::rustc-cfg=KEY[="VALUE"]`](#rustc-cfg) --- Enables compile-time `cfg`
132132
settings.
133+
* [`cargo::rustc-check-cfg=CHECK_CFG`](#rustc-check-cfg) -- Register custom `cfg`s as
134+
expected for compile-time checking of configs.
133135
* [`cargo::rustc-env=VAR=VALUE`](#rustc-env) --- Sets an environment variable.
134136
* [`cargo::rustc-cdylib-link-arg=FLAG`](#rustc-cdylib-link-arg) --- Passes custom
135137
flags to a linker for cdylib crates.
@@ -233,7 +235,10 @@ equivalent to using [`rustc-link-lib`](#rustc-link-lib) and
233235

234236
The `rustc-cfg` instruction tells Cargo to pass the given value to the
235237
[`--cfg` flag][option-cfg] to the compiler. This may be used for compile-time
236-
detection of features to enable [conditional compilation].
238+
detection of features to enable [conditional compilation]. Custom cfgs
239+
must either be expected using the [`cargo::rustc-check-cfg`](#rustc-check-cfg)
240+
instruction or usage will need to allow the [`unexpected_cfgs`][unexpected-cfgs]
241+
lint to avoid unexpected cfgs warnings.
237242

238243
Note that this does *not* affect Cargo's dependency resolution. This cannot be
239244
used to enable an optional dependency, or enable other Cargo features.
@@ -249,6 +254,41 @@ identifier, the value should be a string.
249254
[cargo features]: features.md
250255
[conditional compilation]: ../../reference/conditional-compilation.md
251256
[option-cfg]: ../../rustc/command-line-arguments.md#option-cfg
257+
[unexpected-cfgs]: ../../rustc/lints/listing/warn-by-default.md#unexpected-cfgs
258+
259+
### `cargo::rustc-check-cfg=CHECK_CFG` {#rustc-check-cfg}
260+
261+
Add to the list of expected config names and values that is used when checking
262+
the _reachable_ cfg expressions.
263+
264+
For details on the syntax of `CHECK_CFG`, see `rustc` [`--check-cfg` flag][option-check-cfg].
265+
See also the [`unexpected_cfgs`][unexpected-cfgs] lint.
266+
267+
The instruction can be used like this:
268+
269+
```rust,no_run
270+
// build.rs
271+
println!("cargo::rustc-check-cfg=cfg(foo, values(\"bar\"))");
272+
```
273+
274+
Note that all possible cfgs should be defined, regardless of which cfgs are
275+
currently enabled. This includes all possible values of a given cfg name.
276+
277+
It is recommended to group the `cargo::rustc-check-cfg` and
278+
[`cargo::rustc-cfg`][option-cfg] instructions as closely as possible in order to
279+
avoid typos, missing check-cfg, stalled cfgs...
280+
281+
#### Example of using `cargo::rustc-check-cfg` and `cargo::rustc-cfg` together
282+
283+
```rust,no_run
284+
// build.rs
285+
println!("cargo::rustc-check-cfg=cfg(foo, values(\"bar\"))");
286+
if foo_bar_condition {
287+
println!("cargo::rustc-cfg=foo=\"bar\"");
288+
}
289+
```
290+
291+
[option-check-cfg]: ../../rustc/command-line-arguments.md#option-check-cfg
252292

253293
### `cargo::rustc-env=VAR=VALUE` {#rustc-env}
254294

src/doc/src/reference/unstable.md

+8-39
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ For the latest nightly, see the [nightly version] of this page.
8383
* [build-std-features](#build-std-features) --- Sets features to use with the standard library.
8484
* [binary-dep-depinfo](#binary-dep-depinfo) --- Causes the dep-info file to track binary dependencies.
8585
* [panic-abort-tests](#panic-abort-tests) --- Allows running tests with the "abort" panic strategy.
86-
* [check-cfg](#check-cfg) --- Compile-time validation of `cfg` expressions.
8786
* [host-config](#host-config) --- Allows setting `[target]`-like configuration settings for host build targets.
8887
* [target-applies-to-host](#target-applies-to-host) --- Alters whether certain flags will be passed to host build targets.
8988
* [gc](#gc) --- Global cache garbage collection.
@@ -1154,44 +1153,6 @@ You can use the flag like this:
11541153
cargo rustdoc -Z unstable-options --output-format json
11551154
```
11561155

1157-
## check-cfg
1158-
1159-
* RFC: [#3013](https://github.com/rust-lang/rfcs/pull/3013)
1160-
* Tracking Issue: [#10554](https://github.com/rust-lang/cargo/issues/10554)
1161-
1162-
`-Z check-cfg` command line enables compile time checking of Cargo features as well as `rustc`
1163-
well known names and values in `#[cfg]`, `cfg!`, `#[link]` and `#[cfg_attr]` with the `rustc`
1164-
and `rustdoc` unstable `--check-cfg` command line.
1165-
1166-
You can use the flag like this:
1167-
1168-
```
1169-
cargo check -Z unstable-options -Z check-cfg
1170-
```
1171-
1172-
### `cargo::rustc-check-cfg=CHECK_CFG`
1173-
1174-
The `rustc-check-cfg` instruction tells Cargo to pass the given value to the
1175-
`--check-cfg` flag to the compiler. This may be used for compile-time
1176-
detection of unexpected conditional compilation name and/or values.
1177-
1178-
This can only be used in combination with `-Zcheck-cfg` otherwise it is ignored
1179-
with a warning.
1180-
1181-
If you want to integrate with Cargo features, only use `-Zcheck-cfg` instead of
1182-
trying to do it manually with this option.
1183-
1184-
You can use the instruction like this:
1185-
1186-
```rust,no_run
1187-
// build.rs
1188-
println!("cargo::rustc-check-cfg=cfg(foo, bar)");
1189-
```
1190-
1191-
```
1192-
cargo check -Z unstable-options -Z check-cfg
1193-
```
1194-
11951156
## codegen-backend
11961157

11971158
The `codegen-backend` feature makes it possible to select the codegen backend used by rustc using a profile.
@@ -1798,3 +1759,11 @@ The `-Z registry-auth` feature has been stabilized in the 1.74 release with the
17981759
requirement that a credential-provider is configured.
17991760

18001761
See [Registry Authentication](registry-authentication.md) documentation for details.
1762+
1763+
## check-cfg
1764+
1765+
The `-Z check-cfg` feature has been stabilized in the 1.80 release by making it the
1766+
default behavior.
1767+
1768+
See the [build script documentation](build-scripts.md#rustc-check-cfg) for informations
1769+
about specifying custom cfgs.

tests/testsuite/build_script.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -2609,7 +2609,10 @@ fn cfg_test() {
26092609
)
26102610
.file(
26112611
"build.rs",
2612-
r#"fn main() { println!("cargo::rustc-cfg=foo"); }"#,
2612+
r#"fn main() {
2613+
println!("cargo::rustc-cfg=foo");
2614+
println!("cargo::rustc-check-cfg=cfg(foo)");
2615+
}"#,
26132616
)
26142617
.file(
26152618
"src/lib.rs",
@@ -2714,6 +2717,9 @@ fn cfg_override_test() {
27142717
authors = []
27152718
build = "build.rs"
27162719
links = "a"
2720+
2721+
[lints.rust]
2722+
unexpected_cfgs = "allow" # bc of override, stable/nightly, tests
27172723
"#,
27182724
)
27192725
.file("build.rs", "")
@@ -5590,9 +5596,10 @@ fn build_script_rerun_when_target_rustflags_change() {
55905596
use std::env;
55915597
55925598
fn main() {
5599+
println!("cargo::rustc-check-cfg=cfg(enable)");
55935600
if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") {
55945601
if !rustflags.is_empty() {
5595-
println!("cargo::rustc-cfg=enable")
5602+
println!("cargo::rustc-cfg=enable");
55965603
}
55975604
}
55985605
}

0 commit comments

Comments
 (0)