Skip to content

Commit

Permalink
Make unexpected target cfgs respect Rust unexpected_cfgs lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Urgau committed Sep 23, 2024
1 parent 4109e11 commit bd376fb
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 6 deletions.
2 changes: 1 addition & 1 deletion crates/cargo-platform/src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl CfgExpr {
}
}

pub fn fold<E>(&self, f: &impl Fn(&Cfg) -> Result<(), E>) -> Result<(), E> {
pub fn fold<E>(&self, f: &mut impl FnMut(&Cfg) -> Result<(), E>) -> Result<(), E> {
match *self {
CfgExpr::Not(ref e) => CfgExpr::fold(e, f),
CfgExpr::All(ref e) | CfgExpr::Any(ref e) => {
Expand Down
53 changes: 49 additions & 4 deletions src/cargo/ops/cargo_compile/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ use crate::ops;
use crate::ops::resolve::WorkspaceResolve;
use crate::util::context::GlobalContext;
use crate::util::interning::InternedString;
use crate::util::lints::LintLevel;
use crate::util::{CargoResult, Rustc, StableHasher};

mod compile_filter;
Expand Down Expand Up @@ -482,6 +483,9 @@ pub fn create_bcx<'a, 'gctx>(

if let Some(check_cfg) = target_data.check_cfg() {
if check_cfg.exhaustive {
let mut error_count = 0;
let mut max_lint_level = LintLevel::Allow;

let target_cfgs = gctx.target_cfgs()?;
for (key, _fields) in target_cfgs {
if !key.starts_with("cfg(") || !key.ends_with(')') {
Expand All @@ -493,14 +497,36 @@ pub fn create_bcx<'a, 'gctx>(
continue;
};

warn_on_unexpected_cfgs(gctx, check_cfg, &cfg_expr, None, "")?;
warn_on_unexpected_cfgs(
gctx,
check_cfg,
&cfg_expr,
LintLevel::Warn,
&mut error_count,
None,
"",
)?;
}

for unit in &units {
if !unit.show_warnings(gctx) {
continue;
}

let mut lint_level = LintLevel::Warn;
if let Ok(Some(lints)) = unit.pkg.manifest().normalized_toml().normalized_lints() {
if let Some(rust_lints) = lints.get("rust") {
if let Some(unexpected_cfgs) = rust_lints.get("unexpected_cfgs") {
lint_level = unexpected_cfgs.level().into();
max_lint_level = std::cmp::max(max_lint_level, lint_level);
}
}
}

if lint_level == LintLevel::Allow {
continue;
}

let specific_check_cfg =
get_specific_check_cfg_for_unit(gctx, &target_data.rustc, unit)?;
let check_cfg = specific_check_cfg.as_ref().unwrap_or(check_cfg);
Expand All @@ -521,11 +547,19 @@ pub fn create_bcx<'a, 'gctx>(
gctx,
check_cfg,
cfg_expr,
lint_level,
&mut error_count,
Some(unit.pkg.manifest_path()),
".dependencies",
)?;
}
}

if max_lint_level >= LintLevel::Deny && error_count > 0 {
Err(anyhow::anyhow!(
"encountered {error_count} `unexpected_cfgs` error(s)",
))?
}
}
}

Expand Down Expand Up @@ -613,6 +647,8 @@ fn warn_on_unexpected_cfgs(
gctx: &GlobalContext,
check_cfg: &CheckCfg,
cfg_expr: &CfgExpr,
lint_level: LintLevel,
error_count: &mut u32,
path: Option<&Path>,
suffix: &str,
) -> CargoResult<()> {
Expand All @@ -622,7 +658,16 @@ fn warn_on_unexpected_cfgs(
"".to_string()
};

cfg_expr.fold(&|cfg| -> CargoResult<()> {
let mut emit_lint = |msg| {
*error_count += 1;
match lint_level {
LintLevel::Warn => gctx.shell().warn(msg),
LintLevel::Deny | LintLevel::Forbid => gctx.shell().error(msg),
LintLevel::Allow => Ok(()),
}
};

cfg_expr.fold(&mut |cfg| -> CargoResult<()> {
let (name, value) = match cfg {
Cfg::Name(name) => (name, None),
Cfg::KeyPair(name, value) => (name, Some(value.to_string())),
Expand All @@ -635,12 +680,12 @@ fn warn_on_unexpected_cfgs(
} else {
"(none)"
};
gctx.shell().warn(format!(
emit_lint(format!(
"{prefix}unexpected `cfg` condition value: `{value}` for `{cfg}` in `[target.'cfg({cfg_expr})'{suffix}]`"
))?;
}
None => {
gctx.shell().warn(format!(
emit_lint(format!(
"{prefix}unexpected `cfg` condition name: `{name}`{cfg} in `[target.'cfg({cfg_expr})'{suffix}]`",
cfg = if value.is_some() {
format!(" for `{cfg}`")
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/util/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ impl Lint {
}
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum LintLevel {
Allow,
Warn,
Expand Down
71 changes: 71 additions & 0 deletions tests/testsuite/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,77 @@ fn unexpected_cfgs_target_with_lint() {
.run();
}

#[cargo_test(nightly, reason = "--print=check-cfg is unstable in rustc")]
fn unexpected_cfgs_target_lint_level_allow() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "a"
version = "0.0.1"
edition = "2015"
authors = []
[target."cfg(foo)".dependencies]
b = { path = 'b' }
[lints.rust.unexpected_cfgs]
level = "allow"
"#,
)
.file("src/lib.rs", "")
.file("b/Cargo.toml", &basic_manifest("b", "0.0.1"))
.file("b/src/lib.rs", "")
.build();

p.cargo("check -Zcheck-target-cfgs")
.masquerade_as_nightly_cargo(&["requires -Zcheck-target-cfgs"])
.with_stderr_data(str![[r#"
[LOCKING] 1 package to latest compatible version
[CHECKING] a v0.0.1 ([ROOT]/foo)
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
"#]])
.run();
}

#[cargo_test(nightly, reason = "--print=check-cfg is unstable in rustc")]
fn unexpected_cfgs_target_lint_level_deny() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "a"
version = "0.0.1"
edition = "2015"
authors = []
[target."cfg(foo)".dependencies]
b = { path = 'b' }
[lints.rust.unexpected_cfgs]
level = "deny"
"#,
)
.file("src/lib.rs", "")
.file("b/Cargo.toml", &basic_manifest("b", "0.0.1"))
.file("b/src/lib.rs", "")
.build();

p.cargo("check -Zcheck-target-cfgs")
.masquerade_as_nightly_cargo(&["requires -Zcheck-target-cfgs"])
.with_stderr_data(str![[r#"
[LOCKING] 1 package to latest compatible version
[ERROR] [ROOT]/foo/Cargo.toml: unexpected `cfg` condition name: `foo` in `[target.'cfg(foo)'.dependencies]`
[ERROR] encountered 1 `unexpected_cfgs` error(s)
"#]])
.with_status(101)
.run();
}

#[cargo_test(nightly, reason = "--print=check-cfg is unstable in rustc")]
fn unexpected_cfgs_target_cfg_any() {
let p = project()
Expand Down

0 comments on commit bd376fb

Please sign in to comment.