blob: 3849075ceb3ce76f8832e8c7d61058eeb767b48f [file]
# Copyright 2026 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Repository rule that discovers a host-installed Rust toolchain for bootstrapping."""
load("@rules_rust//rust/platform:triple.bzl", "triple")
load(
"@rules_rust//rust/platform:triple_mappings.bzl",
"system_to_binary_ext",
"system_to_dylib_ext",
"system_to_staticlib_ext",
"system_to_stdlib_linkflags",
"triple_to_constraint_set",
)
_RUSTC_SHARED_LIB_PREFIXES = (
"librustc",
"libLLVM",
"libstd-",
"libtest-",
"libz.",
)
_BUILD_TEMPLATE = """\
# Auto-generated by //scripts:local_rust_configure.bzl
load("@rules_rust//rust:rust_stdlib_filegroup.bzl", "rust_stdlib_filegroup")
load("@rules_rust//rust:rust_toolchain.bzl", "rust_toolchain")
filegroup(
name = "rustc",
srcs = ["bin/rustc{binary_ext}"],
visibility = ["//visibility:public"],
)
filegroup(
name = "rustdoc",
srcs = ["bin/rustdoc{binary_ext}"],
visibility = ["//visibility:public"],
)
filegroup(
name = "rustc_lib",
srcs = glob(
[
"bin/*{dylib_ext}",
"lib/*{dylib_ext}*",
"lib/rustlib/{host_triple}/codegen-backends/*{dylib_ext}",
],
allow_empty = True,
),
visibility = ["//visibility:public"],
)
rust_stdlib_filegroup(
name = "rust_std",
srcs = glob(
[
"lib/rustlib/{host_triple}/lib/*.rlib",
"lib/rustlib/{host_triple}/lib/*.rmeta",
"lib/rustlib/{host_triple}/lib/*{dylib_ext}*",
"lib/rustlib/{host_triple}/lib/*{staticlib_ext}",
"lib/rustlib/{host_triple}/lib/self-contained/**",
],
allow_empty = True,
),
visibility = ["//visibility:public"],
)
{rust_objcopy_target}{toolchains}"""
_TOOLCHAIN_TEMPLATE = """
# Keep the rust_toolchain target name short so generated sysroot `.rlib` paths
# stay under Windows's 260-character MAX_PATH limit.
rust_toolchain(
name = "{toolchain_name}",
binary_ext = {binary_ext_repr},
bootstrapping = {bootstrapping_repr},
channel = {channel_repr},
default_edition = "2024",
dylib_ext = {dylib_ext_repr},
exec_triple = {host_triple_repr},
process_wrapper = {process_wrapper_repr},
rust_doc = ":rustdoc",
rust_std = ":rust_std",
rustc = ":rustc",
rustc_lib = ":rustc_lib",
staticlib_ext = {staticlib_ext_repr},
stdlib_linkflags = {stdlib_linkflags_repr},
target_triple = {host_triple_repr},
version = {version_repr},
{rust_objcopy_kwarg}
)
toolchain(
name = "local_rust{suffix}",
exec_compatible_with = {constraints_repr},
target_compatible_with = {constraints_repr},
target_settings = ["@rules_rust//rust/private:{setting}"],
toolchain = ":{toolchain_name}",
toolchain_type = "@rules_rust//rust:toolchain_type",
visibility = ["//visibility:public"],
)
"""
def _find_rustc(repository_ctx):
rustc_env = repository_ctx.os.environ.get("RUSTC")
if rustc_env:
rustc = repository_ctx.path(rustc_env)
if not rustc.exists:
fail("RUSTC={} does not exist".format(rustc_env))
return rustc
rustc = repository_ctx.which("rustc")
if not rustc:
fail(
"Could not find `rustc` on PATH. Please install a Rust toolchain " +
"(e.g. via your system package manager or rustup) or set RUSTC.",
)
return rustc
def _impl(repository_ctx):
is_windows = repository_ctx.os.name.lower().startswith("windows")
exe_ext = ".exe" if is_windows else ""
rustc = _find_rustc(repository_ctx)
version_res = repository_ctx.execute([rustc, "-vV"])
if version_res.return_code != 0:
fail("Failed to run `{} -vV`:\n{}".format(rustc, version_res.stderr))
host_triple_str = None
release = ""
for line in version_res.stdout.splitlines():
if line.startswith("host:"):
host_triple_str = line.split(":", 1)[1].strip()
elif line.startswith("release:"):
release = line.split(":", 1)[1].strip()
if not host_triple_str:
fail("Could not determine host triple from `{} -vV`:\n{}".format(rustc, version_res.stdout))
# Prefer the parent directory of rustc if it already forms a complete
# sysroot (e.g. a symlinked sysroot where `rustc --print sysroot` would
# follow /proc/self/exe to a directory without rust-std).
candidate = rustc.dirname.dirname
cand_lib = candidate.get_child("lib").get_child("rustlib").get_child(host_triple_str).get_child("lib")
if cand_lib.exists and any([p.basename.endswith(".rlib") for p in cand_lib.readdir()]):
sysroot = candidate
else:
sysroot_res = repository_ctx.execute([rustc, "--print", "sysroot"])
if sysroot_res.return_code != 0:
fail("Failed to run `{} --print sysroot`:\n{}".format(rustc, sysroot_res.stderr))
sysroot = repository_ctx.path(sysroot_res.stdout.strip())
# Resolve past proxy shims (such as rustup's ~/.cargo/bin/rustc) so
# build actions invoke the real compiler directly.
real_rustc = sysroot.get_child("bin").get_child("rustc" + exe_ext)
if real_rustc.exists:
rustc = real_rustc
host_triple = triple(host_triple_str)
binary_ext = system_to_binary_ext(host_triple.system)
dylib_ext = system_to_dylib_ext(host_triple.system)
staticlib_ext = system_to_staticlib_ext(host_triple.system, abi = host_triple.abi)
stdlib_linkflags = system_to_stdlib_linkflags(host_triple.system, abi = host_triple.abi)
constraints = triple_to_constraint_set(host_triple_str)
if "-nightly" in release:
channel = "nightly"
elif "-beta" in release:
channel = "beta"
else:
channel = "stable"
# Symlink compiler binaries.
repository_ctx.symlink(rustc, "bin/rustc" + binary_ext)
rustdoc = sysroot.get_child("bin").get_child("rustdoc" + binary_ext)
if not rustdoc.exists:
rustdoc = rustc.dirname.get_child("rustdoc" + binary_ext)
repository_ctx.symlink(rustdoc if rustdoc.exists else rustc, "bin/rustdoc" + binary_ext)
# On Windows, rustc's shared libraries live alongside rustc.exe in bin/.
if is_windows:
sysroot_bin = sysroot.get_child("bin")
if sysroot_bin.exists:
for entry in sysroot_bin.readdir():
if not entry.is_dir and entry.basename.lower().endswith(".dll"):
repository_ctx.symlink(entry, "bin/" + entry.basename)
# Selectively symlink compiler shared libraries from lib/ so sysroot=/usr
# does not pull in unrelated system libraries.
llvm_libs = []
sysroot_lib = sysroot.get_child("lib")
if sysroot_lib.exists:
for entry in sysroot_lib.readdir():
if entry.is_dir:
continue
name = entry.basename
if (is_windows and name.lower().endswith(".dll")) or (not is_windows and name.startswith(_RUSTC_SHARED_LIB_PREFIXES)):
repository_ctx.symlink(entry, "lib/" + name)
if name.startswith("libLLVM"):
llvm_libs.append(entry)
# Symlink target standard library and auxiliary tools under lib/rustlib/<triple>/.
rustlib_triple = sysroot.get_child("lib").get_child("rustlib").get_child(host_triple_str)
rustlib_lib = rustlib_triple.get_child("lib")
if not rustlib_lib.exists:
fail("Rust standard library not found at {}".format(rustlib_lib))
existing_rustlib_libs = {}
for entry in rustlib_lib.readdir():
repository_ctx.symlink(entry, "lib/rustlib/{}/lib/{}".format(host_triple_str, entry.basename))
existing_rustlib_libs[entry.basename] = True
# rust-objcopy has RUNPATH=$ORIGIN/../lib, so mirror libLLVM* from <sysroot>/lib
# into lib/rustlib/<triple>/lib when not already present (e.g. rustup layouts).
for entry in llvm_libs:
if entry.basename not in existing_rustlib_libs:
repository_ctx.symlink(entry, "lib/rustlib/{}/lib/{}".format(host_triple_str, entry.basename))
codegen_backends = rustlib_triple.get_child("codegen-backends")
if codegen_backends.exists:
repository_ctx.symlink(codegen_backends, "lib/rustlib/{}/codegen-backends".format(host_triple_str))
rust_objcopy = rustlib_triple.get_child("bin").get_child("rust-objcopy" + binary_ext)
if rust_objcopy.exists:
repository_ctx.symlink(rust_objcopy, "lib/rustlib/{}/bin/rust-objcopy{}".format(host_triple_str, binary_ext))
rust_objcopy_target = """
filegroup(
name = "rust_objcopy",
srcs = ["lib/rustlib/{host_triple}/bin/rust-objcopy{binary_ext}"],
visibility = ["//visibility:public"],
)
""".format(host_triple = host_triple_str, binary_ext = binary_ext)
rust_objcopy_kwarg = 'rust_objcopy = ":rust_objcopy",'
else:
rust_objcopy_target = ""
# Disable debuginfo stripping in -c opt when host lacks rust-objcopy.
rust_objcopy_kwarg = 'strip_level = {"dbg": "none", "fastbuild": "none", "opt": "none"},'
toolchains = "".join([
_TOOLCHAIN_TEMPLATE.format(
binary_ext_repr = repr(binary_ext),
bootstrapping_repr = repr(bootstrapping),
channel_repr = repr(channel),
constraints_repr = repr(constraints),
dylib_ext_repr = repr(dylib_ext),
host_triple_repr = repr(host_triple_str),
process_wrapper_repr = repr(process_wrapper),
rust_objcopy_kwarg = rust_objcopy_kwarg,
setting = setting,
staticlib_ext_repr = repr(staticlib_ext),
stdlib_linkflags_repr = repr(stdlib_linkflags),
suffix = suffix,
toolchain_name = toolchain_name,
version_repr = repr(release),
)
for suffix, toolchain_name, bootstrapping, process_wrapper, setting in [
("_bootstrap", "b", True, "@rules_rust//util/process_wrapper:bootstrap_process_wrapper", "bootstrapping"),
("", "t", False, "@rules_rust//util/process_wrapper", "bootstrapped"),
]
])
repository_ctx.file(
"BUILD.bazel",
content = _BUILD_TEMPLATE.format(
binary_ext = binary_ext,
dylib_ext = dylib_ext,
host_triple = host_triple_str,
rust_objcopy_target = rust_objcopy_target,
staticlib_ext = staticlib_ext,
toolchains = toolchains,
),
executable = False,
)
return repository_ctx.repo_metadata(reproducible = False)
local_rust_configure = repository_rule(
implementation = _impl,
local = True,
environ = [
"PATH",
"RUSTC",
"RUSTUP_HOME",
"RUSTUP_TOOLCHAIN",
],
)