5

I am currently making an embedded system. For that I have 2 different panic handlers based on whether it is run normally or as a test. #[cfg(test)] for the test panic handler and #[cfg(not(test))] for the normal panic handler.

rust-analyzer says: code is inactive due to #[cfg] directives: test is enabled

and grays out the function. Test is never explicitly set so I cant just change it and I don't want to disable the graying out inactive code across the workspace.

Is there a way to either disable rust-analyzer checking the test cfg, or to disable the gray out just for this function

I tried finding infos about the test flag but I couldn't find any, i'm using VS Code if it is important

lv4
  • 53
  • 6
  • I would also be curious to find out how to do this with arbitrary features in CLion/Intellij. – Locke Feb 02 '23 at 17:19
  • If you will disable the inactive cfgs, you will get two functions with the same name, which is an error. Do you want that? – Chayim Friedman Feb 02 '23 at 18:24
  • no but I'd rather have #[cfg(test)] inactive by default instead of #[cfg(not(test))] – lv4 Feb 02 '23 at 18:58
  • Related: [Code is inactive hint on `#[cfg(not(test))]`](https://github.com/rust-lang/rust-analyzer/issues/7529) and the linked issue. – cafce25 Feb 02 '23 at 19:09

1 Answers1

3

In VSCode's workspaces settings, set the following:

"rust-analyzer.cargo.extraEnv": {
  "RUSTFLAGS": "--cfg rust_analyzer"
}

This will enable the #[cfg(rust_analyzer)] for rust-analyzer metadata inspection.

Then, replace #[cfg(not(test))] with #[cfg(any(not(test), rust_analyzer))], and #[cfg(test)] with #[cfg(all(test, not(rust_analyzer)))]. This will disable and enable the functions for testing as usual, but when running in rust-analyzer, only the no-test function will be enabled.

Important: this will only work if you don't need to set special RUSTFLAGS for your workspace.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • Thank you, do you have the link to the docs, so I can read up on what exactly this does? – lv4 Feb 02 '23 at 19:32
  • 1
    @lv4 https://rust-analyzer.github.io/manual for `extraEnv`, https://doc.rust-lang.org/rustc/command-line-arguments.html#--cfg-configure-the-compilation-environment for the `--cfg`, and the rest is just normal Rust cfg. – Chayim Friedman Feb 02 '23 at 19:34