dtolnay/cargo-expand

Feature request: allow `--cfg` flags to be passed to the compilation

yannbolliger opened this issue · 3 comments

We have a use-case where some macro inserts code with #[cfg(our_flag)] and we can compile the project/file with --cfg our_flag given to cargo build. It would be great, to be able to do the same for cargo expand. Also happy to provide a PR.

Desired interface:

cargo expand --example our_example --cfg our_flag
# or 
cargo expand --example our_example -- --cfg our_flag

we can compile the project/file with --cfg our_flag given to cargo build.

Huh? Cargo build does not take a cfg flag as far as I can tell.

$ cargo build --example our_example --cfg our_flag
error: Found argument '--cfg' which wasn't expected, or isn't valid in this context

USAGE:
    cargo build --example <NAME>...

For more information try --help

$ cargo build --example our_example -- --cfg our_flag
error: Found argument '--cfg' which wasn't expected, or isn't valid in this context

USAGE:
    cargo build --example <NAME>...

For more information try --help

I'm sorry, you're right. I actually meant that, as you write in the README, cargo expand is a wrapper for cargo rustc --profile=check -- -Zunstable-options --pretty=expanded. There, one can append the --cfg our_flag which will then trigger conditional compilation.

What also works, is RUST_FLAGS="--cfg our_flag" cargo build and it would be great if cargo expand would also pick that flag up, or offered the flag itself:

RUST_FLAGS="--cfg our_flag" cargo expand --example our_example
# or
cargo expand --example our_example --cfg our_flag
# or 
cargo expand --example our_example -- --cfg our_flag

I believe that already works, using the same env var that other cargo commands use.

#[cfg_attr(our_flag, derive(Copy))]
struct S;
$ cargo expand
...
struct S;

$ RUSTFLAGS='--cfg our_flag' cargo expand
...
struct S;
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::marker::Copy for S {}