bazelbuild / rules_rust

Rust rules for Bazel
https://bazelbuild.github.io/rules_rust/
Apache License 2.0
650 stars 409 forks source link

Set the same env vars as cargo both when invoking rustc and when invoking a cargo_build_script #661

Open illicitonion opened 3 years ago

illicitonion commented 3 years ago

Cargo sets this list of env vars when either invoking rustc, or cargo runing or cargo testing a binary. We should be setting them all when we invoke rustc.

Cargo additionally sets this list of env vars when running (not when compiling) a build script. We should be setting them all when we invoke a build script. We should also be setting all of the rustc env vars when we invoke a build script.

Currently we have two lists of env vars:

This list is used for when we invoke rustc: https://github.com/bazelbuild/rules_rust/blob/e744b93f5e6fa21b2c4ee2e49e984e7402df9e46/rust/private/rustc.bzl#L57-L85

This list is used when we invoke an already-compiled build-script (note that we use the above list when compiling the build script): https://github.com/bazelbuild/rules_rust/blob/e744b93f5e6fa21b2c4ee2e49e984e7402df9e46/cargo/cargo_build_script.bzl#L79-L132

Both of these lists are currently incomplete, as we've generally added stuff as-needed. Additionally, the rustc_env list contains some vars which should actually only be in the build_script list (e.g. CARGO_CFG_TARGET_ARCH and CARGO_CFG_TARGET_OS).

We should:

  1. Make the build script env vars be a superset of the rustc ones, by calling _get_rustc_env from _build_script_impl. This will both help keep the lists in sync, and avoid duplicating things like the processing of version numbers.
  2. Move any build_script-specific env vars out of _get_rustc_env
  3. (Optional): Add more env vars pro-actively, rather than reactively when someone finds some third-party code doesn't build.
bbstilson commented 6 months ago

Related to:

Add more env vars pro-actively, rather than reactively when someone finds some third-party code doesn't build.

I've hit an issue compiling a sqlx query! macro as the CARGO env var is not set by rules_rust and is required by the macro

Any interim suggestions about how to get around this would be appreciated 🙂

illicitonion commented 6 months ago

$CARGO is definitely a tricky one. In the short term, you can probably add an annotation setting build_script_data to @rules_rust//rust/toolchain:current_cargo_files and setting build_script_env to {"CARGO": "$(execpath @rules_rust//rust/toolchain:current_cargo_files)"}. But in general, any time a build script tries to use cargo directly, it's likely to be doing something that won't be exactly compatible with how Bazel runs things.