3

I want to print the compile-time attributes to the console, ("conditional predicates"). Is there built-in function or macro that does this?

I'm imagining code like:

#[allow(non_snake_case)]
fn main() {
    eprintln!(cfg_as_str!());
}

that might print

allow.non_snake_case=true
allow.dead_code=false
...
cfg.debug_attributes=true
cfg.test=false
cfg.bench=false
...
target_arch="x86_64"
...

I want to better understand the state of the rust compiler at different lines of code. However, it's tedious to do so by trial-and-error.

Of course, I could write this on my own. But I'd guess someone else already has.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
  • 1
    Do you want to print only `cfg`s or all attributes in scope? – Chayim Friedman Apr 01 '22 at 05:30
  • More is better than less in this case. But either would help. – JamesThomasMoon Apr 01 '22 at 05:31
  • 1
    Does this help get the information you want: [How to obtain the value of a configuration flag?](https://stackoverflow.com/q/43435072/2189130) – kmdreko Apr 01 '22 at 05:38
  • Thanks @kmdreko . The Question is somewhat related but not quite what I was looking for. – JamesThomasMoon Apr 01 '22 at 05:43
  • 1
    I get that, but I think what you're looking for doesn't exist. The lint attributes in particular would need help from the compiler to get that status and I don't think that kind of API is available. – kmdreko Apr 01 '22 at 06:08
  • Related Question [How can a Rust program access metadata from its Cargo package?](https://stackoverflow.com/questions/27840394/how-can-a-rust-program-access-metadata-from-its-cargo-package) – JamesThomasMoon Apr 13 '22 at 22:05

1 Answers1

0

I don't think you'll get the lint attributes but for the cfg options you could add a build.rs with:

use std::env;

fn main() {
    for (key, value) in env::vars() {
        if key.starts_with("CARGO") {
            eprintln!("{}: {}", key, value);
        }
    }
}

Then building with cargo build -vv will output cfgs.

See: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts

evading
  • 3,032
  • 6
  • 37
  • 57
  • Thanks @evading . But wouldn't that print the process environment variables+values? Not uninteresting to me, but not quite what I was looking for. – JamesThomasMoon Apr 01 '22 at 21:56
  • 1
    @JamesThomasMoon Yes, but Cargo will set the cfg attributes and features as environment variables for you, so running my example with `cargo test -vv --features=this-feature-will-show^C` will print things like `CARGO_CFG_TARGET_ARCH: x86_64` and `CARGO_FEATURE_THIS_FEATURE_WILL_SHOW: 1`. But maybe I'm misunderstanding what you're trying to do =) – evading Apr 03 '22 at 06:32