Can proc macros read compiler cfgs?

Is it possible for a proc macro to read the cfg flags that are set while the macro is being executed? #[cfg(...)] and friends will work on the ones defined when the proc macro crate itself is being compiled, which aren’t necessarily the same, and it would be a nice way to let different crates in the same project control the macro’s behavior indepently.

In particular, I want it to expand slightly differently when used inside its partner ordinary crate instead of a downstream user of the pair— The most promising avenue I see right now is compiling my crate with a cfg flag that won’t be in general use.

Please note that this is a pedagogical exercise to poke at the limits of what proc macros can and can’t do; I’m not interested in any solution that involves altering the callsite itself by, for example, adding another argument.

No, proc macros currently can't do this.

1 Like

I think you might be able to grab this information using env variables cargo populates? I know you can grab these from a build.rs in the client crate, I don't know if the same information is available to proc macros running but I expect it might be.

It'd definitely be hacky, but it might be possible.

1 Like

It looks like the CARGO_PKG_NAME and CARGO_PKG_VERSION* environment variables get set for compilation runs, so env! will fetch them when the proc macro is compiled, and std::env::var_os can be used to get them while the proc macro is running and producing code.

1 Like

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.