cargo_build_script incompatible with rust_toolchain using target_json

Abierto
#4,268 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 3 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
65/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
rust

Línea de trabajo

The issue is in cargo_build_script.bzl and cargo_build_script_runner/bin.rs. Start by examining the cargo_build_script rule implementation around line 468 and the runner's get_target_env_vars function. The fix involves checking if target_json is set and passing the JSON file path instead of the target triple, and adding -Zunstable-options when the target ends with .json. Run the provided reproduction steps to verify the fix works with a custom JSON target.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

needs-triage

Description

I am trying to use a tier-3 language, and defining the platform as a platform JSON.
It seems cargo_build_script cannot be used with a rust_toolchain that has target_json due to a type mismatch between literal and filename.

  • Current: analysis fails with Error in run: got dict<string, File> for 'env', want dict<string, string>.
  • Expected: build works with JSON targets.

Reproduction steps

MODULE.bazel:

module(name = "repro")
bazel_dep(name = "rules_rust", version = "0.74.0")
bazel_dep(name = "platforms", version = "1.1.0")
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.toolchain(edition = "2021", versions = ["nightly/2026-09-21"])
use_repo(rust, "rust_toolchains", "rust_linux_x86_64__x86_64-unknown-linux-gnu__nightly_tools")
register_toolchains("//:json_toolchain", "@rust_toolchains//:all")

BUILD.bazel:

load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
load("@rules_rust//rust:defs.bzl", "rust_binary")
load("@rules_rust//rust:toolchain.bzl", "rust_toolchain")
load(":target.bzl", "TARGET_JSON")

constraint_setting(name = "spec")
constraint_value(name = "json_spec", constraint_setting = ":spec")
platform(name = "json_platform", constraint_values = ["@platforms//cpu:x86_64", "@platforms//os:linux", ":json_spec"])

TOOLS = "@rust_linux_x86_64__x86_64-unknown-linux-gnu__nightly_tools"
rust_toolchain(
    name = "json_rust_toolchain",
    binary_ext = "", dylib_ext = ".so", staticlib_ext = ".a",
    exec_triple = "x86_64-unknown-linux-gnu",
    extra_rustc_flags = ["-Zunstable-options"],
    rust_doc = TOOLS + "//:rustdoc",
    rust_std = TOOLS + "//:rust_std-x86_64-unknown-linux-gnu",
    rustc = TOOLS + "//:rustc",
    rustc_lib = TOOLS + "//:rustc_lib",
    stdlib_linkflags = ["-ldl", "-lpthread"],
    target_json = TARGET_JSON,
)
toolchain(
    name = "json_toolchain",
    exec_compatible_with = ["@platforms//cpu:x86_64", "@platforms//os:linux"],
    target_compatible_with = ["@platforms//cpu:x86_64", "@platforms//os:linux", ":json_spec"],
    toolchain = ":json_rust_toolchain",
    toolchain_type = "@rules_rust//rust:toolchain_type",
)
cargo_build_script(name = "bs", srcs = ["build.rs"], edition = "2021")
rust_binary(name = "bin", srcs = ["main.rs"], edition = "2021", deps = [":bs"])

build.rs:

fn main() { println!("cargo:rustc-cfg=from_build_script"); }

main.rs:

fn main() { }

Trigger:

(echo 'TARGET_JSON = """'; rustc -Zunstable-options --print target-spec-json --target x86_64-unknown-linux-gnu; echo '"""') > target.bzl
bazel build //:bs --platforms=//:json_platform --@rules_rust//rust/toolchain/channel=nightly

Additional context

ERROR: /home/bluecmd/work/rust-repro/BUILD.bazel:30:19: in cargo_build_script rule //:bs: 
Traceback (most recent call last):
        File "/home/bluecmd/.cache/bazel/_bazel_bluecmd/ea14b543b17791a382a3d5f7ed953007/external/rules_rust+/cargo/private/cargo_build_script.bzl", line 703, column 20, in _cargo_build_script_impl
                ctx.actions.run(
Error in run: got dict<string, File> for 'env', want dict<string, string>
ERROR: /home/bluecmd/work/rust-repro/BUILD.bazel:30:19: Analysis of target '//:bs' (config: 63aac55) failed
ERROR: Analysis of target '//:bin' failed; build aborted: Analysis failed
INFO: Elapsed time: 33.434s, Critical Path: 0.06s
INFO: 1 process: 1 internal.
ERROR: Build did NOT complete successfully

Something like this might work?
Adding -Zunstable-options since the error without seems to want it; error loading target specification: custom targets are unstable and require -Zunstable-options".

--- a/cargo/private/cargo_build_script.bzl
+++ b/cargo/private/cargo_build_script.bzl
@@ -468,7 +468,7 @@
         "RUSTDOC": toolchain.rust_doc.path,
-        "TARGET": toolchain.target_flag_value,
+        "TARGET": toolchain.target_json.path if toolchain.target_json else toolchain.target_flag_value,
--- a/cargo/private/cargo_build_script_runner/bin.rs
+++ b/cargo/private/cargo_build_script_runner/bin.rs
@@ -505,12 +505,14 @@
 fn get_target_env_vars<P: AsRef<Path>>(rustc: &P) -> Result<BTreeMap<String, String>, String> {
-    let output = Command::new(rustc.as_ref())
-        .arg("--print=cfg")
-        .arg(format!(
-            "--target={}",
-            env::var("TARGET").expect("missing TARGET")
-        ))
+    let target = env::var("TARGET").expect("missing TARGET");
+    let mut command = Command::new(rustc.as_ref());
+    command.arg("--print=cfg").arg(format!("--target={target}"));
+    if target.ends_with(".json") {
+        command.arg("-Zunstable-options");
+    }
+    let output = command
         .output()

Impact

Blocks every crate with a build.rs on custom JSON targets.

Bazel and rules_rust version

Bazel 9.2.0, rules_rust 0.74.0

Lenguaje dominante
Starlark
Estrellas
857
Forks
701
Merge medio
4 d 7 h
PR fusionados (30 d)
46

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de bazelbuild/rules_rust

Todos los issues de bazelbuild/rules_rust

Issues similares

Más issues de Build System

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.