facebook / facebook/buck2

Pass name of crate being compiled to `rustc` when using rust_library/rust_binary

Open
#348 6 comments 0 reactions 0 assignees View on GitHub
prelude rust
Dominant language
Rust
Stars
4.4k
Forks
394
PR merge metrics
No merged PRs in 30d

Description

I found a piece of code I want to use today that uses a macro to generate calls to `core::option_env!`; the reason is because it is a [fault injection] library, so the idea is you as a library user invoke the macro to get fault-injectable code, which creates a call to `option_env!`, which the compiler then runs and embeds the string into the binary.

[fault injection]: https://github.com/komora-io/fault-injection/blob/2ce6662c35e978c6b357467dae362b66133b48c5/src/lib.rs#L129-L133

The macro in question here is `CARGO_CRATE_NAME`, so the idea is crate "foobar_test" uses `failable!()` and then if a fault arises, you get a message containing the name `foobar_test` from everywhere else. If I use Reindeer to generate the build rules for `fault-injection` or not (it's a very simple library), it doesn't matter; it's my own buck2-only code that uses e.g. `rust_library` that needs that environment variable passed.

The [Cargo reference manual](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates) states these are defined as:

> - `CARGO_PKG_NAME` — The name of your package.
> ...
> - `CARGO_CRATE_NAME` — The name of the crate that is currently being compiled. It is the name of the [Cargo target](https://doc.rust-lang.org/cargo/reference/cargo-targets.html) with - converted to _, such as the name of the library, binary, example, integration test, or benchmark.

However, the *name* of the environment variables isn't really relevant. I could change that. I don't see any place something like this is passed through `rustc_action.py` or anything like that.

Would it be possible to provide `rust_library` and `rust_binary` compiled code some alternatives to these variables? Or do they exist already, perhaps? I also wouldn't mind something that told you what the target name of the crate itself was (e.g. `root//path/to:rust_binary`) either if we can manage it!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.