Rust analyzer hints to remove code useful for different targets (cfg macro, conditional compilation)

Hello, everyone!

I'm experimenting with developing a cross-platform (web and Unix) game. On the web I use some JS interop, while on Unix I use OS features like environment variables. So I have some code like this:

use wasm_bindgen::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
fn get_env(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(module = "/web-assets/env.js")]
extern "C" {
    fn get_env(name: &str) -> Option<String>;
}

It works very well, but Rust Analyzer gives me warnings and hints like this:

unused import: `wasm_bindgen::prelude::*` `#[warn(unused_imports)]` on by default - rustc
remove the whole `use` item - rustc
code is inactive due to #[cfg] directives: target_arch = "wasm32" is disabled - rust-analyzer

How can I tell the language server that this code is actually useful?

For reference, my code is here: https://gitlab.com/tad-lispy/bevy-lion-playground/-/tree/1f020a0e0715ad1a7d37bb14c0a2bd71b93b6534

Annotate the use with a cfg(…) as well.

1 Like

The warning comes from rustc, so you would get it with cargo build too. Rust-analyzer merely passed it through. The hint does come from rust-analyzer. Rust-analyzer only supports working on a single configuration at a time. You can switch for which target the configuration is used using the rust-analyzer.cargo.target config, but if you set it to a wasm target, you will get the same hint except on the non-wasm code.

1 Like

Thank you. That's a good advise insofar as there is no warning anymore. The hints are still there but I guess I can live with them. The warning was most annoying.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.