reference icon indicating copy to clipboard operation
reference copied to clipboard

Conditional compilation makes it sound like `#[cfg(foo)]` will evaluate to `true` for `--cfg=foo="bar"` but it doesn't

Open epage opened this issue 2 months ago • 1 comments

From the Reference:

A configuration option. The predicate is true if the option is set, and false if it is unset.

And from the Reference

Configuration options are either names or key-value pairs, and are either set or unset.

but rustc's behavior for #[cfg(foo)] is if its set and a name.

A minimal reproduction:

#!/usr/bin/env -S cargo +nightly -Zscript
---
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(foo, values(any()))'] }
---

fn main() {
    println!("Hello from the control grup!");
    #[cfg(foo)]
    println!("Hello from `foo`");
    #[cfg(foo = "value")]
    println!("Hello, from `foo=value`");
}

$ RUSTFLAGS='' ./check-cfg-exists.rs  # unset
Hello from the control grup!

$ RUSTFLAGS='--cfg=foo' ./check-cfg-exists.rs  # set with name
Hello from the control grup!
Hello from `foo`

$ RUSTFLAGS='--cfg=foo="value"' ./check-cfg-exists.rs  # set with key-value pair
Hello from the control grup!
Hello, from `foo=value`

epage avatar Sep 17 '25 18:09 epage

A proposed re-wording

- A configuration option. The predicate is true if the option is set, and false if it is unset.
+ A configuration option. The predicate is true if the option is set and only a name, and false if it is unset or has a value

I've not put up a PR for this yet because I feel like this might need some further investigation first.

epage avatar Sep 17 '25 18:09 epage