rust-lang / rust-analyzer

A Rust compiler front-end for IDEs
https://rust-analyzer.github.io/
Apache License 2.0
14.34k stars 1.62k forks source link

Inconsistent warning for macros that contain `unexpected_cfgs` #18461

Closed funemy closed 3 weeks ago

funemy commented 3 weeks ago

Hi, I recently encountered an inconsistent behavior of rust-analyzer when I have a macro which expands to something with unexpected_cfgs.

I would like to understand if this is expected, because it feels like a bug to me.

Here is a minimal example:

Say I have a library mylib, and mylib/lib.rs has

pub fn my_lib_func() {
    println!("my nice little library")
}

#[macro_export]
macro_rules! my_lib_macro {
    () => {
        #[cfg(feature = "my_feature")]
        $crate::my_lib_func()
    };
}

#[test]
fn my_unit_test() {
    // rust-analyzer warning here
    my_lib_macro!();
}

mylib has no feature declared, so I got an unexpected_cfgs warning in the place where I called my_lib_macro!():

unexpected `cfg` condition value: `my_feature`
   no expected values for `feature`
   consider adding `my_feature` as a feature in `Cargo.toml`
   see <https://doc.rust-lang.org/nightly/rustc/check-cfg/cargo-specifics.html> for more information about checking conditional configuration
   `#[warn(unexpected_cfgs)]` on by default [unexpected_cfgs]

This is great, exactly what I would expect.

However, if I use mylib in other packages, say I have another crate, myapp, that depends on mylib. In myapp/main.rs, I have:

use mylib::my_lib_macro;

fn main() {
    my_lib_macro!();
}

Rust-analyzer does not report anything in main(), which confuses me why that is the case.

Hopefully the example makes sense, happy to provide more information if needed. And thanks for the help :).

ChayimFriedman2 commented 3 weeks ago

Is the same thing happening with cargo check?

funemy commented 3 weeks ago

@ChayimFriedman2 I'm not sure if I did it correctly, but I didn't see any warning with cargo check.

ChayimFriedman2 commented 3 weeks ago

Then rust-analyzer is functioning correctly, the warnings are reported by Cargo (and rustc), if they are missing it's at most a Cargo bug, not a rust-analyzer bug.

I believe this is because there is no way to state the expected features for a binary, so every feature is expected.