Rules Rust
This repository provides rules for building Rust projects with Bazel.
Setup
The rules are released, and releases can be found on the GitHub Releases page. We recommend using the latest release from that page.
To use rules_rust in a project, add the following to your MODULE.bazel file:
bazel_dep(name = "rules_rust", version = "0.70.0")
Don't forget to substitute in your desired release's version number.
Specifying Rust version
To use a particular version of the Rust compiler, pass that version to the toolchain method of the rust extension, like this:
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.toolchain(
edition = "2024",
versions = [ "1.85.0" ],
)
As well as an exact version, versions can accept nightly/{iso_date} and beta/{iso_date} strings for toolchains from different release channels, as in
rust.toolchain(
edition = "2021",
versions = [ "nightly/1.85.0" ],
)
By default, a stable and nightly toolchain will be registered if no toolchain method is called (and thus no specific versions are registered). However, if only 1 version is passed and it is from the nightly or beta release channels (i.e. not stable), then the following build setting flag must be present, either on the command line or set in the project's .bazelrc file:
build --@rules_rust//rust/toolchain/channel=nightly
Failure to do so will result in rules attempting to match a stable toolchain when one was not registered, thus raising an error.
Supported bazel versions
The oldest version of Bazel the main branch is tested against is 7.4.1. Previous versions may still be functional in certain environments, but this is the minimum version we strive to fully support.
We test these rules against the latest rolling releases of Bazel, and aim for compatibility with them, but prioritise stable releases over rolling releases where necessary.
Supported platforms
We aim to support Linux and macOS.
We do not have sufficient maintainer expertise to support Windows. Most things probably work, but we have had to disable many tests in CI because we lack the expertise to fix them. We welcome contributions to help improve its support.
Rules
- defs: standard rust rules for building and testing libraries and binaries.
- rustdoc: rules for generating and testing rust documentation.
- clippy: rules for running clippy.
- rustfmt: rules for running rustfmt.
- cargo: Rules dedicated to Cargo compatibility. ie:
build.rsscripts. - crate_universe: Rules for generating Bazel targets for external crate dependencies.
Experimental rules
- rust_analyzer: rules for generating
rust-project.jsonfiles for rust-analyzer
3rd party rules
- rust_bindgen: rules for generating C++ bindings.
- rust_prost: rules for generating protobuf and gRPC stubs using prost.
- rust_pyo3: Bazel rules for PyO3.
- rust_wasm_bindgen: rules for generating WebAssembly bindings.
Public entry point to all Rust rules and supported APIs.
Rules
- rust_binary
- rust_library
- rust_library_group
- rust_lint_config
- rust_proc_macro
- rust_shared_library
- rust_static_library
- rust_test
- rust_unpretty
Functions
Aspects
rust_binary
load("@rules_rust//rust:defs.bzl", "rust_binary")
rust_binary(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, binary_name,
compile_data, crate_features, crate_name, crate_root, crate_type, edition, env,
experimental_use_cc_common_link, linker_script, lint_config, malloc, platform,
proc_macro_deps, require_explicit_unstable_features, rustc_env, rustc_env_files,
rustc_flags, stamp, unstable_rust_features_config, version)
Builds a Rust binary crate.
Example:
Suppose you have the following directory structure for a Rust project with a
library crate, hello_lib, and a binary crate, hello_world that uses the
hello_lib library:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
lib.rs
hello_world/
BUILD
src/
main.rs
hello_lib/src/lib.rs:
#![allow(unused)] fn main() { pub struct Greeter { greeting: String, } impl Greeter { pub fn new(greeting: &str) -> Greeter { Greeter { greeting: greeting.to_string(), } } pub fn greet(&self, thing: &str) { println!("{} {}", &self.greeting, thing); } } }
hello_lib/BUILD:
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_library")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
hello_world/src/main.rs:
extern crate hello_lib; fn main() { let hello = hello_lib::Greeter::new("Hello"); hello.greet("world"); }
hello_world/BUILD:
load("@rules_rust//rust:defs.bzl", "rust_binary")
rust_binary(
name = "hello_world",
srcs = ["src/main.rs"],
deps = ["//hello_lib"],
)
Build and run hello_world:
$ bazel run //hello_world
INFO: Found 1 target...
Target //examples/rust/hello_world:hello_world up-to-date:
bazel-bin/examples/rust/hello_world/hello_world
INFO: Elapsed time: 1.308s, Critical Path: 1.22s
INFO: Running command line: bazel-bin/examples/rust/hello_world/hello_world
Hello world
On Windows, a PDB file containing debugging information is available under
the key pdb_file in OutputGroupInfo. Similarly on macOS, a dSYM folder
is available under the key dsym_folder in OutputGroupInfo.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| binary_name | Override the resulting binary file name. By default, the binary file will be named using the name attribute on this rule, however sometimes that is not deseriable. | String | optional | "" |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| crate_type | Crate type that will be passed to rustc to be used for building this crate.This option is a temporary workaround and should be used only when building for WebAssembly targets (//rust/platform:wasi and //rust/platform:wasm). | String | optional | "bin" |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| env | Specifies additional environment variables to set when the target is executed by bazel run. Values are subject to $(rootpath), $(execpath), location, and "Make variable" substitution.Execpath returns absolute path, and in order to be able to construct the absolute path we need to wrap the test binary in a launcher. Using a launcher comes with complications, such as more complicated debugger attachment. | Dictionary: String -> String | optional | {} |
| experimental_use_cc_common_link | Whether to use cc_common.link to link rust binaries. Possible values: [-1, 0, 1]. -1 means use the value of the toolchain.experimental_use_cc_common_link boolean build setting to determine. 0 means do not use cc_common.link (use rustc instead). 1 means use cc_common.link. | Integer | optional | -1 |
| linker_script | Link script to forward into linker via rustc options. | Label | optional | None |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| malloc | Override the default dependency on malloc.By default, Rust binaries linked with cc_common.link are linked against @rules_rust//rust/private/cc:malloc, which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule. | Label | optional | "@rules_rust//rust/private/cc:malloc" |
| platform | Optional platform to transition the static library to. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | -1 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_library
load("@rules_rust//rust:defs.bzl", "rust_library")
rust_library(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data,
crate_features, crate_name, crate_root, disable_pipelining, edition, lint_config,
proc_macro_deps, require_explicit_unstable_features, rustc_env, rustc_env_files,
rustc_flags, stamp, unstable_rust_features_config, version)
Builds a Rust library crate.
Example:
Suppose you have the following directory structure for a simple Rust library crate:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
greeter.rs
lib.rs
hello_lib/src/greeter.rs:
#![allow(unused)] fn main() { pub struct Greeter { greeting: String, } impl Greeter { pub fn new(greeting: &str) -> Greeter { Greeter { greeting: greeting.to_string(), } } pub fn greet(&self, thing: &str) { println!("{} {}", &self.greeting, thing); } } }
hello_lib/src/lib.rs:
#![allow(unused)] fn main() { pub mod greeter; }
hello_lib/BUILD:
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_library")
rust_library(
name = "hello_lib",
srcs = [
"src/greeter.rs",
"src/lib.rs",
],
)
Build the library:
$ bazel build //hello_lib
INFO: Found 1 target...
Target //examples/rust/hello_lib:hello_lib up-to-date:
bazel-bin/examples/rust/hello_lib/libhello_lib.rlib
INFO: Elapsed time: 1.245s, Critical Path: 1.01s
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| disable_pipelining | Disables pipelining for this rule if it is globally enabled. This will cause this rule to not produce a .rmeta file and all the dependent crates will instead use the .rlib file. | Boolean | optional | False |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | 0 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_library_group
load("@rules_rust//rust:defs.bzl", "rust_library_group")
rust_library_group(name, deps)
Functions as an alias for a set of dependencies.
Specifically, the following are equivalent:
rust_library_group(
name = "crate_group",
deps = [
":crate1",
":crate2",
],
)
rust_library(
name = "foobar",
deps = [":crate_group"],
...
)
and
rust_library(
name = "foobar",
deps = [
":crate1",
":crate2",
],
...
)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | Other dependencies to forward through this crate group. | List of labels | optional | [] |
rust_lint_config
load("@rules_rust//rust:defs.bzl", "rust_lint_config")
rust_lint_config(name, clippy, rustc, rustc_check_cfg, rustdoc)
Defines a group of lints that can be applied when building Rust targets.
For example, you can define a single group of lints:
load("@rules_rust//rust:defs.bzl", "rust_lint_config")
rust_lint_config(
name = "workspace_lints",
rustc = {
"unknown_lints": "allow",
"unexpected_cfgs": "warn",
},
rustc_check_cfg = {
"bazel": [],
"fuzzing": [],
"mz_featutres": ["laser", "rocket"],
},
clippy = {
"box_default": "allow",
"todo": "warn",
"unused_async": "warn",
},
rustdoc = {
"unportable_markdown": "allow",
},
)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| clippy | Set of 'clippy' lints to 'allow', 'expect', 'warn', 'force-warn', 'deny', or 'forbid'. | Dictionary: String -> String | optional | {} |
| rustc | Set of 'rustc' lints to 'allow', 'expect', 'warn', 'force-warn', 'deny', or 'forbid'. | Dictionary: String -> String | optional | {} |
| rustc_check_cfg | Set of 'cfg' names and list of values to expect. | Dictionary: String -> List of strings | optional | {} |
| rustdoc | Set of 'rustdoc' lints to 'allow', 'expect', 'warn', 'force-warn', 'deny', or 'forbid'. | Dictionary: String -> String | optional | {} |
rust_proc_macro
load("@rules_rust//rust:defs.bzl", "rust_proc_macro")
rust_proc_macro(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data,
crate_features, crate_name, crate_root, edition, lint_config, proc_macro_deps,
require_explicit_unstable_features, rustc_env, rustc_env_files, rustc_flags, stamp,
unstable_rust_features_config, version)
Builds a Rust proc-macro crate.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | 0 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_shared_library
load("@rules_rust//rust:defs.bzl", "rust_shared_library")
rust_shared_library(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data,
crate_features, crate_name, crate_root, edition, experimental_use_cc_common_link,
lint_config, malloc, platform, proc_macro_deps,
require_explicit_unstable_features, rustc_env, rustc_env_files, rustc_flags,
stamp, unstable_rust_features_config, version)
Builds a Rust shared library.
This shared library will contain all transitively reachable crates and native objects. It is meant to be used when producing an artifact that is then consumed by some other build system (for example to produce a shared library that Python program links against).
This rule provides CcInfo, so it can be used everywhere Bazel expects rules_cc.
When building the whole binary in Bazel, use rust_library instead.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| experimental_use_cc_common_link | Whether to use cc_common.link to link rust binaries. Possible values: [-1, 0, 1]. -1 means use the value of the toolchain.experimental_use_cc_common_link boolean build setting to determine. 0 means do not use cc_common.link (use rustc instead). 1 means use cc_common.link. | Integer | optional | -1 |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| malloc | Override the default dependency on malloc.By default, Rust binaries linked with cc_common.link are linked against @rules_rust//rust/private/cc:malloc, which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule. | Label | optional | "@rules_rust//rust/private/cc:malloc" |
| platform | Optional platform to transition the static library to. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | 0 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_static_library
load("@rules_rust//rust:defs.bzl", "rust_static_library")
rust_static_library(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data,
crate_features, crate_name, crate_root, edition, lint_config, platform,
proc_macro_deps, require_explicit_unstable_features, rustc_env, rustc_env_files,
rustc_flags, stamp, unstable_rust_features_config, version)
Builds a Rust static library.
This static library will contain all transitively reachable crates and native objects. It is meant to be used when producing an artifact that is then consumed by some other build system (for example to produce an archive that Python program links against).
This rule provides CcInfo, so it can be used everywhere Bazel expects rules_cc.
When building the whole binary in Bazel, use rust_library instead.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| platform | Optional platform to transition the static library to. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | 0 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_test
load("@rules_rust//rust:defs.bzl", "rust_test")
rust_test(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data, crate,
crate_features, crate_name, crate_root, edition, env, env_inherit,
experimental_use_cc_common_link, lint_config, malloc, platform, proc_macro_deps,
require_explicit_unstable_features, rustc_env, rustc_env_files, rustc_flags, stamp,
unstable_rust_features_config, use_libtest_harness, version)
Builds a Rust test crate.
Examples:
Suppose you have the following directory structure for a Rust library crate with unit test code in the library sources:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
lib.rs
hello_lib/src/lib.rs:
#![allow(unused)] fn main() { pub struct Greeter { greeting: String, } impl Greeter { pub fn new(greeting: &str) -> Greeter { Greeter { greeting: greeting.to_string(), } } pub fn greet(&self, thing: &str) -> String { format!("{} {}", &self.greeting, thing) } } #[cfg(test)] mod test { use super::Greeter; #[test] fn test_greeting() { let hello = Greeter::new("Hi"); assert_eq!("Hi Rust", hello.greet("Rust")); } } }
To build and run the tests, simply add a rust_test rule with no srcs
and only depends on the hello_lib rust_library target via the
crate attribute:
hello_lib/BUILD:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "hello_lib_test",
crate = ":hello_lib",
# You may add other deps that are specific to the test configuration
deps = ["//some/dev/dep"],
)
Run the test with bazel test //hello_lib:hello_lib_test.
Example: test directory
Integration tests that live in the tests directory, they are essentially built as separate crates. Suppose you have the following directory structure where greeting.rs is an integration test for the hello_lib library crate:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
lib.rs
tests/
greeting.rs
hello_lib/tests/greeting.rs:
#![allow(unused)] fn main() { extern crate hello_lib; use hello_lib; #[test] fn test_greeting() { let hello = greeter::Greeter::new("Hello"); assert_eq!("Hello world", hello.greeting("world")); } }
To build the greeting.rs integration test, simply add a rust_test target
with greeting.rs in srcs and a dependency on the hello_lib target:
hello_lib/BUILD:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Run the test with bazel test //hello_lib:greeting_test.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| srcs | List of Rust .rs source files used to build the library.If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate. | List of labels | optional | [] |
| data | List of files used by this rule at compile time and runtime. If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles. | List of labels | optional | [] |
| aliases | Remap crates to a new name or moniker for linkage to this target These are other rust_library targets and will be presented as the new name given. | Dictionary: Label -> String | optional | {} |
| allocator_libraries | - | Label | optional | "@rules_rust//ffi/rs:default_allocator_libraries" |
| alwayslink | If 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary. This attribute is used by the C++ Starlark API when passing CcInfo providers. | Boolean | optional | False |
| compile_data | List of files used by this rule at compile time. This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro. | List of labels | optional | [] |
| crate | Target inline tests declared in the given crate These tests are typically those that would be held out under #[cfg(test)] declarations. | Label | optional | None |
| crate_features | List of features to enable for this crate. Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags. | List of strings | optional | [] |
| crate_name | Crate name to use for this target. This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores. | String | optional | "" |
| crate_root | The file that will be passed to rustc to be used for building this crate.If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file. | Label | optional | None |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. | String | optional | "" |
| env | Specifies additional environment variables to set when the test is executed by bazel test. Values are subject to $(rootpath), $(execpath), location, and "Make variable" substitution. | Dictionary: String -> String | optional | {} |
| env_inherit | Specifies additional environment variables to inherit from the external environment when the test is executed by bazel test. | List of strings | optional | [] |
| experimental_use_cc_common_link | Whether to use cc_common.link to link rust binaries. Possible values: [-1, 0, 1]. -1 means use the value of the toolchain.experimental_use_cc_common_link boolean build setting to determine. 0 means do not use cc_common.link (use rustc instead). 1 means use cc_common.link. | Integer | optional | -1 |
| lint_config | Set of lints to apply when building this crate. | Label | optional | None |
| malloc | Override the default dependency on malloc.By default, Rust binaries linked with cc_common.link are linked against @rules_rust//rust/private/cc:malloc, which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule. | Label | optional | "@rules_rust//rust/private/cc:malloc" |
| platform | Optional platform to transition the static library to. | Label | optional | None |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| require_explicit_unstable_features | Whether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True. | Integer | optional | -1 |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc.rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more. | Dictionary: String -> String | optional | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged. Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}. | List of labels | optional | [] |
| rustc_flags | List of compiler flags passed to rustc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
| stamp | Whether to encode build information into the Rustc action. Possible values:- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.- stamp = 0: Always replace build information by constant values. This gives good build result caching.- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.Stamped targets are not rebuilt unless their dependencies change. For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves. | Integer | optional | 0 |
| unstable_rust_features_config | Controls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain. | Label | optional | None |
| use_libtest_harness | Whether to use libtest. For targets using this flag, individual tests can be run by using the --test_arg flag. E.g. bazel test //src:rust_test --test_arg=foo::test::test_fn. | Boolean | optional | True |
| version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_unpretty
load("@rules_rust//rust:defs.bzl", "rust_unpretty")
rust_unpretty(name, deps, mode)
Executes rust unpretty on a specific target.
Similar to rust_unpretty_aspect, but allows specifying a list of dependencies within the build system.
For example, given the following example targets:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Rust expand can be set as a build target with the following:
load("@rules_rust//rust:defs.bzl", "rust_unpretty")
rust_unpretty(
name = "hello_library_expand",
testonly = True,
deps = [
":hello_lib",
":greeting_test",
],
mode = "expand",
)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | Rust targets to run unpretty on. | List of labels | optional | [] |
| mode | The value to pass to --unpretty | String | optional | "expanded" |
rust_test_suite
load("@rules_rust//rust:defs.bzl", "rust_test_suite")
rust_test_suite(name, srcs, shared_srcs, **kwargs)
A rule for creating a test suite for a set of rust_test targets.
This rule can be used for setting up typical rust integration tests. Given the following directory structure:
[crate]/
BUILD.bazel
src/
lib.rs
main.rs
tests/
integrated_test_a.rs
integrated_test_b.rs
integrated_test_c.rs
patterns/
fibonacci_test.rs
helpers/
mod.rs
The rule can be used to generate rust_test targets for each source file under tests
and a test_suite which encapsulates all tests.
load("//rust:defs.bzl", "rust_binary", "rust_library", "rust_test_suite")
rust_library(
name = "math_lib",
srcs = ["src/lib.rs"],
)
rust_binary(
name = "math_bin",
srcs = ["src/main.rs"],
)
rust_test_suite(
name = "integrated_tests_suite",
srcs = glob(["tests/**"]),
shared_srcs=glob(["tests/helpers/**"]),
deps = [":math_lib"],
)
PARAMETERS
| Name | Description | Default Value |
|---|---|---|
| name | The name of the test_suite. | none |
| srcs | All test sources, typically glob(["tests/**/*.rs"]). | none |
| shared_srcs | Optional argument for sources shared among tests, typically helper functions. | [] |
| kwargs | Additional keyword arguments for the underlying rust_test targets. The tags argument is also passed to the generated test_suite target. | none |
rust_unpretty_aspect
load("@rules_rust//rust:defs.bzl", "rust_unpretty_aspect")
rust_unpretty_aspect()
Executes Rust expand on specified targets.
This aspect applies to existing rust_library, rust_test, and rust_binary rules.
As an example, if the following is defined in examples/hello_lib/BUILD.bazel:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Then the targets can be expanded with the following command:
$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_unpretty_aspect \
--output_groups=rust_unpretty_expanded \
//hello_lib:all
ASPECT ATTRIBUTES
ATTRIBUTES
Overview
Clippy is a tool for catching common mistakes in Rust code and improving it. An expansive list of lints and the justification can be found in their documentation.
Setup
Simply add the following to the .bazelrc file in the root of your workspace:
build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect
build --output_groups=+clippy_checks
This will enable clippy on all Rust targets.
Note that targets tagged with no-clippy will not perform clippy checks
To use a local clippy.toml, add the following flag to your .bazelrc. Note that due to
the upstream implementation of clippy, this file must be named either .clippy.toml or
clippy.toml. Using a custom config file requires Rust 1.34.0 or newer.
build --@rules_rust//rust/settings:clippy.toml=//:clippy.toml
Rules
Aspects
rust_clippy
load("@rules_rust//rust:defs.bzl", "rust_clippy")
rust_clippy(name, deps)
Executes the clippy checker on a specific target.
Similar to rust_clippy_aspect, but allows specifying a list of dependencies within the build system.
For example, given the following example targets:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Rust clippy can be set as a build target with the following:
load("@rules_rust//rust:defs.bzl", "rust_clippy")
rust_clippy(
name = "hello_library_clippy",
testonly = True,
deps = [
":hello_lib",
":greeting_test",
],
)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | Rust targets to run clippy on. | List of labels | optional | [] |
rust_clippy_aspect
load("@rules_rust//rust:defs.bzl", "rust_clippy_aspect")
rust_clippy_aspect()
Executes the clippy checker on specified targets.
This aspect applies to existing rust_library, rust_test, and rust_binary rules.
As an example, if the following is defined in examples/hello_lib/BUILD.bazel:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Then the targets can be analyzed with clippy using the following command:
$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect --output_groups=clippy_checks //hello_lib:all
ASPECT ATTRIBUTES
ATTRIBUTES
Overview
Rustfmt is a tool for formatting Rust code according to style guidelines. By default, Rustfmt uses a style which conforms to the Rust style guide that has been formalized through the style RFC process. A complete list of all configuration options can be found in the Rustfmt GitHub Pages.
Setup
Formatting your Rust targets' source code requires no setup outside of loading rules_rust
in your workspace. Simply run bazel run @rules_rust//:rustfmt to format source code.
In addition to this formatter, a simple check can be performed using the rustfmt_aspect aspect by running
bazel build --aspects=@rules_rust//rust:defs.bzl%rustfmt_aspect --output_groups=rustfmt_checks
Add the following to a .bazelrc file to enable this check during the build phase.
build --aspects=@rules_rust//rust:defs.bzl%rustfmt_aspect
build --output_groups=+rustfmt_checks
It's recommended to only enable this aspect in your CI environment so formatting issues do not impact user's ability to rapidly iterate on changes.
The rustfmt_aspect also uses a --@rules_rust//rust/settings:rustfmt.toml setting which determines the
configuration file used by the formatter (@rules_rust//tools/rustfmt) and the aspect
(rustfmt_aspect). This flag can be added to your .bazelrc file to ensure a consistent config
file is used whenever rustfmt is run:
build --@rules_rust//rust/settings:rustfmt.toml=//:rustfmt.toml
Tips
Any target which uses Bazel generated sources will cause the @rules_rust//tools/rustfmt tool to fail with
failed to resolve mod `MOD` . To avoid failures, skip_children = true
is recommended to be set in the workspace's rustfmt.toml file which allows rustfmt to run on these targets
without failing.
Rules
Aspects
rustfmt_test
load("@rules_rust//rust:defs.bzl", "rustfmt_test")
rustfmt_test(name, targets)
A test rule for performing rustfmt --check on a set of targets
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| targets | Rust targets to run rustfmt --check on. | List of labels | optional | [] |
rustfmt_aspect
load("@rules_rust//rust:defs.bzl", "rustfmt_aspect")
rustfmt_aspect()
This aspect is used to gather information about a crate for use in rustfmt and perform rustfmt checks
Output Groups:
rustfmt_checks: Executesrustfmt --checkon the specified target.
The build setting @rules_rust//rust/settings:rustfmt.toml is used to control the Rustfmt configuration settings
used at runtime.
This aspect is executed on any target which provides the CrateInfo provider. However
users may tag a target with no-rustfmt or no-format to have it skipped. Additionally,
generated source files are also ignored by this aspect.
ASPECT ATTRIBUTES
ATTRIBUTES
Public entry point to all Rust rules and supported APIs.
Rules
rust_doc
load("@rules_rust//rust:defs.bzl", "rust_doc")
rust_doc(name, crate, crate_features, html_after_content, html_before_content, html_in_header,
markdown_css, rustc_flags, rustdoc_flags)
Generates code documentation.
Example: Suppose you have the following directory structure for a Rust library crate:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
lib.rs
To build rustdoc documentation for the hello_lib crate, define a rust_doc rule that depends on the the hello_lib rust_library target:
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_doc")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_doc(
name = "hello_lib_doc",
crate = ":hello_lib",
)
Running bazel build //hello_lib:hello_lib_doc will build a zip file containing the documentation for the hello_lib library crate generated by rustdoc.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| crate | The label of the target to generate code documentation for.rust_doc can generate HTML code documentation for the source files of rust_library or rust_binary targets. | Label | required | |
| crate_features | List of features to enable for the crate being documented. | List of strings | optional | [] |
| html_after_content | File to add in <body>, after content. | Label | optional | None |
| html_before_content | File to add in <body>, before content. | Label | optional | None |
| html_in_header | File to add to <head>. | Label | optional | None |
| markdown_css | CSS files to include via <link> in a rendered Markdown file. | List of labels | optional | [] |
| rustc_flags | Deprecated: use rustdoc_flags instead | List of strings | optional | [] |
| rustdoc_flags | List of flags passed to rustdoc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
rust_doc_test
load("@rules_rust//rust:defs.bzl", "rust_doc_test")
rust_doc_test(name, deps, crate, crate_features, proc_macro_deps, rustdoc_flags)
Runs Rust documentation tests.
Example:
Suppose you have the following directory structure for a Rust library crate:
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
lib.rs
To run documentation tests for the hello_lib crate, define a rust_doc_test target that depends on the hello_lib rust_library target:
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_doc_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_doc_test(
name = "hello_lib_doc_test",
crate = ":hello_lib",
)
Running bazel test //hello_lib:hello_lib_doc_test will run all documentation tests for the hello_lib library crate.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | List of other libraries to be linked to this library target. These can be either other rust_library targets or cc_library targets if linking a native library. | List of labels | optional | [] |
| crate | The label of the target to generate code documentation for. rust_doc_test can generate HTML code documentation for the source files of rust_library or rust_binary targets. | Label | required | |
| crate_features | List of features to enable for the crate being documented. | List of strings | optional | [] |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
| rustdoc_flags | List of flags passed to rustdoc.These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target). | List of strings | optional | [] |
Cargo
Common definitions for the @rules_rust//cargo package
Rules
Functions
Repository Rules
cargo_dep_env
load("@rules_rust//cargo:defs.bzl", "cargo_dep_env")
cargo_dep_env(name, src, out_dir)
A rule for generating variables for dependent cargo_build_scripts without a build script. This is useful for using Bazel rules instead of a build script, while also generating configuration information for build scripts which depend on this crate.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| src | File containing additional environment variables to set for build scripts of direct dependencies. This has the same effect as a cargo_build_script which prints cargo:VAR=VALUE lines, but without requiring a build script.This files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\). | Label | required | |
| out_dir | Folder containing additional inputs when building all direct dependencies. This has the same effect as a cargo_build_script which prints puts files into $OUT_DIR, but without requiring a build script. | Label | optional | None |
extract_cargo_lints
load("@rules_rust//cargo:defs.bzl", "extract_cargo_lints")
extract_cargo_lints(name, manifest, workspace)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| manifest | Cargo.toml to read lints from. | Label | required | |
| workspace | Workspace Cargo.toml that the manifest Cargo.toml inherits from. | Label | optional | None |
cargo_build_script
load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
cargo_build_script(*, name, edition, crate_name, crate_root, srcs, crate_features, version, deps,
link_deps, proc_macro_deps, build_script_env, build_script_env_files,
use_default_shell_env, data, compile_data, tools, links, rundir, rustc_env,
rustc_env_files, rustc_flags, visibility, tags, aliases, pkg_name, **kwargs)
Compile and execute a rust build script to generate build attributes
This rules take the same arguments as rust_binary.
Example:
Suppose you have a crate with a cargo build script build.rs:
[workspace]/
hello_lib/
BUILD
build.rs
src/
lib.rs
Then you want to use the build script in the following:
hello_lib/BUILD:
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
# This will run the build script from the root of the workspace, and
# collect the outputs.
cargo_build_script(
name = "build_script",
srcs = ["build.rs"],
# Optional environment variables passed during build.rs compilation
rustc_env = {
"CARGO_PKG_VERSION": "0.1.2",
},
# Optional environment variables passed during build.rs execution.
# Note that as the build script's working directory is not execroot,
# execpath/location will return an absolute path, instead of a relative
# one.
build_script_env = {
"SOME_TOOL_OR_FILE": "$(execpath @tool//:binary)"
},
# Optional data/tool dependencies
data = ["@tool//:binary"],
)
rust_library(
name = "hello_lib",
srcs = [
"src/lib.rs",
],
deps = [":build_script"],
)
The hello_lib target will be build with the flags and the environment variables declared by the build script in addition to the file generated by it.
PARAMETERS
cargo_env
load("@rules_rust//cargo:defs.bzl", "cargo_env")
cargo_env(env)
A helper for generating platform specific environment variables
load("@rules_rust//rust:defs.bzl", "rust_common")
load("@rules_rust//cargo:defs.bzl", "cargo_bootstrap_repository", "cargo_env")
cargo_bootstrap_repository(
name = "bootstrapped_bin",
cargo_lockfile = "//:Cargo.lock",
cargo_toml = "//:Cargo.toml",
srcs = ["//:resolver_srcs"],
version = rust_common.default_version,
binary = "my-crate-binary",
env = {
"x86_64-unknown-linux-gnu": cargo_env({
"FOO": "BAR",
}),
},
env_label = {
"aarch64-unknown-linux-musl": cargo_env({
"DOC": "//:README.md",
}),
}
)
PARAMETERS
RETURNS
str: A json encoded string of the environment variables
cargo_bootstrap_repository
load("@rules_rust//cargo:defs.bzl", "cargo_bootstrap_repository")
cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_config, cargo_lockfile, cargo_toml,
compressed_windows_toolchain_names, env, env_label,
rust_toolchain_cargo_template, rust_toolchain_rustc_template, timeout,
version)
A rule for bootstrapping a Rust binary using Cargo
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this repository. | Name | required | |
| srcs | Source files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made | List of labels | optional | [] |
| binary | The binary to build (the --bin parameter for Cargo). If left empty, the repository name will be used. | String | optional | "" |
| build_mode | The build mode the binary should be built with | String | optional | "release" |
| cargo_config | The path of the Cargo configuration (Config.toml) file. | Label | optional | None |
| cargo_lockfile | The lockfile of the crate_universe resolver | Label | required | |
| cargo_toml | The path of the Cargo.toml file. | Label | required | |
| compressed_windows_toolchain_names | Whether or not the toolchain names of windows toolchains are expected to be in a compressed format. | Boolean | optional | True |
| env | A mapping of platform triple to a set of environment variables. See cargo_env for usage details. Additionally, the platform triple * applies to all platforms. | Dictionary: String -> String | optional | {} |
| env_label | A mapping of platform triple to a set of environment variables. This attribute differs from env in that all variables passed here must be fully qualified labels of files. See cargo_env for usage details. Additionally, the platform triple * applies to all platforms. | Dictionary: String -> String | optional | {} |
| rust_toolchain_cargo_template | The template to use for finding the host cargo binary. {version} (eg. '1.53.0'), {triple} (eg. 'x86_64-unknown-linux-gnu'), {arch} (eg. 'aarch64'), {vendor} (eg. 'unknown'), {system} (eg. 'darwin'), {channel} (eg. 'stable'), and {tool} (eg. 'rustc.exe') will be replaced in the string if present. | String | optional | "@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}" |
| rust_toolchain_rustc_template | The template to use for finding the host rustc binary. {version} (eg. '1.53.0'), {triple} (eg. 'x86_64-unknown-linux-gnu'), {arch} (eg. 'aarch64'), {vendor} (eg. 'unknown'), {system} (eg. 'darwin'), {channel} (eg. 'stable'), and {tool} (eg. 'rustc.exe') will be replaced in the string if present. | String | optional | "@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}" |
| timeout | Maximum duration of the Cargo build command in seconds | Integer | optional | 600 |
| version | The version of Rust the currently registered toolchain is using. Eg. 1.56.0, or nightly/2021-09-08 | String | optional | "1.95.0" |
Rust Analyzer
For non-Cargo projects,
rust-analyzer depends on either a rust-project.json file
at the root of the project that describes its structure or on build system specific
project auto-discovery.
The rust_analyzer rules facilitate both approaches.
rust-project.json approach
Setup
First, ensure rules_rust is setup in your MODULE.bazel:
# MODULE.bazel
# See releases page for available versions:
# https://github.com/bazelbuild/rules_rust/releases
bazel_dep(name = "rules_rust", version = "{SEE_RELEASES}")
Bazel will create the target @rules_rust//tools/rust_analyzer:gen_rust_project, which you can build
with
bazel run @rules_rust//tools/rust_analyzer:gen_rust_project
whenever dependencies change to regenerate the rust-project.json file. It
should be added to .gitignore because it is effectively a build artifact.
Once the rust-project.json has been generated in the project root,
rust-analyzer can pick it up upon restart.
VSCode
To set this up using VSCode, users should first install the
rust_analyzer plugin.
With that in place, the following task can be added to the .vscode/tasks.json file of the workspace
to ensure a rust-project.json file is created and up to date when the editor is opened.
{
"version": "2.0.0",
"tasks": [
{
"label": "Generate rust-project.json",
"command": "bazel",
"args": [
"run",
"@rules_rust//tools/rust_analyzer:gen_rust_project"
],
"options": {
"cwd": "${workspaceFolder}"
},
"group": "build",
"problemMatcher": [],
"presentation": {
"reveal": "never",
"panel": "dedicated"
},
"runOptions": {
"runOn": "folderOpen"
}
}
]
}
Alternative vscode option (prototype)
Add the following to your bazelrc:
build --@rules_rust//rust/settings:rustc_output_diagnostics=true --output_groups=+rust_lib_rustc_output,+rust_metadata_rustc_output
Then you can use a prototype rust-analyzer plugin that automatically collects the outputs whenever you recompile.
Project auto-discovery
Setup
Auto-discovery makes rust-analyzer behave in a Bazel project in a similar fashion to how it does
in a Cargo project. This is achieved by generating a structure similar to what rust-project.json
contains but, instead of writing that to a file, the data gets piped to rust-analyzer directly
through stdout. To use auto-discovery the rust-analyzer IDE settings must be configured similar to:
"rust-analyzer": {
"workspace": {
"discoverConfig": {
"command": ["discover_bazel_rust_project.sh"],
"progressLabel": "rust_analyzer",
"filesToWatch": ["BUILD", "BUILD.bazel", "MODULE.bazel"]
}
}
}
The shell script passed to discoverConfig.command is typically meant to wrap the bazel rule invocation,
primarily for muting stderr (because rust-analyzer will consider that an error has occurred if anything
is passed through stderr) and, additionally, for specifying rule arguments. E.g:
#!/usr/bin/bash
bazel \
run \
@rules_rust//tools/rust_analyzer:discover_bazel_rust_project -- \
--bazel_startup_option=--output_base=~/ide_bazel \
--bazel_arg=--watchfs \
${1:+"$1"} 2>/dev/null
The script above also handles an optional CLI argument which gets passed when workspace splitting is enabled. The script path should be either absolute or relative to the project root.
Workspace splitting
The above configuration treats the entire project as a single workspace. However, large codebases might be
too much to handle for rust-analyzer all at once. This can be addressed by splitting the codebase in
multiple workspaces by extending the discoverConfig.command setting:
"rust-analyzer": {
"workspace": {
"discoverConfig": {
"command": ["discover_bazel_rust_project.sh", "{arg}"],
"progressLabel": "rust_analyzer",
"filesToWatch": ["BUILD", "BUILD.bazel", "MODULE.bazel"]
}
}
}
{arg} acts as a placeholder that rust-analyzer replaces with the path of the source / build file
that gets opened.
The root of the workspace will, in this configuration, be the package the crate currently being worked on
belongs to. This means that only that package and its dependencies get built and indexed by rust-analyzer,
thus allowing for a smaller footprint.
rust-analyzer will switch workspaces whenever an out-of-tree file gets opened, essentially indexing that
crate and its dependencies separately. A caveat of this is that dependents of the crate currently being
worked on are not indexed and won't be tracked by rust-analyzer.
Public entry point to all Rust rules and supported APIs.
Rules
Aspects
rust_unpretty
load("@rules_rust//rust:defs.bzl", "rust_unpretty")
rust_unpretty(name, deps, mode)
Executes rust unpretty on a specific target.
Similar to rust_unpretty_aspect, but allows specifying a list of dependencies within the build system.
For example, given the following example targets:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Rust expand can be set as a build target with the following:
load("@rules_rust//rust:defs.bzl", "rust_unpretty")
rust_unpretty(
name = "hello_library_expand",
testonly = True,
deps = [
":hello_lib",
":greeting_test",
],
mode = "expand",
)
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | Rust targets to run unpretty on. | List of labels | optional | [] |
| mode | The value to pass to --unpretty | String | optional | "expanded" |
rust_unpretty_aspect
load("@rules_rust//rust:defs.bzl", "rust_unpretty_aspect")
rust_unpretty_aspect()
Executes Rust expand on specified targets.
This aspect applies to existing rust_library, rust_test, and rust_binary rules.
As an example, if the following is defined in examples/hello_lib/BUILD.bazel:
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
Then the targets can be expanded with the following command:
$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_unpretty_aspect \
--output_groups=rust_unpretty_expanded \
//hello_lib:all
ASPECT ATTRIBUTES
ATTRIBUTES
Settings
Flags which control granular behavior of various Rust rules.
Rust settings
Definitions for all @rules_rust//rust settings
always_enable_metadata_output_groups
--@rules_rust//rust/settings:always_enable_metadata_output_groups
A flag to enable the always_enable_metadata_output_groups setting.
If this flag is true, all rules will support the metadata and
rustc_rmeta_output output groups.
capture_clippy_output
--@rules_rust//rust/settings:capture_clippy_output
Control whether to print clippy output or store it to a file, using the configured error_format.
clippy_error_format
--@rules_rust//rust/settings:clippy_error_format
This setting may be changed from the command line to generate machine readable errors.
clippy_flag
--@rules_rust//rust/settings:clippy_flag
Add a custom clippy flag from the command line with --@rules_rust//rust/settings:clippy_flag.
Multiple uses are accumulated and appended after the extra_rustc_flags.
clippy_flags
--@rules_rust//rust/settings:clippy_flags
This setting may be used to pass extra options to clippy from the command line.
It applies across all targets.
clippy_output_diagnostics
--@rules_rust//rust/settings:clippy_output_diagnostics
A flag to enable the clippy_output_diagnostics setting.
If this flag is true, rules_rust will save clippy json output (suitable for consumption
by rust-analyzer) in a file, available from the clippy_output output group. This is the
clippy equivalent of rustc_output_diagnostics.
clippy_toml
--@rules_rust//rust/settings:clippy_toml
This setting is used by the clippy rules. See https://bazelbuild.github.io/rules_rust/rust_clippy.html
Note that this setting is actually called clippy.toml.
codegen_units
--@rules_rust//rust/settings:codegen_units
The default value for --codegen-units which also affects resource allocation for rustc actions.
Note that any value 0 or less will prevent this flag from being passed by Bazel and allow rustc to perform it's default behavior.
https://doc.rust-lang.org/rustc/codegen-options/index.html#codegen-units
collect_cfgs
--@rules_rust//rust/settings:collect_cfgs
Enable collection of cfg flags with results stored in CrateInfo.cfgs.
default_allocator_library
--@rules_rust//rust/settings:default_allocator_library
A flag that determines the default allocator library for rust_toolchain targets.
error_format
--@rules_rust//rust/settings:error_format
This setting may be changed from the command line to generate machine readable errors.
experimental_link_std_dylib
--@rules_rust//rust/settings:experimental_link_std_dylib
A flag to control whether to link libstd dynamically.
experimental_per_crate_rustc_flag
--@rules_rust//rust/settings:experimental_per_crate_rustc_flag
Add additional rustc_flag to matching crates from the command line with --@rules_rust//rust/settings:experimental_per_crate_rustc_flag.
The expected flag format is prefix_filter@flag, where any crate with a label or execution path starting
with the prefix filter will be built with the given flag. The label matching uses the canonical form of
the label (i.e //package:label_name). The execution path is the relative path to your workspace directory
including the base name (including extension) of the crate root. This flag is not applied to the exec
configuration (proc-macros, cargo_build_script, etc). Multiple uses are accumulated.
experimental_use_allocator_libraries_with_mangled_symbols
--@rules_rust//rust/settings:experimental_use_allocator_libraries_with_mangled_symbols
A flag used to select allocator libraries implemented in rust that are compatible with the rustc allocator symbol mangling.
The symbol mangling mechanism relies on unstable language features and requires a nightly rustc from 2025-04-05 or later.
Rustc generates references to internal allocator symbols when building rust libraries. At link time, rustc generates the definitions of these symbols. When rustc is not used as the final linker, we need to generate the definitions ourselves. This happens for example when a rust_library is used as a dependency of a rust_binary, or when the experimental_use_cc_common_link setting is used.
For older versions of rustc, the allocator symbol definitions can be provided
via the rust_toolchain's allocator_library or global_allocator_library
attributes, with sample targets like @rules_rust//ffi/cc/allocator_library
and @rules_rust//ffi/cc/global_allocator_library.
Recent versions of rustc started mangling these allocator symbols (https://github.com/rust-lang/rust/pull/127173). The mangling uses a scheme that is specific to the exact version of the compiler. This makes the cc allocator library definitions ineffective. When rustc builds a staticlib it provides the mapping definitions. We rely on this and build an empty staticlib as a basis for the allocator definitions.
Since the new symbol definitions are written in rust, we cannot just attach
them as attributes on the rust_toolchain as the old cc versions, as that
would create a build graph cycle (we need a rust_toolchain to build a
rust_library, so the allocator library cannot be a rust_library directly).
The bootstrapping cycle can be avoided by defining a separate internal "initial" rust toolchain specifically for building the rust allocator libraries, and use a transition to attach the generated libraries to the "main" rust toolchain. But that duplicates the whole sub-graph of the build around the rust toolchains, repository and supporting tools used for them.
Instead, we define a new custom rust_allocator_library rule, which exposes
the result of building the rust allocator libraries via a provider, which
can be consumed by the rust build actions. We attach an instance of this
as a common attribute to the rust rule set.
PARAMETERS
experimental_use_cc_common_link
--@rules_rust//rust/settings:experimental_use_cc_common_link
A flag to control whether to link rust_binary and rust_test targets using cc_common.link instead of rustc.
experimental_use_coverage_metadata_files
--@rules_rust//rust/settings:experimental_use_coverage_metadata_files
A flag to have coverage tooling added as coverage_common.instrumented_files_info.metadata_files instead of reporting tools like llvm-cov and llvm-profdata as runfiles to each test.
experimental_use_global_allocator
--@rules_rust//rust/settings:experimental_use_global_allocator
A flag to indicate that a global allocator is in use when using --@rules_rust//rust/settings:experimental_use_cc_common_link
Users need to specify this flag because rustc generates different set of symbols at link time when a global allocator is in use.
When the linking is not done by rustc, the rust_toolchain itself provides the appropriate set of symbols.
experimental_use_sh_toolchain_for_bootstrap_process_wrapper
--@rules_rust//rust/settings:experimental_use_sh_toolchain_for_bootstrap_process_wrapper
A flag to control whether the shell path from a shell toolchain (@bazel_tools//tools/sh:toolchain_type) is embedded into the bootstrap process wrapper for the .sh file.
extra_exec_rustc_env
--@rules_rust//rust/settings:extra_exec_rustc_env
This setting may be used to pass extra environment variables to rustc from the command line in exec configuration.
It applies to tools built and run during the build process, such as proc-macros and build scripts. This can be useful for enabling features that are needed during tool compilation.
extra_exec_rustc_flag
--@rules_rust//rust/settings:extra_exec_rustc_flag
Add additional rustc_flags in the exec configuration from the command line with --@rules_rust//rust/settings:extra_exec_rustc_flag.
Multiple uses are accumulated and appended after the extra_exec_rustc_flags.
extra_exec_rustc_flags
--@rules_rust//rust/settings:extra_exec_rustc_flags
This setting may be used to pass extra options to rustc from the command line in exec configuration.
It applies across all targets whereas the rustc_flags option on targets applies only to that target. This can be useful for passing build-wide options such as LTO.
extra_rustc_env
--@rules_rust//rust/settings:extra_rustc_env
This setting may be used to pass extra environment variables to rustc from the command line in non-exec configuration.
It applies across all targets whereas environment variables set in a specific rule apply only to that target.
This can be useful for setting build-wide env flags such as RUSTC_BOOTSTRAP=1.
extra_rustc_flag
--@rules_rust//rust/settings:extra_rustc_flag
Add additional rustc_flag from the command line with --@rules_rust//rust/settings:extra_rustc_flag.
Multiple uses are accumulated and appended after the extra_rustc_flags.
extra_rustc_flags
--@rules_rust//rust/settings:extra_rustc_flags
This setting may be used to pass extra options to rustc from the command line in non-exec configuration.
It applies across all targets whereas the rustc_flags option on targets applies only to that target. This can be useful for passing build-wide options such as LTO.
incompatible_change_clippy_error_format
--@rules_rust//rust/settings:incompatible_change_clippy_error_format
A flag to enable the clippy_error_format setting.
If this flag is true, Clippy uses the format set in clippy_error_format to
format its diagnostics; otherwise, it uses the format set in error_format.
incompatible_do_not_include_data_in_compile_data
--@rules_rust//rust/settings:incompatible_do_not_include_data_in_compile_data
A flag to control whether to include data files in compile_data.
incompatible_do_not_include_transitive_data_in_compile_inputs
--@rules_rust//rust/settings:incompatible_do_not_include_transitive_data_in_compile_inputs
A flag to control whether transitive data dependencies are included in compile inputs.
lto
--@rules_rust//rust/settings:lto
A build setting which specifies the link time optimization mode used when building Rust code.
no_std
--@rules_rust//rust/settings:no_std
This setting may be used to enable builds without the standard library.
Currently only no_std + alloc is supported, which can be enabled with setting the value to "alloc". In the future we could add support for additional modes, e.g "core", "alloc,collections".
pipelined_compilation
--@rules_rust//rust/settings:pipelined_compilation
When set, this flag causes rustc to emit *.rmeta files and use them for rlib -> rlib dependencies.
While this involves one extra (short) rustc invocation to build the rmeta file, it allows library dependencies to be unlocked much sooner, increasing parallelism during compilation.
rename_first_party_crates
--@rules_rust//rust/settings:rename_first_party_crates
A flag controlling whether to rename first-party crates such that their names encode the Bazel package and target name, instead of just the target name.
First-party vs. third-party crates are identified using the value of
@rules_rust//settings:third_party_dir.
require_explicit_unstable_features
--@rules_rust//rust/settings:require_explicit_unstable_features
A flag controlling whether unstable features should be disallowed by default
If true, an empty -Zallow-features= will be added to the rustc command line whenever no other
-Zallow-features= is present in the rustc flags. The effect is to disallow all unstable
features by default, with the possibility to explicitly re-enable them selectively using
-Zallow-features=....
rustc_output_diagnostics
--@rules_rust//rust/settings:rustc_output_diagnostics
This setting may be changed from the command line to generate rustc diagnostics.
rustfmt_toml
--@rules_rust//rust/settings:rustfmt_toml
This setting is used by the rustfmt rules. See https://bazelbuild.github.io/rules_rust/rust_fmt.html
Note that this setting is actually called rustfmt.toml.
third_party_dir
--@rules_rust//rust/settings:third_party_dir
A flag specifying the location of vendored third-party rust crates within this repository that must not be renamed when rename_first_party_crates is enabled.
Must be specified as a Bazel package, e.g. "//some/location/in/repo".
toolchain_generated_sysroot
--@rules_rust//rust/settings:toolchain_generated_sysroot
A flag to set rustc --sysroot flag to the sysroot generated by rust_toolchain.
toolchain_linker_preference
--@rules_rust//rust/settings:toolchain_linker_preference
A flag to control which linker is preferred for linking Rust binaries.
Accepts three values:
- "rust": Use
rust_toolchain.linkeralways (e.g.,rust-lld). This uses rustc to invoke the linker directly. - "cc": Use the linker provided by the configured
cc_toolchain. This uses rustc to invoke the C++ toolchain's linker (e.g.,clang,gcc,link.exe). - "none": Default to
ccbeing the preference and falling back torustif nocc_toolchainis available.
unpretty
--@rules_rust//rust/settings:unpretty
A build setting to control the output of RustUnpretty* actions
Supported values are:
ast-tree,expandedast-treeexpanded,hygieneexpanded,identifiedexpandedhir-treehir,identifiedhir,typedhiridentifiedmir-cfgmirnormal
use_real_import_macro
--@rules_rust//rust/settings:use_real_import_macro
A flag to control whether rust_library and rust_binary targets should implicitly depend on the real import macro, or on a no-op target.
Cargo settings
Definitions for all @rules_rust//cargo settings
cargo_manifest_dir_filename_suffixes_to_retain
--@rules_rust//cargo/settings:cargo_manifest_dir_filename_suffixes_to_retain
A flag which determines what files are retained in CARGO_MANIFEST_DIR directories that are created in CargoBuildScriptRun actions.
debug_std_streams_output_group
--@rules_rust//cargo/settings:debug_std_streams_output_group
A flag which adds a streams output group to cargo_build_script targets that contain the raw stderr and stdout streams from the build script.
experimental_symlink_execroot
--@rules_rust//cargo/settings:experimental_symlink_execroot
A flag for which causes cargo_build_script to symlink the execroot of the action to the CARGO_MANIFEST_DIR where the scripts are run.
out_dir_volatile_file_basenames
--@rules_rust//cargo/settings:out_dir_volatile_file_basenames
A flag which determines what file basenames are removed from OUT_DIR by cargo_build_script actions to make the _bs.out_dir TreeArtifact deterministic.
Files whose names appear in this list, as well as files with a .d or .pc
extension, are deleted from OUT_DIR after the build script runs and before Bazel
captures the directory. Files like config.log and Makefile embed the Bazel
sandbox path, so their content changes on every action invocation, causing cache
misses for all downstream rustc compilations.
use_default_shell_env
--@rules_rust//cargo/settings:use_default_shell_env
A flag which controls the global default of ctx.actions.run.use_default_shell_env for cargo_build_script targets.
Rust Toolchains
Toolchain rules for Rust.
Rules
rust_analyzer_toolchain
load("@rules_rust//rust:toolchain.bzl", "rust_analyzer_toolchain")
rust_analyzer_toolchain(name, proc_macro_srv, rust_analyzer, rustc, rustc_srcs, rustc_srcs_path)
A toolchain for rust-analyzer.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| proc_macro_srv | The path to a rust_analyzer_proc_macro_srv binary. | Label | optional | None |
| rust_analyzer | The path to a rust-analyzer binary. | Label | optional | None |
| rustc | The path to a rustc binary. | Label | required | |
| rustc_srcs | The source code of rustc. | Label | required | |
| rustc_srcs_path | The direct path to rustc srcs relative to rustc_srcs package root. | String | optional | "library" |
rust_toolchain
load("@rules_rust//rust:toolchain.bzl", "rust_toolchain")
rust_toolchain(name, allocator_library, binary_ext, cargo, cargo_clippy, channel, clippy_driver,
debug_info, default_edition, dylib_ext, env, exec_triple, experimental_link_std_dylib,
experimental_use_allocator_libraries_with_mangled_symbols,
experimental_use_cc_common_link, extra_exec_rustc_flags, extra_rustc_flags,
extra_rustc_flags_for_crate_types, global_allocator_library, iso_date, linker,
linker_preference, linker_type, llvm_cov, llvm_lib, llvm_profdata, llvm_tools, lto,
opt_level, per_crate_rustc_flags, require_explicit_unstable_features, rust_doc,
rust_objcopy, rust_std, rustc, rustc_lib, rustfmt, staticlib_ext, stdlib_linkflags,
strip_level, target_json, target_triple, version)
Declares a Rust toolchain for use.
This is for declaring a custom toolchain, eg. for configuring a particular version of rust or supporting a new platform.
Example:
Suppose the core rust team has ported the compiler to a new target CPU, called cpuX. This support can be used in Bazel by defining a new toolchain definition and declaration:
load('@rules_rust//rust:toolchain.bzl', 'rust_toolchain')
rust_toolchain(
name = "rust_cpuX_impl",
binary_ext = "",
dylib_ext = ".so",
exec_triple = "cpuX-unknown-linux-gnu",
rust_doc = "@rust_cpuX//:rustdoc",
rust_std = "@rust_cpuX//:rust_std",
rustc = "@rust_cpuX//:rustc",
rustc_lib = "@rust_cpuX//:rustc_lib",
staticlib_ext = ".a",
stdlib_linkflags = ["-lpthread", "-ldl"],
target_triple = "cpuX-unknown-linux-gnu",
)
toolchain(
name = "rust_cpuX",
exec_compatible_with = [
"@platforms//cpu:cpuX",
"@platforms//os:linux",
],
target_compatible_with = [
"@platforms//cpu:cpuX",
"@platforms//os:linux",
],
toolchain = ":rust_cpuX_impl",
)
Then, either add the label of the toolchain rule to register_toolchains in the WORKSPACE, or pass it to the "--extra_toolchains" flag for Bazel, and it will be used.
To use a platform-specific linker, you can use a select() in the linker attribute:
rust_toolchain(
name = "rust_toolchain_impl",
# ... other attributes ...
linker = select({
"@platforms//os:linux": "//tools:rust-lld-linux",
"@platforms//os:windows": "//tools:rust-lld-windows",
"//conditions:default": "//tools:rust-lld",
}),
)
The select() is evaluated against the target platform before the exec transition is applied, allowing platform-specific linker selection while ensuring the selected linker is built for the exec platform.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | Label | optional | "@rules_rust//rust/settings:default_allocator_library" |
| binary_ext | The extension for binaries created from rustc. | String | required | |
| cargo | The location of the cargo binary. Can be a direct source or a filegroup containing one item. | Label | optional | None |
| cargo_clippy | The location of the cargo_clippy binary. Can be a direct source or a filegroup containing one item. | Label | optional | None |
| channel | The Rust release channel (stable, nightly, or beta). | String | optional | "" |
| clippy_driver | The location of the clippy-driver binary. Can be a direct source or a filegroup containing one item. | Label | optional | None |
| debug_info | Rustc debug info levels per opt level | Dictionary: String -> String | optional | {"dbg": "2", "fastbuild": "0", "opt": "0"} |
| default_edition | The edition to use for rust_* rules that don't specify an edition. If absent, every rule is required to specify its edition attribute. | String | optional | "" |
| dylib_ext | The extension for dynamic libraries created from rustc. | String | required | |
| env | Environment variables to set in actions. | Dictionary: String -> String | optional | {} |
| exec_triple | The platform triple for the toolchains execution environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations | String | required | |
| experimental_link_std_dylib | Label to a boolean build setting that controls whether whether to link libstd dynamically. | Label | optional | "@rules_rust//rust/settings:experimental_link_std_dylib" |
| experimental_use_allocator_libraries_with_mangled_symbols | Whether to use rust-based allocator libraries with mangled symbols. Possible values: [-1, 0, 1]. -1 means to use the value of the build setting //rust/settings:experimental_use_allocator_libraries_with_mangled_symbols. 0 means do not use. In that case, rules_rust will try to use the c-based allocator libraries that don't support symbol mangling. 1 means use the rust-based allocator libraries. | Integer | optional | -1 |
| experimental_use_cc_common_link | Label to a boolean build setting that controls whether cc_common.link is used to link rust binaries. | Label | optional | "@rules_rust//rust/settings:experimental_use_cc_common_link" |
| extra_exec_rustc_flags | Extra flags to pass to rustc in exec configuration. Subject to location expansion with respect to the srcs of the rust_std attribute. Subject to Make variable expansion with respect to RUST_SYSROOT, RUST_SYSROOT_SHORT, RUSTC, etc. | List of strings | optional | [] |
| extra_rustc_flags | Extra flags to pass to rustc in non-exec configuration. Subject to location expansion with respect to the srcs of the rust_std attribute. Subject to Make variable expansion with respect to RUST_SYSROOT, RUST_SYSROOT_SHORT, RUSTC, etc. | List of strings | optional | [] |
| extra_rustc_flags_for_crate_types | Extra flags to pass to rustc based on crate type | Dictionary: String -> List of strings | optional | {} |
| global_allocator_library | Target that provides allocator functions for when a global allocator is present. | Label | optional | "@rules_rust//rust/private/cc:global_allocator_library" |
| iso_date | The ISO date of the nightly or beta release (e.g. 2026-03-26). Empty for stable releases. | String | optional | "" |
| linker | The label to an explicit linker to use (e.g. rust-lld, ld, link-ld.exe, etc.). Linker binaries must be runnable in the exec configuration, so cfg = "exec" is used. To choose a linker based on the target platform, use a select() when providing this attribute. The select() will be evaluated against the target platform before the exec transition is applied, allowing platform-specific linker selection while ensuring the selected linker is built for the exec platform. | Label | optional | None |
| linker_preference | The preferred linker to use. If unspecified, cc is preferred and rust is used as a fallback whenever linker is provided. | String | optional | "" |
| linker_type | The type of linker invocation: 'direct' (ld, rust-lld) or 'indirect' (via compiler like clang/gcc). If unset, defaults based on linker_preference. | String | optional | "" |
| llvm_cov | The location of the llvm-cov binary. Can be a direct source or a filegroup containing one item. If None, rust code is not instrumented for coverage. | Label | optional | None |
| llvm_lib | The location of the libLLVM shared object files. If llvm_cov is None, this can be None as well and rust code is not instrumented for coverage. | Label | optional | None |
| llvm_profdata | The location of the llvm-profdata binary. Can be a direct source or a filegroup containing one item. If llvm_cov is None, this can be None as well and rust code is not instrumented for coverage. | Label | optional | None |
| llvm_tools | LLVM tools that are shipped with the Rust toolchain. | Label | optional | None |
| lto | Label to an LTO setting whether which can enable custom LTO settings | Label | optional | "@rules_rust//rust/settings:lto" |
| opt_level | Rustc optimization levels. | Dictionary: String -> String | optional | {"dbg": "0", "fastbuild": "0", "opt": "3"} |
| per_crate_rustc_flags | Extra flags to pass to rustc in non-exec configuration | List of strings | optional | [] |
| require_explicit_unstable_features | Label to a boolean build setting that controls whether all uses of unstable Rust features must be explicitly opted in to using -Zallow-features=.... | Label | optional | "@rules_rust//rust/settings:require_explicit_unstable_features" |
| rust_doc | The location of the rustdoc binary. Can be a direct source or a filegroup containing one item. | Label | required | |
| rust_objcopy | The location of the rust-objcopy binary. Can be a direct source or a filegroup containing one item. | Label | optional | None |
| rust_std | The Rust standard library. | Label | required | |
| rustc | The location of the rustc binary. Can be a direct source or a filegroup containing one item. | Label | required | |
| rustc_lib | The libraries used by rustc during compilation. | Label | optional | None |
| rustfmt | Deprecated: Instead see rustfmt_toolchain | Label | optional | None |
| staticlib_ext | The extension for static libraries created from rustc. | String | required | |
| stdlib_linkflags | Additional linker flags to use when Rust standard library is linked by a C++ linker (rustc will deal with these automatically). Subject to location expansion with respect to the srcs of the rust_std attribute. Subject to Make variable expansion with respect to RUST_SYSROOT, RUST_SYSROOT_SHORT, RUSTC, etc. | List of strings | required | |
| strip_level | Rustc strip levels. For all potential options, see https://doc.rust-lang.org/rustc/codegen-options/index.html#strip | Dictionary: String -> String | optional | {"dbg": "none", "fastbuild": "none", "opt": "debuginfo"} |
| target_json | Override the target_triple with a custom target specification. For more details see: https://doc.rust-lang.org/rustc/targets/custom.html | String | optional | "" |
| target_triple | The platform triple for the toolchains target environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations | String | optional | "" |
| version | The version of the Rust compiler (e.g. 1.94.1). | String | optional | "" |
rustfmt_toolchain
load("@rules_rust//rust:toolchain.bzl", "rustfmt_toolchain")
rustfmt_toolchain(name, rustc, rustc_lib, rustfmt)
A toolchain for rustfmt
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| rustc | The location of the rustc binary. Can be a direct source or a filegroup containing one item. | Label | optional | None |
| rustc_lib | The libraries used by rustc during compilation. | Label | optional | None |
| rustfmt | The location of the rustfmt binary. Can be a direct source or a filegroup containing one item. | Label | required |
Module extensions for using rules_rust with bzlmod
Module Extensions
rust
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.repository_set(name, allocator_library, auth, auth_patterns, dev_components, edition,
exec_compatible_with, exec_triple, extra_exec_rustc_flags, extra_rustc_flags,
global_allocator_library, netrc, opt_level, rustfmt_version, sha256s, strip_level,
target_compatible_with, target_settings, target_triple, urls, versions)
rust.toolchain(aliases, allocator_library, dev_components, edition, extra_exec_rustc_flags,
extra_rustc_flags, extra_rustc_flags_triples, extra_target_triples,
global_allocator_library, rust_analyzer_version, rustfmt_toolchain_triples,
rustfmt_version, sha256s, strip_level, target_settings, urls, versions)
Rust toolchain extension.
TAG CLASSES
repository_set
Tags for defining rust repository sets (where toolchains are defined).
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | Name of the repository_set - if you're looking to replace default toolchains you must use the exact name you're replacing. | Name | optional | "" |
| allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | Label | optional | None |
| auth | Auth object compatible with repository_ctx.download to use when downloading files. | Dictionary: String -> String | optional | {} |
| auth_patterns | Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive. | Dictionary: String -> String | optional | {} |
| dev_components | Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly". | Boolean | optional | False |
| edition | The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute. | String | optional | "" |
| exec_compatible_with | A list of constraints for the execution platform for this toolchain. | List of labels | optional | [] |
| exec_triple | Exec triple for this repository_set. | String | optional | "" |
| extra_exec_rustc_flags | Extra flags to pass to rustc in exec configuration. | List of strings | optional | [] |
| extra_rustc_flags | Extra flags to pass to rustc in non-exec configuration. | List of strings | optional | [] |
| global_allocator_library | Target that provides allocator functions when global allocator is used with cc_common.link. | Label | optional | None |
| netrc | .netrc file to use for authentication; mirrors the eponymous attribute from http_archive. | String | optional | "" |
| opt_level | Rustc optimization levels. For more details see the documentation for rust_toolchain.opt_level. | Dictionary: String -> String | optional | {} |
| rustfmt_version | The version of the tool among "nightly", "beta", or an exact version. | String | optional | "nightly/2026-04-16" |
| sha256s | A dict associating tool subdirectories to sha256 hashes. | Dictionary: String -> String | optional | {} |
| strip_level | Rustc strip levels. For more details see the documentation for rust_toolchain.strip_level. | Dictionary: String -> String | optional | {} |
| target_compatible_with | List of platform constraints this toolchain produces, for the particular target_triple this call is for. | List of labels | optional | [] |
| target_settings | A list of config_settings that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution. | List of labels | optional | [] |
| target_triple | target_triple to configure. | String | optional | "" |
| urls | A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). | List of strings | optional | ["https://static.rust-lang.org/dist/{}.tar.xz"] |
| versions | A list of toolchain versions to download. This parameter only accepts one version per channel. E.g. ["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]. May be set to an empty list ([]) to inhibit rules_rust from registering toolchains. | List of strings | optional | [] |
toolchain
Tags for defining rust toolchains (where toolchain tools are fetched).
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| aliases | Map of full toolchain repository name to an alias. If any repository is created by this extension matches a key in this dictionary, the name of the created repository will be remapped to the value instead. This may be required to work around path length limits on Windows. | Dictionary: String -> String | optional | {} |
| allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | Label | optional | None |
| dev_components | Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly". | Boolean | optional | False |
| edition | The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute. | String | optional | "" |
| extra_exec_rustc_flags | Extra flags to pass to rustc in exec configuration | List of strings | optional | [] |
| extra_rustc_flags | Extra flags to pass to rustc in non-exec configuration | List of strings | optional | [] |
| extra_rustc_flags_triples | Extra flags to pass to rustc in non-exec configuration. Key is the triple, value is the flag. | Dictionary: String -> List of strings | optional | {} |
| extra_target_triples | - | List of strings | optional | ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "wasm32-unknown-unknown", "wasm32-wasip1", "wasm32-wasip2"] |
| global_allocator_library | Target that provides allocator functions when global allocator is used with cc_common.link. | Label | optional | None |
| rust_analyzer_version | The version of Rustc to pair with rust-analyzer. | String | optional | "" |
| rustfmt_toolchain_triples | Like toolchain_triples, but for rustfmt toolchains. Mapping of rust target triple to repository name. | Dictionary: String -> String | optional | {} |
| rustfmt_version | The version of the tool among "nightly", "beta", or an exact version. | String | optional | "nightly/2026-04-16" |
| sha256s | A dict associating tool subdirectories to sha256 hashes. | Dictionary: String -> String | optional | {} |
| strip_level | Rustc strip levels. For more details see the documentation for rust_toolchain.strip_level. | Dictionary: String -> String | optional | {} |
| target_settings | A list of config_settings that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution. | List of labels | optional | [] |
| urls | A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). | List of strings | optional | ["https://static.rust-lang.org/dist/{}.tar.xz"] |
| versions | A list of toolchain versions to download. This parameter only accepts one version per channel. E.g. ["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]. May be set to an empty list ([]) to inhibit rules_rust from registering toolchains. | List of strings | optional | ["1.95.0", "nightly/2026-04-16"] |
rust_host_tools
rust_host_tools = use_extension("@rules_rust//rust:extensions.bzl", "rust_host_tools")
rust_host_tools.host_tools(name, allocator_library, dev_components, edition,
global_allocator_library, rustfmt_version, sha256s, urls, version)
An extension which exposes Rust tools compatible with the current host platform.
TAG CLASSES
host_tools
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | The name of the module to create | Name | optional | "rust_host_tools" |
| allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | Label | optional | None |
| dev_components | Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly". | Boolean | optional | False |
| edition | The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute. | String | optional | "" |
| global_allocator_library | Target that provides allocator functions when global allocator is used with cc_common.link. | Label | optional | None |
| rustfmt_version | The version of the tool among "nightly", "beta", or an exact version. | String | optional | "nightly/2026-04-16" |
| sha256s | A dict associating tool subdirectories to sha256 hashes. | Dictionary: String -> String | optional | {} |
| urls | A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). | List of strings | optional | ["https://static.rust-lang.org/dist/{}.tar.xz"] |
| version | The version of Rust to use for tools executed on the Bazel host. | String | optional | "1.95.0" |
External Dependencies
crate_universe workspace (crate_universe bzlmod) is a tool built into rules_rust that can be used to fetch dependencies.
Crate Universe
Crate Universe is a set of Bazel rule for generating Rust targets using Cargo.
This doc describes using crate_universe with bzlmod.
If you're using a WORKSPACE file, please see the WORKSPACE equivalent of this doc.
There are some examples of using crate_universe with bzlmod in the example folder.
Table of Contents
Setup
To use rules_rust in a project using bzlmod, add the following to your MODULE.bazel file:
bazel_dep(name = "rules_rust", version = "0.70.0")
You find the latest version on the release page.
After adding rules_rust in your MODULE.bazel, set the following to begin using crate_universe:
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
// # ... Dependencies
use_repo(crate, "crates")
Dependencies
There are three different ways to declare dependencies in your MODULE.
- Cargo workspace
- Direct Dependencies
- Binary Dependencies
- Vendored Dependencies
Cargo Workspaces
One of the simpler ways to wire up dependencies would be to first structure your project into a Cargo workspace. The crates_repository rule can ingest a root Cargo.toml file and generate Bazel dependencies from there. You find a complete example in the in the example folder.
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
crate.from_cargo(
name = "crates",
cargo_lockfile = "//:Cargo.lock",
manifests = ["//:Cargo.toml"],
)
use_repo(crate, "crates")
Note if using Private Crate Registries
If you are using from_cargo and are pulling dependencies from a private crate registry such as Artifactory,
make sure you set the CARGO_BAZEL_ISOLATED=false bazel build //... environmental. If not crates_universe
will not be able to pull from your private registry.
The generated crates_repository contains helper macros which make collecting dependencies for Bazel targets simpler. Notably, the all_crate_deps, aliases, and crate_edition macros ( see Dependencies API) commonly allow the Cargo.toml files to be the single source of truth for dependencies. Since these macros come from the generated repository, the dependency labels, alias definitions, and editions they return will automatically update BUILD targets. In your BUILD files, you use these macros for a Rust library as shown below:
load("@crates//:defs.bzl", "aliases", "all_crate_deps", "crate_edition")
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "lib",
aliases = aliases(),
edition = crate_edition(),
deps = all_crate_deps(
normal = True,
),
proc_macro_deps = all_crate_deps(
proc_macro = True,
),
)
rust_test(
name = "unit_test",
crate = ":lib",
aliases = aliases(
normal_dev = True,
proc_macro_dev = True,
),
edition = crate_edition(),
deps = all_crate_deps(
normal_dev = True,
),
proc_macro_deps = all_crate_deps(
proc_macro_dev = True,
),
)
For a Rust binary that does not depend on any macro, use the following configuration in your build file:
rust_binary(
name = "bin",
srcs = ["src/main.rs"],
edition = crate_edition(),
deps = all_crate_deps(normal = True),
)
You have to repin before your first build to ensure all Bazel targets for the macros are generated.
Dependency syncing and updating is done in the repository rule which means it's done during the
analysis phase of builds. As mentioned in the environments variable table above, the CARGO_BAZEL_REPIN
(or REPIN) environment variables can be used to force the rule to update dependencies and potentially
render a new lockfile. Given an instance of this repository rule named crates, the easiest way to
repin dependencies is to run:
CARGO_BAZEL_REPIN=1 bazel sync --only=crates
This will result in all dependencies being updated for a project. The CARGO_BAZEL_REPIN
environment variable can also be used to customize how dependencies are updated.
For more details about repin, please refer to the documentation.
Direct Dependencies
In cases where Rust targets have heavy interactions with other Bazel targets (Cc, Proto, etc.), maintaining Cargo.toml files may have diminishing returns as things like rust-analyzer begin to be confused about missing targets or environment variables defined only in Bazel. In situations like this, it may be desirable to have a "Cargo free" setup. You find an example in the in the example folder.
crates_repository supports this through the packages attribute, as shown below.
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
crate.spec(package = "serde", features = ["derive"], version = "1.0")
crate.spec(package = "serde_json", version = "1.0")
crate.spec(package = "tokio", default_features = False, features = ["macros", "net", "rt-multi-thread"], version = "1.38")
crate.from_specs()
use_repo(crate, "crates")
Consuming dependencies may be more ergonomic in this case through the aliases defined in the new repository. In your BUILD files, you use direct dependencies as shown below:
rust_binary(
name = "bin",
crate_root = "src/main.rs",
srcs = glob([
"src/*.rs",
]),
deps = [
# External crates
"@crates//:serde",
"@crates//:serde_json",
"@crates//:tokio",
],
visibility = ["//visibility:public"],
)
Notice, direct dependencies do not need repining. Only a cargo workspace needs updating whenever the underlying Cargo.toml file changed.
Binary Dependencies
With cargo you can install binary dependencies (bindeps) as well with cargo install command.
We don't have such easy facilities available in bazel besides specifying it as a dependency. To mimic cargo's bindeps feature we use the unstable feature called artifact-dependencies which integrates well with bazel concepts.
You could use the syntax specified in the above document to place it in Cargo.toml. For that you can consult the following example.
This method has the following consequences:
- if you use shared dependency tree with your project these binary dependencies will interfere with yours (may conflict)
- you have to use nightly
host_toolsto generate dependencies because
Alternatively you can specify this in a separate repo with cargo.from_specs syntax:
bindeps = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
bindeps.spec(package = "cargo-machete", version = "=0.7.0", artifact = "bin")
bindeps.annotation(crate = "cargo-machete", gen_all_binaries = True)
bindeps.from_specs(
name = "bindeps",
host_tools = "@rust_host_tools_nightly",
)
use_repo(bindeps, "bindeps")
You can run the specified binary dependency with the following command or create additional more complex rules on top of it.
bazel run @bindeps//:cargo-machete__cargo-machete
Notice, direct dependencies do not need repining. Only a cargo workspace needs updating whenever the underlying Cargo.toml file changed.
Vendored Dependencies
In some cases, it is require that all external dependencies are vendored, meaning downloaded and stored in the workspace. This helps, for example, to conduct licence scans, apply custom patches, or to ensure full build reproducibility since no download error could possibly occur. You find a complete example in the in the example folder.
For the setup, you need to add the skylib in addition to the rust rules to your MODULE.bazel.
module(
name = "deps_vendored",
version = "0.0.0"
)
###############################################################################
# B A Z E L C E N T R A L R E G I S T R Y # https://registry.bazel.build/
###############################################################################
# https://github.com/bazelbuild/bazel-skylib/releases/
bazel_dep(name = "bazel_skylib", version = "1.8.2")
# https://github.com/bazelbuild/rules_rust/releases
bazel_dep(name = "rules_rust", version = "0.70.0")
###############################################################################
# T O O L C H A I N S
###############################################################################
# Rust toolchain
RUST_EDITION = "2021"
RUST_VERSION = "1.80.1"
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.toolchain(
edition = RUST_EDITION,
versions = [RUST_VERSION],
)
use_repo(rust, "rust_toolchains")
register_toolchains("@rust_toolchains//:all")
###############################################################################
# R U S T C R A T E S
###############################################################################
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
Note, it is important to load the crate_universe rules otherwise you will get an error as the rule set is needed in the vendored target.
Assuming you have a package called basic in which you want to vendor dependencies,
then you create a folder basic/3rdparty. The folder name can be arbitrary,
but by convention, its either thirdparty or 3rdparty to indicate vendored dependencies.
In the 3rdparty folder, you add a target crates_vendor to declare your dependencies to vendor.
In the example, we vendor a specific version of bzip2.
load("@rules_rust//crate_universe:defs.bzl", "crate", "crates_vendor")
crates_vendor(
name = "crates_vendor",
annotations = {
"bzip2-sys": [crate.annotation(
gen_build_script = True,
)],
},
cargo_lockfile = "Cargo.Bazel.lock",
generate_build_scripts = False,
mode = "remote",
packages = {
"bzip2": crate.spec(
version = "=0.3.3",
),
},
repository_name = "basic",
tags = ["manual"],
)
Next, you have to run Cargo build to generate a Cargo.lock file with all resolved dependencies.
Then, you rename Cargo.lock to Cargo.Bazel.lock and place it inside the basic/3rdparty folder.
At this point, you have the following folder and files:
basic
|-- 3rdparty
| |-- BUILD.bazel
| |-- Cargo.Bazel.lock
Now you can run the crates_vendor target:
bazel run //basic/3rdparty:crates_vendor
This generates a crate folders with all configurations for the vendored dependencies.
basic
|-- 3rdparty
| |-- cratea
| |-- BUILD.bazel
| |-- Cargo.Bazel.lock
Suppose you have an application in basic/src that is defined in basic/BUILD.bazel and
that depends on a vendored dependency. You find a list of all available vendored dependencies
in the BUILD file of the generated folder: basic/3rdparty/crates/BUILD.bazel
You declare a vendored dependency in you target as following:
load("@rules_rust//rust:defs.bzl", "rust_binary")
rust_binary(
name = "hello_sys",
srcs = ["src/main.rs"],
deps = ["//basic/3rdparty/crates:bzip2"],
visibility = ["//visibility:public"],
)
Note, the vendored dependency is not yet accessible because you have to define first
how to load the vendored dependencies. For that, you first create a file sys_deps.bzl
and add the following content:
# rename the default name "crate_repositories" in case you import multiple vendored folders.
load("//basic/3rdparty/crates:defs.bzl", basic_crate_repositories = "crate_repositories")
def sys_deps():
# Load the vendored dependencies
basic_crate_repositories()
This is straightforward, you import the generated crate_repositories from the crates folder, rename it to avoid name clashes in case you import from multiple vendored folders, and then just load the vendored dependencies.
In a WORKSPACE configuration, you would just load and call sys_deps(), but in a MODULE configuration, you cannot do that.
Instead, you create a new file WORKSPACE.bzlmod and add the following content.
load("//:sys_deps.bzl", "sys_deps")
sys_deps()
Now, you can build the project as usual.
There are some more examples of using crate_universe with bzlmod in the example folder.
crate
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
crate.annotation(deps, data, additive_build_file, additive_build_file_content, alias_rule,
build_script_compile_data, build_script_data, build_script_data_glob,
build_script_deps, build_script_env, build_script_exec_properties,
build_script_link_deps, build_script_proc_macro_deps, build_script_rundir,
build_script_rustc_env, build_script_toolchains, build_script_tools, compile_data,
compile_data_glob, compile_data_glob_excludes, crate, crate_features, data_glob,
disable_pipelining, extra_aliased_targets, gen_all_binaries, gen_binaries,
gen_build_script, override_target_bin, override_target_build_script,
override_target_lib, override_target_proc_macro, patch_args, patch_tool, patches,
proc_macro_deps, repositories, rustc_env, rustc_env_files, rustc_flags,
shallow_since, version)
crate.annotation_select(deps, data, build_script_compile_data, build_script_data, build_script_deps,
build_script_env, build_script_exec_properties, build_script_link_deps,
build_script_proc_macro_deps, build_script_rundir, build_script_rustc_env,
build_script_tools, compile_data, crate, crate_features, proc_macro_deps,
repositories, rustc_env, rustc_env_files, rustc_flags, triples, version)
crate.from_cargo(name, cargo_config, cargo_lockfile, generate_binaries, generate_build_scripts,
host_tools, isolated, lockfile, manifests, skip_cargo_lockfile_overwrite,
strip_internal_dependencies_from_cargo_lockfile, supported_platform_triples)
crate.from_specs(name, cargo_config, cargo_lockfile, generate_binaries, generate_build_scripts,
host_tools, isolated, lockfile, skip_cargo_lockfile_overwrite,
strip_internal_dependencies_from_cargo_lockfile, supported_platform_triples)
crate.render_config(build_file_template, crate_alias_template, crate_label_template,
crate_repository_template, crates_module_template, default_alias_rule_bzl,
default_alias_rule_name, default_package_name, generate_cargo_toml_env_vars,
generate_rules_license_metadata, generate_target_compatible_with,
platforms_template, regen_command, repositories, vendor_mode)
crate.spec(artifact, branch, default_features, features, git, lib, package, package_alias, path,
repositories, rev, tag, version)
crate.splicing_config(repositories, resolver_version)
Crate universe module extensions.
Environment Variables:
| variable | usage |
|---|---|
CARGO_BAZEL_GENERATOR_SHA256 | The sha256 checksum of the file located at CARGO_BAZEL_GENERATOR_URL |
CARGO_BAZEL_GENERATOR_URL | The URL of a cargo-bazel binary. This variable takes precedence over attributes and can use file:// for local paths |
CARGO_BAZEL_ISOLATED | An authoritative flag as to whether or not the CARGO_HOME environment variable should be isolated from the host configuration |
CARGO_BAZEL_REPIN | An indicator that the dependencies represented by the rule should be regenerated. REPIN may also be used. See Repinning / Updating Dependencies for more details. |
CARGO_BAZEL_REPIN_ONLY | A comma-delimited allowlist for rules to execute repinning. Can be useful if multiple instances of the repository rule are used in a Bazel workspace, but repinning should be limited to one of them. |
CARGO_BAZEL_TIMEOUT | An integer value to override the default timeout setting when running the cargo-bazel binary. This value must be in seconds. |
TAG CLASSES
annotation
A collection of extra attributes and settings for a particular crate.
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| deps | A list of labels to add to a crate's rust_library::deps attribute. | List of strings | optional | [] |
| data | A list of labels to add to a crate's rust_library::data attribute. | List of strings | optional | [] |
| additive_build_file | A file containing extra contents to write to the bottom of generated BUILD files. | Label | optional | None |
| additive_build_file_content | Extra contents to write to the bottom of generated BUILD files. | String | optional | "" |
| alias_rule | Alias rule to use instead of native.alias(). Overrides render_config's 'default_alias_rule'. | String | optional | "" |
| build_script_compile_data | A list of labels to add to a crate's cargo_build_script::compile_data attribute. | List of strings | optional | [] |
| build_script_data | A list of labels to add to a crate's cargo_build_script::data attribute. | List of strings | optional | [] |
| build_script_data_glob | A list of glob patterns to add to a crate's cargo_build_script::data attribute | List of strings | optional | [] |
| build_script_deps | A list of labels to add to a crate's cargo_build_script::deps attribute. | List of strings | optional | [] |
| build_script_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | Dictionary: String -> String | optional | {} |
| build_script_exec_properties | Execution properties to set on a crate's cargo_build_script::exec_properties attribute. | Dictionary: String -> String | optional | {} |
| build_script_link_deps | A list of labels to add to a crate's cargo_build_script::link_deps attribute. | List of strings | optional | [] |
| build_script_proc_macro_deps | A list of labels to add to a crate's cargo_build_script::proc_macro_deps attribute. | List of strings | optional | [] |
| build_script_rundir | An override for the build script's rundir attribute. | String | optional | "" |
| build_script_rustc_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | Dictionary: String -> String | optional | {} |
| build_script_toolchains | A list of labels to set on a crates's cargo_build_script::toolchains attribute. | List of labels | optional | [] |
| build_script_tools | A list of labels to add to a crate's cargo_build_script::tools attribute. | List of strings | optional | [] |
| compile_data | A list of labels to add to a crate's rust_library::compile_data attribute. | List of strings | optional | [] |
| compile_data_glob | A list of glob patterns to add to a crate's rust_library::compile_data attribute. | List of strings | optional | [] |
| compile_data_glob_excludes | A list of glob patterns to be excllued from a crate's rust_library::compile_data attribute. | List of strings | optional | [] |
| crate | The name of the crate the annotation is applied to | String | required | |
| crate_features | A list of strings to add to a crate's rust_library::crate_features attribute. | List of strings | optional | [] |
| data_glob | A list of glob patterns to add to a crate's rust_library::data attribute. | List of strings | optional | [] |
| disable_pipelining | If True, disables pipelining for library targets for this crate. | Boolean | optional | False |
| extra_aliased_targets | A list of targets to add to the generated aliases in the root crate_universe repository. | Dictionary: String -> String | optional | {} |
| gen_all_binaries | If true, generates rust_binary targets for all of the crates bins | Boolean | optional | False |
| gen_binaries | As a list, the subset of the crate's bins that should get rust_binary targets produced. | List of strings | optional | [] |
| gen_build_script | An authoritative flag to determine whether or not to produce cargo_build_script targets for the current crate. Supported values are 'on', 'off', and 'auto'. | String | optional | "auto" |
| override_target_bin | An optional alternate target to use when something depends on this crate to allow the parent repo to provide its own version of this dependency. | Label | optional | None |
| override_target_build_script | An optional alternate target to use when something depends on this crate to allow the parent repo to provide its own version of this dependency. | Label | optional | None |
| override_target_lib | An optional alternate target to use when something depends on this crate to allow the parent repo to provide its own version of this dependency. | Label | optional | None |
| override_target_proc_macro | An optional alternate target to use when something depends on this crate to allow the parent repo to provide its own version of this dependency. | Label | optional | None |
| patch_args | The patch_args attribute of a Bazel repository rule. See http_archive.patch_args | List of strings | optional | [] |
| patch_tool | The patch_tool attribute of a Bazel repository rule. See http_archive.patch_tool | String | optional | "" |
| patches | The patches attribute of a Bazel repository rule. See http_archive.patches | List of labels | optional | [] |
| proc_macro_deps | A list of labels to add to a crate's rust_library::proc_macro_deps attribute. | List of strings | optional | [] |
| repositories | A list of repository names specified from crate.from_cargo(name=...) that this annotation is applied to. Defaults to all repositories. | List of strings | optional | [] |
| rustc_env | Additional variables to set on a crate's rust_library::rustc_env attribute. | Dictionary: String -> String | optional | {} |
| rustc_env_files | A list of labels to set on a crate's rust_library::rustc_env_files attribute. | List of strings | optional | [] |
| rustc_flags | A list of strings to set on a crate's rust_library::rustc_flags attribute. | List of strings | optional | [] |
| shallow_since | An optional timestamp used for crates originating from a git repository instead of a crate registry. This flag optimizes fetching the source code. | String | optional | "" |
| version | The versions of the crate the annotation is applied to. Defaults to all versions. | String | optional | "*" |
annotation_select
A constructor for a crate dependency with selectable attributes.
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| deps | A list of labels to add to a crate's rust_library::deps attribute. | List of strings | optional | [] |
| data | A list of labels to add to a crate's rust_library::data attribute. | List of strings | optional | [] |
| build_script_compile_data | A list of labels to add to a crate's cargo_build_script::compile_data attribute. | List of strings | optional | [] |
| build_script_data | A list of labels to add to a crate's cargo_build_script::data attribute. | List of strings | optional | [] |
| build_script_deps | A list of labels to add to a crate's cargo_build_script::deps attribute. | List of strings | optional | [] |
| build_script_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | Dictionary: String -> String | optional | {} |
| build_script_exec_properties | Execution properties to set on a crate's cargo_build_script::exec_properties attribute. | Dictionary: String -> String | optional | {} |
| build_script_link_deps | A list of labels to add to a crate's cargo_build_script::link_deps attribute. | List of strings | optional | [] |
| build_script_proc_macro_deps | A list of labels to add to a crate's cargo_build_script::proc_macro_deps attribute. | List of strings | optional | [] |
| build_script_rundir | An override for the build script's rundir attribute. | String | optional | "" |
| build_script_rustc_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | Dictionary: String -> String | optional | {} |
| build_script_tools | A list of labels to add to a crate's cargo_build_script::tools attribute. | List of strings | optional | [] |
| compile_data | A list of labels to add to a crate's rust_library::compile_data attribute. | List of strings | optional | [] |
| crate | The name of the crate the annotation is applied to | String | required | |
| crate_features | A list of strings to add to a crate's rust_library::crate_features attribute. | List of strings | optional | [] |
| proc_macro_deps | A list of labels to add to a crate's rust_library::proc_macro_deps attribute. | List of strings | optional | [] |
| repositories | A list of repository names specified from crate.from_cargo(name=...) that this annotation is applied to. Defaults to all repositories. | List of strings | optional | [] |
| rustc_env | Additional variables to set on a crate's rust_library::rustc_env attribute. | Dictionary: String -> String | optional | {} |
| rustc_env_files | A list of labels to set on a crate's rust_library::rustc_env_files attribute. | List of strings | optional | [] |
| rustc_flags | A list of strings to set on a crate's rust_library::rustc_flags attribute. | List of strings | optional | [] |
| triples | A list of triples to apply the annotation to. | List of strings | required | |
| version | The versions of the crate the annotation is applied to. Defaults to all versions. | String | optional | "*" |
from_cargo
Generates a repo @crates from a Cargo.toml / Cargo.lock pair.
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | The name of the repo to generate | Name | optional | "crates" |
| cargo_config | A Cargo configuration file. | Label | optional | None |
| cargo_lockfile | The path to an existing Cargo.lock file | Label | optional | None |
| generate_binaries | Whether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated. | Boolean | optional | False |
| generate_build_scripts | Whether or not to generate cargo build scripts by default. | Boolean | optional | True |
| host_tools | The rust_host_tools repository to use. | Label | optional | "@@rules_rust++rust_host_tools+rust_host_tools//:rust_host_tools" |
| isolated | If true, CARGO_HOME will be overwritten to a directory within the generated repository in order to prevent other uses of Cargo from impacting having any effect on the generated targets produced by this rule. For users who either have multiple crate_repository definitions in a WORKSPACE or rapidly re-pin dependencies, setting this to false may improve build times. This variable is also controlled by CARGO_BAZEL_ISOLATED environment variable. | Boolean | optional | True |
| lockfile | The path to a file to use for reproducible renderings. If set, this file must exist within the workspace (but can be empty) before this rule will work. | Label | optional | None |
| manifests | A list of Cargo manifests (Cargo.toml files). | List of labels | optional | [] |
| skip_cargo_lockfile_overwrite | Whether to skip writing the cargo lockfile back after resolving. You may want to set this if your dependency versions are maintained externally through a non-trivial set-up. But you probably don't want to set this. | Boolean | optional | False |
| strip_internal_dependencies_from_cargo_lockfile | Whether to strip internal dependencies from the cargo lockfile. You may want to use this if you want to maintain a cargo lockfile for bazel only. Bazel only requires external dependencies to be present in the lockfile. By removing internal dependencies, the lockfile changes less frequently which reduces merge conflicts in other lockfiles where the cargo lockfile's sha is stored. | Boolean | optional | False |
| supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "wasm32-unknown-unknown", "wasm32-wasip1", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu"] |
from_specs
Generates a repo @crates from the defined spec tags.
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | The name of the repo to generate. | Name | optional | "crates" |
| cargo_config | A Cargo configuration file. | Label | optional | None |
| cargo_lockfile | The path to an existing Cargo.lock file | Label | optional | None |
| generate_binaries | Whether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated. | Boolean | optional | False |
| generate_build_scripts | Whether or not to generate cargo build scripts by default. | Boolean | optional | True |
| host_tools | The rust_host_tools repository to use. | Label | optional | "@@rules_rust++rust_host_tools+rust_host_tools//:rust_host_tools" |
| isolated | If true, CARGO_HOME will be overwritten to a directory within the generated repository in order to prevent other uses of Cargo from impacting having any effect on the generated targets produced by this rule. For users who either have multiple crate_repository definitions in a WORKSPACE or rapidly re-pin dependencies, setting this to false may improve build times. This variable is also controlled by CARGO_BAZEL_ISOLATED environment variable. | Boolean | optional | True |
| lockfile | The path to a file to use for reproducible renderings. If set, this file must exist within the workspace (but can be empty) before this rule will work. | Label | optional | None |
| skip_cargo_lockfile_overwrite | Whether to skip writing the cargo lockfile back after resolving. You may want to set this if your dependency versions are maintained externally through a non-trivial set-up. But you probably don't want to set this. | Boolean | optional | False |
| strip_internal_dependencies_from_cargo_lockfile | Whether to strip internal dependencies from the cargo lockfile. You may want to use this if you want to maintain a cargo lockfile for bazel only. Bazel only requires external dependencies to be present in the lockfile. By removing internal dependencies, the lockfile changes less frequently which reduces merge conflicts in other lockfiles where the cargo lockfile's sha is stored. | Boolean | optional | False |
| supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "wasm32-unknown-unknown", "wasm32-wasip1", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu"] |
render_config
Various settings used to configure rendered outputs.
The template parameters each support a select number of format keys. A description of each key can be found below where the supported keys for each template can be found in the parameter docs
| key | definition |
|---|---|
name | The name of the crate. Eg tokio |
repository | The rendered repository name for the crate. Directly relates to crate_repository_template. |
triple | A platform triple. Eg x86_64-unknown-linux-gnu |
version | The crate version. Eg 1.2.3 |
target | The library or binary target of the crate |
file | The basename of a file |
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| build_file_template | The base template to use for BUILD file names. The available format keys are [{name}, {version}`]. | String | optional | "//:BUILD.{name}-{version}.bazel" |
| crate_alias_template | The base template to use for crate labels. The available format keys are [{repository}, {name}, {version}, {target}]. | String | optional | "@{repository}//:{name}-{version}-{target}" |
| crate_label_template | The base template to use for crate labels. The available format keys are [{repository}, {name}, {version}, {target}]. | String | optional | "@{repository}__{name}-{version}//:{target}" |
| crate_repository_template | The base template to use for Crate label repository names. The available format keys are [{repository}, {name}, {version}]. | String | optional | "{repository}__{name}-{version}" |
| crates_module_template | The pattern to use for the defs.bzl and BUILD.bazel file names used for the crates module. The available format keys are [{file}]. | String | optional | "//:{file}" |
| default_alias_rule_bzl | Alias rule to use when generating aliases for all crates. Acceptable values are 'alias', 'dbg'/'fastbuild'/'opt' (transitions each crate's compilation_mode) or a string representing a rule in the form '<label to .bzl>: | Label | optional | None |
| default_alias_rule_name | Alias rule to use when generating aliases for all crates. Acceptable values are 'alias', 'dbg'/'fastbuild'/'opt' (transitions each crate's compilation_mode) or a string representing a rule in the form '<label to .bzl>: | String | optional | "alias" |
| default_package_name | The default package name to use in the rendered macros. This affects the auto package detection of things like all_crate_deps. | String | optional | "" |
| generate_cargo_toml_env_vars | Whether to generate cargo_toml_env_vars targets. | Boolean | optional | True |
| generate_rules_license_metadata | Whether to generate rules license metadata. | Boolean | optional | False |
| generate_target_compatible_with | Whether to generate target_compatible_with annotations on the generated BUILD files. This catches a target_triple being targeted that isn't declared in supported_platform_triples. | Boolean | optional | True |
| platforms_template | The base template to use for platform names. See platforms documentation. The available format keys are [{triple}]. | String | optional | "@rules_rust//rust/platform:{triple}" |
| regen_command | An optional command to demonstrate how generated files should be regenerated. | String | optional | "" |
| repositories | A list of repository names specified from crate.from_cargo(name=...) that this annotation is applied to. Defaults to all repositories. | List of strings | optional | [] |
| vendor_mode | An optional configuration for rendering content to be rendered into repositories. | String | optional | "" |
spec
A constructor for a crate dependency.
Attributes
splicing_config
Various settings used to configure Cargo manifest splicing behavior.
Attributes
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| repositories | A list of repository names specified from crate.from_cargo(name=...) that this annotation is applied to. Defaults to all repositories. | List of strings | optional | [] |
| resolver_version | The resolver version to use in generated Cargo manifests. This flag is only used when splicing a manifest from direct package definitions. See crates_repository::packages | String | optional | "2" |
Upstream Tooling
rules_rust manages versions of things like rustc. If you want to manually run upstream tooling configured at the versions, plugins and such that rules_rust has configured, rules_rust exposes these as targets in @rules_rust//tools/upstream_wrapper:
% bazel query @rules_rust//tools/upstream_wrapper
@rules_rust//tools/upstream_wrapper:cargo
@rules_rust//tools/upstream_wrapper:cargo_clippy
@rules_rust//tools/upstream_wrapper:rustc
@rules_rust//tools/upstream_wrapper:rustfmt
You can run them via bazel run, e.g. bazel run @rules_rust//tools/upstream_wrapper:cargo -- check.
IDE Integrations
VSCode
Intellisense
The best intellisense integrations to date are documented for rust-analyzer. Please refer to this documentation for setup instructions.
Debugging
rules_rust offers tooling to generate VSCode targets for running rust_binary and rust_test targets with a debugger in VSCode.
Prerequisites
Install CodeLLDB extension in VSCode.
Generate Launch Configurations
Generate VSCode launch.json for debugging all Rust targets in the current workspace:
bazel run @rules_rust//tools/vscode:gen_launch_json
To scope debug generated launch.json targets, query patterns can be passed:
bazel run @rules_rust//tools/vscode:gen_launch_json -- //path/to/...
Bazel targets should now be available for debugging via the "Run and Debug" menu.
Extensions
rules_rust_bindgen
These rules are for using Bindgen to generate Rust bindings to C (and some C++) libraries.
Rules
Setup
To use the Rust bindgen rules, add the following to your MODULE.bazel file:
bazel_dep(name = "rules_rust_bindgen", version = "{SEE_RELEASE_NOTES}")
rules_rust_bindgen does not automatically register a bindgen toolchain.
You need to register either your own or the default toolchain by adding the following to your MODULE.bazel file:
register_toolchains("@rules_rust_bindgen//:default_bindgen_toolchain")
The default toolchain builds libclang from source via the llvm-project bazel_dep. examples/bindgen_toolchain shows how to use a prebuilt libclang.
Bindgen aims to be as hermetic as possible so will end up building libclang from llvm-project from
source. If this is found to be undesirable, users should define their own repositories using something akin to
crate_universe and define their own toolchains following the instructions for
rust_bindgen_toolchain.
rust_bindgen
load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen")
rust_bindgen(name, bindgen_flags, cc_lib, clang_flags, header, merge_cc_lib_objects_into_rlib,
wrap_static_fns)
Generates a rust source file from a cc_library and a header.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| bindgen_flags | Flags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details. | List of strings | optional | [] |
| cc_lib | The cc_library that contains the .h file. This is used to find the transitive includes. | Label | required | |
| clang_flags | Flags to pass directly to the clang executable. | List of strings | optional | [] |
| header | The .h file to generate bindings for. | Label | required | |
| merge_cc_lib_objects_into_rlib | When True, objects from cc_lib will be copied into the rlib archive produced by the rust_library that depends on this rust_bindgen rule (using BuildInfo provider) | Boolean | optional | True |
| wrap_static_fns | Whether to create a separate .c file for static fns. Requires nightly toolchain, and a header that actually needs this feature (otherwise bindgen won't generate the file and Bazel complains). | Boolean | optional | False |
rust_bindgen_toolchain
load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen_toolchain")
rust_bindgen_toolchain(name, bindgen, clang, default_rustfmt, libclang, libstdcxx)
The tools required for the rust_bindgen rule.
This rule depends on the bindgen binary crate, and it
in turn depends on both a clang binary and the clang library. To obtain these dependencies,
rust_bindgen_dependencies imports bindgen and its dependencies.
load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen_toolchain")
rust_bindgen_toolchain(
name = "bindgen_toolchain_impl",
bindgen = "//my/rust:bindgen",
clang = "//my/clang:clang",
libclang = "//my/clang:libclang.so",
libstdcxx = "//my/cpp:libstdc++",
)
toolchain(
name = "bindgen_toolchain",
toolchain = "bindgen_toolchain_impl",
toolchain_type = "@rules_rust_bindgen//:toolchain_type",
)
This toolchain will then need to be registered in the current WORKSPACE.
For additional information, see the Bazel toolchains documentation.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| bindgen | The label of a bindgen executable. | Label | optional | None |
| clang | The label of a clang executable. | Label | optional | None |
| default_rustfmt | If set, rust_bindgen targets will always format generated sources with rustfmt. | Boolean | optional | True |
| libclang | A cc_library providing bindgen's runtime dependency on libclang. This attribute is required for hermeticity when bindgen is dynamically linked. If None, bindgen must be statically linked; else, system libraries will be used instead. | Label | optional | None |
| libstdcxx | A cc_library that satisfies libclang's libstdc++ dependency. This is used to make the execution of clang hermetic. If None, system libraries will be used instead. | Label | optional | None |
rust_bindgen_library
load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen_library")
rust_bindgen_library(name, header, cc_lib, bindgen_flags, bindgen_features, clang_flags,
wrap_static_fns, **kwargs)
Generates a rust source file for header, and builds a rust_library.
Arguments are the same as rust_bindgen, and kwargs are passed directly to rust_library.
PARAMETERS
rules_rust_mdbook
Bazel rules for mdBook.
Rules
Setup
bazel_dep(name = "rules_rust_mdbook", version = "{SEE_RELEASE_NOTES}")
mdbook
load("@rules_rust_mdbook//:defs.bzl", "mdbook")
mdbook(name, srcs, book, plugins)
Rules to create book from markdown files using mdBook.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| srcs | All inputs to the book. | List of labels | optional | [] |
| book | The book.toml file. | Label | required | |
| plugins | Executables to inject into PATH for use in preprocessor commands. | List of labels | optional | [] |
mdbook_server
load("@rules_rust_mdbook//:defs.bzl", "mdbook_server")
mdbook_server(name, book, hostname, port)
Spawn an mdbook server for a given mdbook target.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| book | The mdbook target to serve. | Label | required | |
| hostname | The default hostname to use (Can be overridden on the command line). | String | optional | "localhost" |
| port | The default port to use (Can be overridden on the command line). | String | optional | "3000" |
mdbook_toolchain
load("@rules_rust_mdbook//:defs.bzl", "mdbook_toolchain")
mdbook_toolchain(name, mdbook, plugins)
A mdBook toolchain.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| mdbook | A mdBook binary. | Label | required | |
| plugins | Executables to inject into PATH for use in preprocessor commands. | List of labels | optional | [] |
rules_rust_prost
These build rules are used for building protobufs/gRPC in Rust with Bazel using Prost and Tonic
Rules
Setup
bazel_dep(name = "rules_rust_prost", version = "{SEE_RELEASE_NOTES}")
The prost and tonic rules do not specify a default toolchain in order to avoid mismatched
dependency issues. To setup the prost and tonic toolchain, please see the section
Customizing prost and tonic Dependencies.
For additional information about Bazel toolchains, see here.
Customizing prost and tonic Dependencies
These rules depend on the prost and tonic dependencies. To setup the necessary toolchain
for these rules, you must define a toolchain with the prost, prost-types, tonic, protoc-gen-prost, and protoc-gen-tonic crates as well as the protoc binary.
To get access to these crates, you can use the crate_universe repository rules. For example:
load("//crate_universe:defs.bzl", "crate", "crates_repository")
crates_repository(
name = "crates_io",
annotations = {
"protoc-gen-prost": [crate.annotation(
gen_binaries = ["protoc-gen-prost"],
patch_args = [
"-p1",
],
patches = [
# Note: You will need to use this patch until a version greater than `0.2.2` of
# `protoc-gen-prost` is released.
"@rules_rust//proto/prost/private/3rdparty/patches:protoc-gen-prost.patch",
],
)],
"protoc-gen-tonic": [crate.annotation(
gen_binaries = ["protoc-gen-tonic"],
)],
},
cargo_lockfile = "Cargo.Bazel.lock",
mode = "remote",
packages = {
"prost": crate.spec(
version = "0",
),
"prost-types": crate.spec(
version = "0",
),
"protoc-gen-prost": crate.spec(
version = "0",
),
"protoc-gen-tonic": crate.spec(
version = "0",
),
"tonic": crate.spec(
version = "0",
),
},
repository_name = "rules_rust_prost",
tags = ["manual"],
)
You can then define a toolchain with the rust_prost_toolchain rule which uses the crates
defined above. For example:
load("@rules_rust//proto/prost:defs.bzl", "rust_prost_toolchain")
load("@rules_rust//rust:defs.bzl", "rust_library_group")
rust_library_group(
name = "prost_runtime",
deps = [
"@crates_io//:prost",
],
)
rust_library_group(
name = "tonic_runtime",
deps = [
":prost_runtime",
"@crates_io//:tonic",
],
)
rust_prost_toolchain(
name = "prost_toolchain_impl",
prost_plugin = "@crates_io//:protoc-gen-prost__protoc-gen-prost",
prost_runtime = ":prost_runtime",
prost_types = "@crates_io//:prost-types",
proto_compiler = "@com_google_protobuf//:protoc",
tonic_plugin = "@crates_io//:protoc-gen-tonic__protoc-gen-tonic",
tonic_runtime = ":tonic_runtime",
)
toolchain(
name = "prost_toolchain",
toolchain = "prost_toolchain_impl",
toolchain_type = "@rules_rust//proto/prost:toolchain_type",
)
Lastly, you must register the toolchain in your MODULE.bazel file. For example:
register_toolchains("//toolchains:prost_toolchain")
rust_prost_library
load("@rules_rust_prost//:defs.bzl", "rust_prost_library")
rust_prost_library(name, proto)
A rule for generating a Rust library using Prost.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| proto | A proto_library target for which to generate Rust gencode. | Label | required |
rust_prost_toolchain
load("@rules_rust_prost//:defs.bzl", "rust_prost_toolchain")
rust_prost_toolchain(name, compile_well_known_types, include_transitive_deps, prost_opts,
prost_plugin, prost_plugin_flag, prost_runtime, prost_types, proto_compiler,
tonic_opts, tonic_plugin, tonic_plugin_flag, tonic_runtime)
Rust Prost toolchain rule.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| compile_well_known_types | Corresponds to prost_build's compile_well_known_types option. If set to False, well-known-types will not be compiled by prost, and instead rely on the provided Prost types crate. | Boolean | optional | True |
| include_transitive_deps | Whether to include transitive dependencies. If set to True, all transitive dependencies will directly accessible by the dependent crate. | Boolean | optional | False |
| prost_opts | Additional options to add to Prost. | List of strings | optional | [] |
| prost_plugin | Additional plugins to add to Prost. | Label | required | |
| prost_plugin_flag | Prost plugin flag format. (e.g. --plugin=protoc-gen-prost=%s) | String | optional | "--plugin=protoc-gen-prost=%s" |
| prost_runtime | The Prost runtime crates to use. | Label | required | |
| prost_types | The Prost types crates to use. | Label | required | |
| proto_compiler | The protoc compiler to use. Note that this attribute is deprecated - prefer to use --incompatible_enable_proto_toolchain_resolution. | Label | optional | None |
| tonic_opts | Additional options to add to Tonic. | List of strings | optional | [] |
| tonic_plugin | Additional plugins to add to Tonic. | Label | optional | None |
| tonic_plugin_flag | Tonic plugin flag format. (e.g. --plugin=protoc-gen-tonic=%s)) | String | optional | "--plugin=protoc-gen-tonic=%s" |
| tonic_runtime | The Tonic runtime crates to use. | Label | optional | None |
rust_prost_transform
load("@rules_rust_prost//:defs.bzl", "rust_prost_transform")
rust_prost_transform(name, deps, srcs, crate_name, prost_opts, tonic_opts)
A rule for transforming the outputs of ProstGenProto actions.
This rule is used by adding it to the data attribute of proto_library targets. E.g.
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_rust_prost//:defs.bzl", "rust_prost_library", "rust_prost_transform")
rust_prost_transform(
name = "a_transform",
srcs = [
"a_src.rs",
],
)
proto_library(
name = "a_proto",
srcs = [
"a.proto",
],
data = [
":transform",
],
)
rust_prost_library(
name = "a_rs_proto",
proto = ":a_proto",
)
The rust_prost_library will spawn an action on the a_proto target which consumes the
a_transform rule to provide a means of granularly modifying a proto library for ProstGenProto
actions with minimal impact to other consumers.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| deps | Additional dependencies to add to the compiled crate. | List of labels | optional | [] |
| srcs | Additional source files to include in generated Prost source code. | List of labels | optional | [] |
| crate_name | The name of the crate generated by Prost. This is used to override the default name which is the name of the proto_library target. | String | optional | "" |
| prost_opts | Additional options to add to Prost. | List of strings | optional | [] |
| tonic_opts | Additional options to add to Tonic. | List of strings | optional | [] |
rules_rust_pyo3
pyo3_toolchain
load("@rules_rust_pyo3//:defs.bzl", "pyo3_toolchain")
pyo3_toolchain(name)
Define a toolchain which generates config data for the PyO3 for producing extension modules on any target platform.
Note that this toolchain expects the pyo3 crate to be built with the following features:
abi3abi3-py3*(e.gabi3-py311)extension-module
When using rules_rust's crate_universe, this data can be plubmed into the target using the following snippet.
annotations = {
"pyo3-build-config": [
crate.annotation(
build_script_data = [
"@rules_rust_pyo3//:current_pyo3_toolchain",
],
build_script_env = {
"PYO3_CROSS": "$(PYO3_CROSS)",
"PYO3_CROSS_LIB_DIR": "$(PYO3_CROSS_LIB_DIR)",
"PYO3_CROSS_PYTHON_IMPLEMENTATION": "$(PYO3_CROSS_PYTHON_IMPLEMENTATION)",
"PYO3_CROSS_PYTHON_VERSION": "$(PYO3_CROSS_PYTHON_VERSION)",
"PYO3_NO_PYTHON": "$(PYO3_NO_PYTHON)",
"PYO3_PYTHON": "$(PYO3_PYTHON)",
},
build_script_toolchains = [
"@rules_rust_pyo3//:current_pyo3_toolchain",
],
),
],
"pyo3-ffi": [
crate.annotation(
build_script_data = [
"@rules_rust_pyo3//:current_pyo3_toolchain",
],
build_script_env = {
"PYO3_CROSS": "$(PYO3_CROSS)",
"PYO3_CROSS_LIB_DIR": "$(PYO3_CROSS_LIB_DIR)",
"PYO3_CROSS_PYTHON_IMPLEMENTATION": "$(PYO3_CROSS_PYTHON_IMPLEMENTATION)",
"PYO3_CROSS_PYTHON_VERSION": "$(PYO3_CROSS_PYTHON_VERSION)",
"PYO3_NO_PYTHON": "$(PYO3_NO_PYTHON)",
"PYO3_PYTHON": "$(PYO3_PYTHON)",
},
build_script_toolchains = [
"@rules_rust_pyo3//:current_pyo3_toolchain",
],
),
],
},
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required |
rust_pyo3_toolchain
load("@rules_rust_pyo3//:defs.bzl", "rust_pyo3_toolchain")
rust_pyo3_toolchain(name, pyo3, pyo3_introspection)
Define a toolchain for PyO3 Rust dependencies which power internal rules.
This toolchain is how the rules know which version of pyo3 to link against.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| pyo3 | The PyO3 library. | Label | required | |
| pyo3_introspection | The PyO3 introspection library. | Label | required |
pyo3_extension
load("@rules_rust_pyo3//:defs.bzl", "pyo3_extension")
pyo3_extension(*, name, srcs, aliases, compile_data, crate_features, crate_root, data, deps,
edition, imports, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stubs,
version, compilation_mode, module_name, **kwargs)
Define a PyO3 python extension module.
This target is consumed just as a py_library would be.
PARAMETERS
| Name | Description | Default Value |
|---|---|---|
| name | The name of the target. | none |
| srcs | List of Rust .rs source files used to build the library. For more details see rust_shared_library. | none |
| aliases | Remap crates to a new name or moniker for linkage to this target. For more details see rust_shared_library. | {} |
| compile_data | List of files used by this rule at compile time. For more details see rust_shared_library. | [] |
| crate_features | List of features to enable for this crate. For more details see rust_shared_library. | [] |
| crate_root | The file that will be passed to rustc to be used for building this crate. For more details see rust_shared_library. | None |
| data | List of files used by this rule at compile time and runtime. For more details see rust_shared_library. | [] |
| deps | List of other libraries to be linked to this library target. For more details see rust_shared_library. | [] |
| edition | The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain. For more details see rust_shared_library. | None |
| imports | List of import directories to be added to the PYTHONPATH. For more details see py_library.imports. | [] |
| proc_macro_deps | List of rust_proc_macro targets used to help build this library target. For more details see rust_shared_library. | [] |
| rustc_env | Dictionary of additional "key": "value" environment variables to set for rustc. For more details see rust_shared_library. | {} |
| rustc_env_files | Files containing additional environment variables to set for rustc. For more details see rust_shared_library. | [] |
| rustc_flags | List of compiler flags passed to rustc. For more details see rust_shared_library. | [] |
| stubs | Whether or not to generate stubs (.pyi file) for the module. | None |
| version | A version to inject in the cargo environment variable. For more details see rust_shared_library. | None |
| compilation_mode | The compilation_mode value to build the extension for. If set to "current", the current configuration will be used. | "opt" |
| module_name | A full dotted Python module path implemented by this extension (e.g. foo.bar). | None |
| kwargs | Additional keyword arguments. | none |
rules_rust_wasm_bindgen
Bazel rules for generating wasm modules for Javascript using wasm-bindgen.
Rules
Setup
To begin using the wasm-bindgen rules, add the following to your MODULE.bazel file:
bazel_dep(name = "rules_rust_wasm_bindgen", version = "{SEE_RELEASE_NOTES}")
This should enable users to start using the rust_wasm_bindgen
rule. However, it's common to want to control the version of wasm-bindgen in the
workspace instead of relying on the one provided by rules_rust. In this case, users
should use the rust_wasm_bindgen_toolchain rule to
define their own toolchains to register.
Interfacing with Javascript rules
Rules for doing so can be found at rules_js_rust_wasm_bindgen
rust_wasm_bindgen
load("@rules_rust_wasm_bindgen//:defs.bzl", "rust_wasm_bindgen")
rust_wasm_bindgen(name, bindgen_flags, out_name, target, target_arch, wasm_file)
Generates javascript and typescript bindings for a webassembly module using wasm-bindgen.
An example of this rule in use can be seen at @rules_rust//examples/wasm
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| bindgen_flags | Flags to pass directly to the wasm-bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details. | List of strings | optional | [] |
| out_name | Set a custom output filename (Without extension. Defaults to target name). | String | optional | "" |
| target | The type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details. | String | optional | "bundler" |
| target_arch | The target architecture to use for the wasm-bindgen command line option. | String | optional | "wasm32" |
| wasm_file | The .wasm crate to generate bindings for. | Label | required |
rust_wasm_bindgen_toolchain
load("@rules_rust_wasm_bindgen//:defs.bzl", "rust_wasm_bindgen_toolchain")
rust_wasm_bindgen_toolchain(name, browser, browser_type, wasm_bindgen_cli, wasm_bindgen_test,
wasm_bindgen_test_runner, webdriver, webdriver_args, webdriver_json)
The tools required for the rust_wasm_bindgen rule.
In cases where users want to control or change the version of wasm-bindgen used by rust_wasm_bindgen,
a unique toolchain can be created as in the example below:
load("@rules_rust_wasm_bindgen//:defs.bzl", "rust_wasm_bindgen_toolchain")
rust_wasm_bindgen_toolchain(
wasm_bindgen_cli = "//3rdparty/crates:wasm_bindgen_cli__bin",
)
toolchain(
name = "wasm_bindgen_toolchain",
toolchain = "wasm_bindgen_toolchain_impl",
toolchain_type = "@rules_rust_wasm_bindgen//:toolchain_type",
)
Now that you have your own toolchain, you need to register it by
inserting the following statement in your WORKSPACE file:
register_toolchains("//my/toolchains:wasm_bindgen_toolchain")
For additional information, see the Bazel toolchains documentation.
ATTRIBUTES
| Name | Description | Type | Mandatory | Default |
|---|---|---|---|---|
| name | A unique name for this target. | Name | required | |
| browser | The browser entrypoint. | Label | optional | None |
| browser_type | The type of browser provided. | String | optional | "" |
| wasm_bindgen_cli | The label of a wasm-bindgen-cli executable. | Label | optional | None |
| wasm_bindgen_test | The label of a wasm-bindgen-test crate. | Label | optional | None |
| wasm_bindgen_test_runner | The label of a wasm-bindgen-test-runner binary. | Label | optional | None |
| webdriver | The webdriver to use. | Label | optional | None |
| webdriver_args | Arguments to pass to the webdriver binary. | List of strings | optional | [] |
| webdriver_json | The webdriver.json config file for wasm-bindgen-test. | Label | optional | None |
RustWasmBindgenInfo
load("@rules_rust_wasm_bindgen//:defs.bzl", "RustWasmBindgenInfo")
RustWasmBindgenInfo(js, root, snippets, ts, wasm)
Info about wasm-bindgen outputs.
FIELDS
rust_wasm_bindgen_test
load("@rules_rust_wasm_bindgen//:defs.bzl", "rust_wasm_bindgen_test")
rust_wasm_bindgen_test(*, name, aliases, compile_data, crate_features, data, edition, env,
env_inherit, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags,
target_arch, version, wasm, tags, **kwargs)
"A test rule for running wasm-bindgen tests."
PARAMETERS