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.
Bzlmod
Note that rules_rust bzlmod support is still a work in progress. Most features should work, but bugs are more likely. This is not a desired end-state - please report (or better yet, help fix!) bugs you run into.
To use rules_rust
in a project using bzlmod, add the following to your MODULE.bazel
file:
bazel_dep(name = "rules_rust", version = "0.48.0")
Don't forget to substitute in your desired release's version number.
WORKSPACE
To use rules_rust
in a project using a WORKSPACE file, add the following to your WORKSPACE
file to add the external repositories for the Rust toolchain:
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# To find additional information on this release or newer ones visit:
# https://github.com/bazelbuild/rules_rust/releases
http_archive(
name = "rules_rust",
integrity = "sha256-Weev1uz2QztBlDA88JX6A1N72SucD1V8lBsaliM0TTg=",
urls = ["https://github.com/bazelbuild/rules_rust/releases/download/0.48.0/rules_rust-v0.48.0.tar.gz"],
)
load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains")
rules_rust_dependencies()
rust_register_toolchains()
Don't forget to substitute in your desired release's version number and integrity hash.
Specifying Rust version
To build with a particular version of the Rust compiler, pass that version to rust_register_toolchains
:
rust_register_toolchains(
edition = "2021",
versions = [
"1.79.0"
],
)
As well as an exact version, versions
can accept nightly/{iso_date}
and beta/{iso_date}
strings for toolchains from different release channels.
rust_register_toolchains(
edition = "2021",
versions = [
"nightly/2024-06-13",
],
)
By default, a stable
and nightly
toolchain will be registered if no versions are passed to rust_register_toolchains
. However,
if only 1 version is passed and it is from the nightly
or beta
release channels (i.e. not stable
), then a build setting must
also be 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.
Supported bazel versions
The oldest version of Bazel the main
branch is tested against is 7.3.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.
Windows support for some features requires --enable_runfiles
to be passed to Bazel, we recommend putting it in your bazelrc. See Using Bazel on Windows for more Windows-specific recommendations.
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.rs
scripts. - crate_universe: Rules for generating Bazel targets for external crate dependencies.
Experimental rules
- rust_analyzer: rules for generating
rust-project.json
files for rust-analyzer
3rd party rules
- rust_bindgen: rules for generating C++ bindings.
- rust_proto: rules for generating protobuf and gRPC stubs.
- rust_wasm_bindgen: rules for generating WebAssembly bindings.
Full API
You can also browse the full API in one page.
Rust
- rust_binary
- rust_library
- rust_library_group
- rust_static_library
- rust_shared_library
- rust_proc_macro
- rust_test
- rust_test_suite
- error_format
- extra_rustc_flag
- extra_rustc_flags
- capture_clippy_output
capture_clippy_output
capture_clippy_output(name)
Control whether to print clippy output or store it to a file, using the configured error_format.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
error_format
error_format(name)
Change the --error-format flag from the command line with --@rules_rust//:error_format
. See rustc documentation for valid values.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
extra_rustc_flag
extra_rustc_flag(name)
Add additional rustc_flag from the command line with --@rules_rust//:extra_rustc_flag
. Multiple uses are accumulated and appended after the extra_rustc_flags.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
extra_rustc_flags
extra_rustc_flags(name)
Add additional rustc_flags from the command line with --@rules_rust//:extra_rustc_flags
. This flag should only be used for flags that need to be applied across the entire build. For options that apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); use --@rules_rust//:extra_exec_rustc_flags
to apply flags to the exec configuration.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
rust_binary
rust_binary(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, crate_type, edition, env, experimental_use_cc_common_link, linker_script, malloc, out_binary, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
out_binary | Force a target, regardless of it's crate_type , to always mark the file as executable. This attribute is only used to support wasm targets but is expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771. | Boolean | optional | False |
platform | Optional platform to transition the binary to. | Label | optional | None |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_library
rust_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, disable_pipelining, edition, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
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_proc_macro
rust_proc_macro(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_shared_library
rust_shared_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, experimental_use_cc_common_link, malloc, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
platform | Optional platform to transition the shared 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 | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_static_library
rust_static_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
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 | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_test
rust_test(name, deps, srcs, data, aliases, alwayslink, compile_data, crate, crate_features, crate_name, crate_root, edition, env, env_inherit, experimental_use_cc_common_link, malloc, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
platform | Optional platform to transition the test to. | Label | optional | None |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
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_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 underyling rust_test targets. The tags argument is also passed to the generated test_suite target. | none |
Rust Doc
rust_doc
rust_doc(name, crate, 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 | |
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
rust_doc_test(name, deps, crate)
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 |
Rust Clippy
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//:clippy.toml=//:clippy.toml
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
rust_clippy_aspect(name)
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
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
Rust Fmt
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//: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//: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.
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_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 |
rustfmt_aspect
rustfmt_aspect(name)
This aspect is used to gather information about a crate for use in rustfmt and perform rustfmt checks
Output Groups:
rustfmt_checks
: Executesrustfmt --check
on the specified target.
The build setting @rules_rust//: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
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
Rust Proto
- rust_prost_library
- rust_prost_toolchain
- rust_prost_dependencies
- rust_prost_transitive_repositories
- rust_proto_library
- rust_grpc_library
- rust_proto_protobuf_toolchain
- rust_proto_protobuf_dependencies
- rust_proto_protobuf_register_toolchains
- rust_proto_protobuf_transitive_repositories
Overview
These build rules are used for building protobufs/gRPC in Rust with Bazel.
There are two rule sets. The first ruleset defines the rust_prost_library
which generates Rust code
using the prost
and tonic
dependencies. The second ruleset defines the rust_proto_library
and
rust_grpc_library
rules which generate Rust code using the rust-protobuf
dependencies.
See the protobuf example for a more complete example of use.
Prost Setup
load("@rules_rust//proto/prost:repositories.bzl", "rust_prost_dependencies")
rust_prost_dependencies()
load("@rules_rust//proto/prost:transitive_repositories.bzl", "rust_prost_transitive_repositories")
rust_prost_transitive_repositories()
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 WORKSPACE
file. For example:
register_toolchains("//toolchains:prost_toolchain")
Rust-Protobuf Setup
To use the Rust proto rules, add the following to your WORKSPACE
file to add the
external repositories for the Rust proto toolchain (in addition to the rust rules setup):
load("@rules_rust//proto/protobuf:repositories.bzl", "rust_proto_protobuf_dependencies", "rust_proto_protobuf_register_toolchains")
rust_proto_protobuf_dependencies()
rust_proto_protobuf_register_toolchains()
load("@rules_rust//proto/protobuf:transitive_repositories.bzl", "rust_proto_protobuf_transitive_repositories")
rust_proto_protobuf_transitive_repositories()
This will load the required dependencies for the rust-protobuf
rules. It will also
register a default toolchain for the rust_proto_library
and rust_grpc_library
rules.
To customize the rust_proto_library
and rust_grpc_library
toolchain, please see the section
Customizing rust-protobuf
Dependencies.
For additional information about Bazel toolchains, see here.
Customizing rust-protobuf
Dependencies
These rules depend on the protobuf
and
the grpc
crates in addition to the protobuf
compiler. To obtain these crates,
rust_proto_repositories
imports the given crates using BUILD files generated with
crate_universe.
If you want to either change the protobuf and gRPC rust compilers, or to simply use crate_universe in a more complex scenario (with more dependencies), you must redefine those dependencies.
To do this, once you've imported the needed dependencies (see our @rules_rust//proto/3rdparty/BUILD.bazel file to see the default dependencies), you need to create your own toolchain. To do so you can create a BUILD file with your toolchain definition, for example:
load("@rules_rust//proto:toolchain.bzl", "rust_proto_toolchain")
rust_proto_toolchain(
name = "proto-toolchain-impl",
# Path to the protobuf compiler.
protoc = "@com_google_protobuf//:protoc",
# Protobuf compiler plugin to generate rust gRPC stubs.
grpc_plugin = "//3rdparty/crates:cargo_bin_protoc_gen_rust_grpc",
# Protobuf compiler plugin to generate rust protobuf stubs.
proto_plugin = "//3rdparty/crates:cargo_bin_protoc_gen_rust",
)
toolchain(
name = "proto-toolchain",
toolchain = ":proto-toolchain-impl",
toolchain_type = "@rules_rust//proto/protobuf: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:proto-toolchain")
Finally, you might want to set the rust_deps
attribute in
rust_proto_library
and rust_grpc_library
to change the compile-time
dependencies:
rust_proto_library(
...
rust_deps = ["//3rdparty/crates:protobuf"],
...
)
rust_grpc_library(
...
rust_deps = [
"//3rdparty/crates:protobuf",
"//3rdparty/crates:grpc",
"//3rdparty/crates:tls_api",
"//3rdparty/crates:tls_api_stub",
],
...
)
Note: Ideally, we would inject those dependencies from the toolchain, but due to bazelbuild/bazel#6889 all dependencies added via the toolchain ends-up being in the wrong configuration.
rust_grpc_library
rust_grpc_library(name, deps, crate_name, rust_deps, rustc_flags)
Builds a Rust library crate from a set of proto_library
s suitable for gRPC.
Example:
load("@rules_rust//proto/protobuf:defs.bzl", "rust_grpc_library")
proto_library(
name = "my_proto",
srcs = ["my.proto"]
)
rust_grpc_library(
name = "rust",
deps = [":my_proto"],
)
rust_binary(
name = "my_service",
srcs = ["my_service.rs"],
deps = [":rust"],
)
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
deps | List of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding gRPC stubs. | List of labels | required | |
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 | "" |
rust_deps | The crates the generated library depends on. | 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 | [] |
rust_prost_toolchain
rust_prost_toolchain(name, 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 | |
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_proto_library
rust_proto_library(name, deps, crate_name, rust_deps, rustc_flags)
Builds a Rust library crate from a set of proto_library
s.
Example:
load("@rules_rust//proto/protobuf:defs.bzl", "rust_proto_library")
proto_library(
name = "my_proto",
srcs = ["my.proto"]
)
rust_proto_library(
name = "rust",
deps = [":my_proto"],
)
rust_binary(
name = "my_proto_binary",
srcs = ["my_proto_binary.rs"],
deps = [":rust"],
)
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
deps | List of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding stubs. | List of labels | required | |
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 | "" |
rust_deps | The crates the generated library depends on. | 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 | [] |
rust_prost_dependencies
rust_prost_dependencies(bzlmod)
Declares repositories needed for prost.
PARAMETERS
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
rust_prost_library
rust_prost_library(name, kwargs)
A rule for generating a Rust library using Prost.
PARAMETERS
Name | Description | Default Value |
---|---|---|
name | The name of the target. | none |
kwargs | Additional keyword arguments for the underlying rust_prost_library rule. | none |
rust_prost_transitive_repositories
rust_prost_transitive_repositories()
Load transitive dependencies of the @rules_rust//proto/protobuf
rules.
This macro should be called immediately after the rust_protobuf_dependencies
macro.
rust_proto_protobuf_dependencies
rust_proto_protobuf_dependencies(bzlmod)
Sets up dependencies for rules_rust's proto support.
PARAMETERS
Name | Description | Default Value |
---|---|---|
bzlmod | Whether this function is being called from a bzlmod context rather than a workspace context. | False |
RETURNS
A list of structs containing information about root module deps to report to bzlmod's extension_metadata.
rust_proto_protobuf_register_toolchains
rust_proto_protobuf_register_toolchains(register_toolchains)
Register toolchains for proto compilation.
PARAMETERS
rust_proto_protobuf_transitive_repositories
rust_proto_protobuf_transitive_repositories()
Load transitive dependencies of the @rules_rust//proto/protobuf
rules.
This macro should be called immediately after the rust_protobuf_dependencies
macro.
Rust Bindgen
- rust_bindgen_library
- rust_bindgen
- rust_bindgen_toolchain
- rust_bindgen_dependencies
- rust_bindgen_register_toolchains
Overview
These rules are for using Bindgen to generate Rust bindings to C (and some C++) libraries.
See the bindgen example for a more complete example of use.
Setup
To use the Rust bindgen rules, add the following to your WORKSPACE
file to add the
external repositories for the Rust bindgen toolchain (in addition to the rust rules setup):
load("@rules_rust//bindgen:repositories.bzl", "rust_bindgen_dependencies", "rust_bindgen_register_toolchains")
rust_bindgen_dependencies()
rust_bindgen_register_toolchains()
load("@rules_rust//bindgen:transitive_repositories.bzl", "rust_bindgen_transitive_dependencies")
rust_bindgen_transitive_dependencies()
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 then no Bindgen related calls should be added to your WORKSPACE and instead
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
rust_bindgen(name, bindgen_flags, cc_lib, clang_flags, header, 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 | |
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
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 that provides bindgen's runtime dependency on libclang. | 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_dependencies
rust_bindgen_dependencies()
Declare dependencies needed for bindgen.
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
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
rust_bindgen_register_toolchains
rust_bindgen_register_toolchains(register_toolchains)
Registers the default toolchains for the rules_rust
bindgen rules.
PARAMETERS
Rust Wasm Bindgen
- rust_wasm_bindgen_dependencies
- rust_wasm_bindgen_register_toolchains
- rust_wasm_bindgen_toolchain
- rust_wasm_bindgen
- RustWasmBindgenInfo
Overview
Bazel rules for generating wasm modules for Javascript using wasm-bindgen.
Setup
To begin using the wasm-bindgen
rules, users can load the necessary dependencies
in their workspace by adding the following to their WORKSPACE.bazel
file.
load("@rules_rust//wasm_bindgen:repositories.bzl", "rust_wasm_bindgen_dependencies", "rust_wasm_bindgen_register_toolchains")
rust_wasm_bindgen_dependencies()
rust_wasm_bindgen_register_toolchains()
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 avoid calling rust_wasm_bindgen_register_toolchains
and instead use the
rust_wasm_bindgen_toolchain rule to define their own
toolchains to register in the workspace.
Interfacing with Javascript rules
While it's recommended for users to mantain their own , in the
@rules_rust//wasm_bindgen
package there exists interface sub-packages for various
Javascript Bazel rules. E.g. build_bazel_rules_nodejs
or aspect_rules_js
. The
rules defined there are a more convenient way to use rust_wasm_bindgen
with the
associated javascript rules due to the inclusion of additional providers. Each
directory contains a defs.bzl
file that defines the different variants of
rust_wasm_bindgen
. (e.g. nodejs_rust_wasm_bindgen
for the rules_nodejs
submodule).
rust_wasm_bindgen
rust_wasm_bindgen(name, bindgen_flags, 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 bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details. | List of strings | 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 file or crate to generate bindings for. | Label | required |
rust_wasm_bindgen_toolchain
rust_wasm_bindgen_toolchain(name, bindgen)
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//bindgen:bindgen.bzl", "rust_bindgen_toolchain")
rust_bindgen_toolchain(
bindgen = "//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 | |
bindgen | The label of a wasm-bindgen-cli executable. | Label | optional | None |
RustWasmBindgenInfo
RustWasmBindgenInfo(js, ts, wasm)
Info about wasm-bindgen outputs.
FIELDS
Name | Description |
---|---|
js | Depset[File]: The Javascript files produced by wasm-bindgen . |
ts | Depset[File]: The Typescript files produced by wasm-bindgen . |
wasm | File: The .wasm file generated by wasm-bindgen . |
rust_wasm_bindgen_dependencies
rust_wasm_bindgen_dependencies()
Declare dependencies needed for the rules_rust
wasm-bindgen rules.
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
rust_wasm_bindgen_register_toolchains
rust_wasm_bindgen_register_toolchains(register_toolchains)
Registers the default toolchains for the rules_rust
wasm-bindgen rules.
PARAMETERS
Cargo
cargo_dep_env
cargo_dep_env(name, src, out_dir)
A rule for generating variables for dependent cargo_build_script
s 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 |
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, 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
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
cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_lockfile, cargo_toml, env, env_label, repo_mapping, 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 | Souce 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_lockfile | The lockfile of the crate_universe resolver | Label | required | |
cargo_toml | The path of the crate_universe resolver manifest (Cargo.toml file) | Label | required | |
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 | {} |
repo_mapping | In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target , it should actually resolve that dependency within globally-declared @bar (@bar//some:target ).This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function). | 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.81.0" |
Rust Analyzer
Overview
For non-Cargo projects,
rust-analyzer depends on a rust-project.json
file at the
root of the project that describes its structure. The rust_analyzer
rule facilitates generating
such a file.
Setup
First, ensure rules_rust
is setup in your workspace. By default, rust_register_toolchains
will
ensure a rust_analyzer_toolchain is registered within the WORKSPACE.
Next, load the dependencies for the rust-project.json
generator tool:
load("@rules_rust//tools/rust_analyzer:deps.bzl", "rust_analyzer_dependencies")
rust_analyzer_dependencies()
Finally, run 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.
For users who do not use rust_register_toolchains
to register toolchains, the following can be added
to their WORKSPACE to register a rust_analyzer_toolchain
. Please make sure the Rust version used in
this toolchain matches the version used by the currently registered toolchain or the sources/documentation
will not match what's being compiled with and can lead to confusing results.
load("@rules_rust//rust:repositories.bzl", "rust_analyzer_toolchain_repository")
register_toolchains(rust_analyzer_toolchain_repository(
name = "rust_analyzer_toolchain",
# This should match the currently registered toolchain.
version = "1.63.0",
))
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",
"//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//: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.
rust_analyzer_toolchain
rust_analyzer_toolchain(name, proc_macro_srv, rustc, rustc_srcs)
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 |
rustc | The path to a rustc binary. | Label | required | |
rustc_srcs | The source code of rustc. | Label | required |
rust_analyzer_aspect
rust_analyzer_aspect(name)
Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json
ASPECT ATTRIBUTES
Name | Type |
---|---|
deps | String |
proc_macro_deps | String |
crate | String |
actual | String |
proto | String |
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
Rust rules
- CrateInfo
- DepInfo
- RustWasmBindgenInfo
- StdLibInfo
- capture_clippy_output
- cargo_bootstrap_repository
- cargo_build_script
- cargo_dep_env
- cargo_env
- error_format
- extra_rustc_flag
- extra_rustc_flags
- fail_when_enabled
- incompatible_flag
- rules_rust_dependencies
- rust_analyzer_aspect
- rust_analyzer_toolchain
- rust_analyzer_toolchain_repository
- rust_binary
- rust_bindgen
- rust_bindgen_dependencies
- rust_bindgen_library
- rust_bindgen_register_toolchains
- rust_bindgen_toolchain
- rust_clippy
- rust_clippy_aspect
- rust_doc
- rust_doc_test
- rust_grpc_library
- rust_library
- rust_library_group
- rust_proc_macro
- rust_prost_dependencies
- rust_prost_library
- rust_prost_toolchain
- rust_prost_transitive_repositories
- rust_proto_library
- rust_proto_protobuf_dependencies
- rust_proto_protobuf_register_toolchains
- rust_proto_protobuf_toolchain
- rust_proto_protobuf_transitive_repositories
- rust_register_toolchains
- rust_repositories
- rust_repository_set
- rust_shared_library
- rust_static_library
- rust_stdlib_filegroup
- rust_test
- rust_test_suite
- rust_toolchain
- rust_toolchain_repository
- rust_toolchain_repository_proxy
- rust_toolchain_tools_repository
- rust_wasm_bindgen
- rust_wasm_bindgen_dependencies
- rust_wasm_bindgen_register_toolchains
- rust_wasm_bindgen_toolchain
- rustfmt_aspect
- rustfmt_test
- rustfmt_toolchain
capture_clippy_output
capture_clippy_output(name)
Control whether to print clippy output or store it to a file, using the configured error_format.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
cargo_dep_env
cargo_dep_env(name, src, out_dir)
A rule for generating variables for dependent cargo_build_script
s 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 |
error_format
error_format(name)
Change the --error-format flag from the command line with --@rules_rust//:error_format
. See rustc documentation for valid values.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
extra_rustc_flag
extra_rustc_flag(name)
Add additional rustc_flag from the command line with --@rules_rust//:extra_rustc_flag
. Multiple uses are accumulated and appended after the extra_rustc_flags.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
extra_rustc_flags
extra_rustc_flags(name)
Add additional rustc_flags from the command line with --@rules_rust//:extra_rustc_flags
. This flag should only be used for flags that need to be applied across the entire build. For options that apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); use --@rules_rust//:extra_exec_rustc_flags
to apply flags to the exec configuration.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
incompatible_flag
incompatible_flag(name, issue)
A rule defining an incompatible flag.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
issue | The link to the github issue associated with this flag | String | required |
rust_analyzer_toolchain
rust_analyzer_toolchain(name, proc_macro_srv, rustc, rustc_srcs)
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 |
rustc | The path to a rustc binary. | Label | required | |
rustc_srcs | The source code of rustc. | Label | required |
rust_binary
rust_binary(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, crate_type, edition, env, experimental_use_cc_common_link, linker_script, malloc, out_binary, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
out_binary | Force a target, regardless of it's crate_type , to always mark the file as executable. This attribute is only used to support wasm targets but is expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771. | Boolean | optional | False |
platform | Optional platform to transition the binary to. | Label | optional | None |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_bindgen
rust_bindgen(name, bindgen_flags, cc_lib, clang_flags, header, 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 | |
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
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 that provides bindgen's runtime dependency on libclang. | 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_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_doc
rust_doc(name, crate, 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 | |
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
rust_doc_test(name, deps, crate)
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 |
rust_grpc_library
rust_grpc_library(name, deps, crate_name, rust_deps, rustc_flags)
Builds a Rust library crate from a set of proto_library
s suitable for gRPC.
Example:
load("@rules_rust//proto/protobuf:defs.bzl", "rust_grpc_library")
proto_library(
name = "my_proto",
srcs = ["my.proto"]
)
rust_grpc_library(
name = "rust",
deps = [":my_proto"],
)
rust_binary(
name = "my_service",
srcs = ["my_service.rs"],
deps = [":rust"],
)
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
deps | List of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding gRPC stubs. | List of labels | required | |
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 | "" |
rust_deps | The crates the generated library depends on. | 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 | [] |
rust_library
rust_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, disable_pipelining, edition, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
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_proc_macro
rust_proc_macro(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_prost_toolchain
rust_prost_toolchain(name, 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 | |
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_proto_library
rust_proto_library(name, deps, crate_name, rust_deps, rustc_flags)
Builds a Rust library crate from a set of proto_library
s.
Example:
load("@rules_rust//proto/protobuf:defs.bzl", "rust_proto_library")
proto_library(
name = "my_proto",
srcs = ["my.proto"]
)
rust_proto_library(
name = "rust",
deps = [":my_proto"],
)
rust_binary(
name = "my_proto_binary",
srcs = ["my_proto_binary.rs"],
deps = [":rust"],
)
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
deps | List of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding stubs. | List of labels | required | |
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 | "" |
rust_deps | The crates the generated library depends on. | 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 | [] |
rust_shared_library
rust_shared_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, experimental_use_cc_common_link, malloc, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
platform | Optional platform to transition the shared 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 | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_static_library
rust_static_library(name, deps, srcs, data, aliases, alwayslink, compile_data, crate_features, crate_name, crate_root, edition, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 | "" |
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 | [] |
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 |
version | A version to inject in the cargo environment variable. | String | optional | "0.0.0" |
rust_stdlib_filegroup
rust_stdlib_filegroup(name, srcs)
A dedicated filegroup-like rule for Rust stdlib artifacts.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
srcs | The list of targets/files that are components of the rust-stdlib file group | List of labels | required |
rust_test
rust_test(name, deps, srcs, data, aliases, alwayslink, compile_data, crate, crate_features, crate_name, crate_root, edition, env, env_inherit, experimental_use_cc_common_link, malloc, platform, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, stamp, 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 | {} |
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 |
malloc | Override the default dependency on malloc .By default, Rust binaries linked with cc_common.link are linked against @bazel_tools//tools/cpp: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 | "@bazel_tools//tools/cpp:malloc" |
platform | Optional platform to transition the test to. | Label | optional | None |
proc_macro_deps | List of rust_proc_macro targets used to help build this library target. | List of labels | optional | [] |
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 |
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_toolchain
rust_toolchain(name, allocator_library, binary_ext, cargo, cargo_clippy, clippy_driver, debug_info, default_edition, dylib_ext, env, exec_triple, experimental_link_std_dylib, experimental_use_cc_common_link, extra_exec_rustc_flags, extra_rustc_flags, extra_rustc_flags_for_crate_types, global_allocator_library, llvm_cov, llvm_profdata, llvm_tools, opt_level, per_crate_rustc_flags, rust_doc, rust_std, rustc, rustc_lib, rustfmt, staticlib_ext, stdlib_linkflags, strip_level, target_json, target_triple)
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.
See @rules_rust//rust:repositories.bzl
for examples of defining the @rust_cpuX
repository with the actual binaries and libraries.
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//ffi/cc/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 |
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_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 | 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. | 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//ffi/cc/global_allocator_library" |
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_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 |
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 | [] |
rust_doc | The location of the rustdoc binary. Can be a direct source or a filegroup containing one item. | Label | required | |
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. | 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 | "" |
rust_wasm_bindgen
rust_wasm_bindgen(name, bindgen_flags, 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 bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details. | List of strings | 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 file or crate to generate bindings for. | Label | required |
rust_wasm_bindgen_toolchain
rust_wasm_bindgen_toolchain(name, bindgen)
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//bindgen:bindgen.bzl", "rust_bindgen_toolchain")
rust_bindgen_toolchain(
bindgen = "//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 | |
bindgen | The label of a wasm-bindgen-cli executable. | Label | optional | None |
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_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 |
CrateInfo
CrateInfo(aliases, compile_data, compile_data_targets, data, deps, edition, is_test, metadata, name, output, owner, proc_macro_deps, root, rustc_env, rustc_env_files, rustc_output, rustc_rmeta_output, srcs, std_dylib, type, wrapped_crate_type)
A provider containing general Crate information.
FIELDS
Name | Description |
---|---|
aliases | Dict[Label, String]: Renamed and aliased crates |
compile_data | depset[File]: Compile data required by this crate. |
compile_data_targets | depset[Label]: Compile data targets required by this crate. |
data | depset[File]: Compile data required by crates that use the current crate as a proc-macro. |
deps | depset[DepVariantInfo]: This crate's (rust or cc) dependencies' providers. |
edition | str: The edition of this crate. |
is_test | bool: If the crate is being compiled in a test context |
metadata | File: The output from rustc from producing the output file. It is optional. |
name | str: The name of this crate. |
output | File: The output File that will be produced, depends on crate type. |
owner | Label: The label of the target that produced this CrateInfo |
proc_macro_deps | depset[DepVariantInfo]: This crate's rust proc_macro dependencies' providers. |
root | File: The source File entrypoint to this crate, eg. lib.rs |
rustc_env | Dict[String, String]: Additional "key": "value" environment variables to set for rustc. |
rustc_env_files | [File]: Files containing additional environment variables to set for rustc. |
rustc_output | File: The output from rustc from producing the output file. It is optional. |
rustc_rmeta_output | File: The rmeta file produced for this crate. It is optional. |
srcs | depset[File]: All source Files that are part of the crate. |
std_dylib | File: libstd.so file |
type | str: The type of this crate (see rustc --crate-type). |
wrapped_crate_type | str, optional: The original crate type for targets generated using a previously defined crate (typically tests using the rust_test::crate attribute) |
DepInfo
DepInfo(dep_env, direct_crates, link_search_path_files, transitive_build_infos, transitive_crate_outputs, transitive_crates, transitive_data, transitive_metadata_outputs, transitive_noncrates, transitive_proc_macro_data)
A provider containing information about a Crate's dependencies.
FIELDS
RustWasmBindgenInfo
RustWasmBindgenInfo(js, ts, wasm)
Info about wasm-bindgen outputs.
FIELDS
Name | Description |
---|---|
js | Depset[File]: The Javascript files produced by wasm-bindgen . |
ts | Depset[File]: The Typescript files produced by wasm-bindgen . |
wasm | File: The .wasm file generated by wasm-bindgen . |
StdLibInfo
StdLibInfo(alloc_files, between_alloc_and_core_files, between_core_and_std_files, core_files, dot_a_files, memchr_files, panic_files, self_contained_files, srcs, std_dylib, std_files, std_rlibs, test_files)
A collection of files either found within the rust-stdlib
artifact or generated based on existing files.
FIELDS
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, 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
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
rules_rust_dependencies
rules_rust_dependencies()
Dependencies used in the implementation of rules_rust
.
rust_analyzer_toolchain_repository
rust_analyzer_toolchain_repository(name, version, exec_compatible_with, target_compatible_with, sha256s, urls, auth, netrc, auth_patterns)
Assemble a remote rust_analyzer_toolchain target based on the given params.
PARAMETERS
Name | Description | Default Value |
---|---|---|
name | The name of the toolchain proxy repository contianing the registerable toolchain. | none |
version | The version of the tool among "nightly", "beta', or an exact version. | none |
exec_compatible_with | A list of constraints for the execution platform for this toolchain. | [] |
target_compatible_with | A list of constraints for the target platform for this toolchain. | [] |
sha256s | A dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details. | None |
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). Defaults to ['https://static.rust-lang.org/dist/{}.tar.xz'] | None |
auth | Auth object compatible with repository_ctx.download to use when downloading files. See repository_ctx.download for more details. | None |
netrc | .netrc file to use for authentication; mirrors the eponymous attribute from http_archive | None |
auth_patterns | Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive | None |
RETURNS
str: The name of a registerable rust_analyzer_toolchain.
rust_bindgen_dependencies
rust_bindgen_dependencies()
Declare dependencies needed for bindgen.
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
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
rust_bindgen_register_toolchains
rust_bindgen_register_toolchains(register_toolchains)
Registers the default toolchains for the rules_rust
bindgen rules.
PARAMETERS
rust_prost_dependencies
rust_prost_dependencies(bzlmod)
Declares repositories needed for prost.
PARAMETERS
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
rust_prost_library
rust_prost_library(name, kwargs)
A rule for generating a Rust library using Prost.
PARAMETERS
Name | Description | Default Value |
---|---|---|
name | The name of the target. | none |
kwargs | Additional keyword arguments for the underlying rust_prost_library rule. | none |
rust_prost_transitive_repositories
rust_prost_transitive_repositories()
Load transitive dependencies of the @rules_rust//proto/protobuf
rules.
This macro should be called immediately after the rust_protobuf_dependencies
macro.
rust_proto_protobuf_dependencies
rust_proto_protobuf_dependencies(bzlmod)
Sets up dependencies for rules_rust's proto support.
PARAMETERS
Name | Description | Default Value |
---|---|---|
bzlmod | Whether this function is being called from a bzlmod context rather than a workspace context. | False |
RETURNS
A list of structs containing information about root module deps to report to bzlmod's extension_metadata.
rust_proto_protobuf_register_toolchains
rust_proto_protobuf_register_toolchains(register_toolchains)
Register toolchains for proto compilation.
PARAMETERS
rust_proto_protobuf_transitive_repositories
rust_proto_protobuf_transitive_repositories()
Load transitive dependencies of the @rules_rust//proto/protobuf
rules.
This macro should be called immediately after the rust_protobuf_dependencies
macro.
rust_register_toolchains
rust_register_toolchains(dev_components, edition, allocator_library, global_allocator_library, register_toolchains, rustfmt_version, rust_analyzer_version, sha256s, extra_target_triples, extra_rustc_flags, extra_exec_rustc_flags, urls, versions)
Emits a default set of toolchains for Linux, MacOS, and Freebsd
Skip this macro and call the rust_repository_set
macros directly if you need a compiler for other hosts or for additional target triples.
The sha256s
attribute represents a dict associating tool subdirectories to sha256 hashes. As an example:
{
"rust-1.46.0-x86_64-unknown-linux-gnu": "e3b98bc3440fe92817881933f9564389eccb396f5f431f33d48b979fa2fbdcf5",
"rustfmt-1.4.12-x86_64-unknown-linux-gnu": "1894e76913303d66bf40885a601462844eec15fca9e76a6d13c390d7000d64b0",
"rust-std-1.46.0-x86_64-unknown-linux-gnu": "ac04aef80423f612c0079829b504902de27a6997214eb58ab0765d02f7ec1dbc",
}
This would match for exec_triple = "x86_64-unknown-linux-gnu"
. If not specified, rules_rust pulls from a non-exhaustive list of known checksums..
See load_arbitrary_tool
in @rules_rust//rust:repositories.bzl
for more details.
PARAMETERS
rust_repositories
rust_repositories(kwargs)
Deprecated: Use rules_rust_dependencies and rust_register_toolchains directly.
PARAMETERS
rust_repository_set
rust_repository_set(name, versions, exec_triple, target_settings, allocator_library, global_allocator_library, extra_target_triples, rustfmt_version, edition, dev_components, extra_rustc_flags, extra_exec_rustc_flags, opt_level, sha256s, urls, auth, netrc, auth_patterns, register_toolchain, exec_compatible_with, default_target_compatible_with)
Assembles a remote repository for the given toolchain params, produces a proxy repository to contain the toolchain declaration, and registers the toolchains.
PARAMETERS
Name | Description | Default Value |
---|---|---|
name | The name of the generated repository | none |
versions | A list of toolchain versions to download. This paramter only accepts one versions per channel. E.g. ["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"] . | none |
exec_triple | The Rust-style target that this compiler runs on | none |
target_settings | A list of config_settings that must be satisfied by the target configuration in order for this set of toolchains to be selected during toolchain resolution. | [] |
allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | None |
global_allocator_library | Target that provides allocator functions a global allocator is used with cc_common.link. | None |
extra_target_triples | Additional rust-style targets that this set of toolchains should support. If a map, values should be (optional) target_compatible_with lists for that particular target triple. | {} |
rustfmt_version | The version of rustfmt to be associated with the toolchain. | None |
edition | The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute. | None |
dev_components | Whether to download the rustc-dev components. Requires version to be "nightly". | False |
extra_rustc_flags | Dictionary of target triples to list of extra flags to pass to rustc in non-exec configuration. | None |
extra_exec_rustc_flags | Extra flags to pass to rustc in exec configuration. | None |
opt_level | Dictionary of target triples to optimiztion config. | None |
sha256s | A dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details. | None |
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). | ["https://static.rust-lang.org/dist/{}.tar.xz"] |
auth | Auth object compatible with repository_ctx.download to use when downloading files. See repository_ctx.download for more details. | None |
netrc | .netrc file to use for authentication; mirrors the eponymous attribute from http_archive | None |
auth_patterns | Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive | None |
register_toolchain | If True, the generated rust_toolchain target will become a registered toolchain. | True |
exec_compatible_with | A list of constraints for the execution platform for this toolchain. | None |
default_target_compatible_with | A list of constraints for the target platform for this toolchain when the exec platform is the same as the target platform. | None |
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 underyling rust_test targets. The tags argument is also passed to the generated test_suite target. | none |
rust_toolchain_repository
rust_toolchain_repository(name, version, exec_triple, target_triple, exec_compatible_with, target_compatible_with, target_settings, channel, allocator_library, global_allocator_library, rustfmt_version, edition, dev_components, extra_rustc_flags, extra_exec_rustc_flags, opt_level, sha256s, urls, auth, netrc, auth_patterns)
Assembles a remote repository for the given toolchain params, produces a proxy repository to contain the toolchain declaration, and registers the toolchains.
PARAMETERS
Name | Description | Default Value |
---|---|---|
name | The name of the generated repository | none |
version | The version of the tool among "nightly", "beta", or an exact version. | none |
exec_triple | The Rust-style target that this compiler runs on. | none |
target_triple | The Rust-style target to build for. | none |
exec_compatible_with | A list of constraints for the execution platform for this toolchain. | None |
target_compatible_with | A list of constraints for the target platform for this toolchain. | None |
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. | [] |
channel | The channel of the Rust toolchain. | None |
allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | None |
global_allocator_library | Target that provides allocator functions when a global allocator is used with cc_common.link. | None |
rustfmt_version | The version of rustfmt to be associated with the toolchain. | None |
edition | The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute. | None |
dev_components | Whether to download the rustc-dev components. Requires version to be "nightly". Defaults to False. | False |
extra_rustc_flags | Extra flags to pass to rustc in non-exec configuration. | None |
extra_exec_rustc_flags | Extra flags to pass to rustc in exec configuration. | None |
opt_level | Optimization level config for this toolchain. | None |
sha256s | A dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details. | None |
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). Defaults to ['https://static.rust-lang.org/dist/{}.tar.xz'] | ["https://static.rust-lang.org/dist/{}.tar.xz"] |
auth | Auth object compatible with repository_ctx.download to use when downloading files. See repository_ctx.download for more details. | None |
netrc | .netrc file to use for authentication; mirrors the eponymous attribute from http_archive | None |
auth_patterns | A list of patterns to match against urls for which the auth object should be used. | None |
RETURNS
str: The name of the registerable toolchain created by this rule.
rust_wasm_bindgen_dependencies
rust_wasm_bindgen_dependencies()
Declare dependencies needed for the rules_rust
wasm-bindgen rules.
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
rust_wasm_bindgen_register_toolchains
rust_wasm_bindgen_register_toolchains(register_toolchains)
Registers the default toolchains for the rules_rust
wasm-bindgen rules.
PARAMETERS
rust_analyzer_aspect
rust_analyzer_aspect(name)
Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json
ASPECT ATTRIBUTES
Name | Type |
---|---|
deps | String |
proc_macro_deps | String |
crate | String |
actual | String |
proto | String |
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
rust_clippy_aspect
rust_clippy_aspect(name)
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
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
rustfmt_aspect
rustfmt_aspect(name)
This aspect is used to gather information about a crate for use in rustfmt and perform rustfmt checks
Output Groups:
rustfmt_checks
: Executesrustfmt --check
on the specified target.
The build setting @rules_rust//: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
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required |
cargo_bootstrap_repository
cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_lockfile, cargo_toml, env, env_label, repo_mapping, 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 | Souce 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_lockfile | The lockfile of the crate_universe resolver | Label | required | |
cargo_toml | The path of the crate_universe resolver manifest (Cargo.toml file) | Label | required | |
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 | {} |
repo_mapping | In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target , it should actually resolve that dependency within globally-declared @bar (@bar//some:target ).This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function). | 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.81.0" |
rust_toolchain_repository_proxy
rust_toolchain_repository_proxy(name, exec_compatible_with, repo_mapping, target_compatible_with, target_settings, toolchain, toolchain_type)
Generates a toolchain-bearing repository that declares the toolchains from some other rust_toolchain_repository.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this repository. | Name | required | |
exec_compatible_with | A list of constraints for the execution platform for this toolchain. | List of strings | optional | [] |
repo_mapping | In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target , it should actually resolve that dependency within globally-declared @bar (@bar//some:target ).This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function). | Dictionary: String -> String | optional | |
target_compatible_with | A list of constraints for the target platform for this toolchain. | List of strings | 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 strings | optional | [] |
toolchain | The name of the toolchain implementation target. | String | required | |
toolchain_type | The toolchain type of the toolchain to declare | String | required |
rust_toolchain_tools_repository
rust_toolchain_tools_repository(name, allocator_library, auth, auth_patterns, dev_components, edition, exec_triple, extra_exec_rustc_flags, extra_rustc_flags, global_allocator_library, netrc, opt_level, repo_mapping, rustfmt_version, sha256s, target_triple, urls, version)
Composes a single workspace containing the toolchain components for compiling on a given platform to a series of target platforms.
A given instance of this rule should be accompanied by a toolchain_repository_proxy invocation to declare its toolchains to Bazel; the indirection allows separating toolchain selection from toolchain fetching.
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this repository. | Name | required | |
allocator_library | Target that provides allocator functions when rust_library targets are embedded in a cc_binary. | String | optional | "@rules_rust//ffi/cc/allocator_library" |
auth | Auth object compatible with repository_ctx.download to use when downloading files. See repository_ctx.download for more details. | Dictionary: String -> String | optional | {} |
auth_patterns | A list of patterns to match against urls for which the auth object should be used. | List of strings | 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_triple | The Rust-style target that this compiler runs on | String | required | |
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 a global allocator is used with cc_common.link. | String | optional | "@rules_rust//ffi/cc/global_allocator_library" |
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 | {} |
repo_mapping | In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target , it should actually resolve that dependency within globally-declared @bar (@bar//some:target ).This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function). | Dictionary: String -> String | optional | |
rustfmt_version | The version of the tool among "nightly", "beta", or an exact version. | String | optional | "" |
sha256s | A dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details. | Dictionary: String -> String | optional | {} |
target_triple | The Rust-style target that this compiler builds for. | String | required | |
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 the tool among "nightly", "beta", or an exact version. | String | required |
External Dependencies
crate_universe (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.49.3")
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:extension.bzl", "crate")
// # ... Dependencies
use_repo(crate, "crates")
Dependencies
There are three different ways to declare dependencies in your MODULE.
- Cargo workspace
- Direct 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:extension.bzl", "crate")
crate.from_cargo(
name = "crates",
cargo_lockfile = "//:Cargo.lock",
manifests = ["//:Cargo.toml"],
)
use_repo(crate, "crates")
The generated crates_repository contains helper macros which make collecting dependencies for Bazel targets simpler. Notably, the all_crate_deps and aliases 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 dependencies and alias definitions they return will automatically update BUILD targets. In your BUILD files, you use these macros for a Rust library as shown below:
load("@crate_index//:defs.bzl", "aliases", "all_crate_deps")
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "lib",
aliases = aliases(),
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,
),
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"],
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:extension.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.
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 MODUE.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.7.1")
# https://github.com/bazelbuild/rules_rust/releases
bazel_dep(name = "rules_rust", version = "0.49.3")
###############################################################################
# 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:extension.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:docs_bzlmod.bzl", "crate") crate.from_cargo(name, cargo_config, cargo_lockfile, generate_binaries, generate_build_scripts, manifests, supported_platform_triples) crate.annotation(deps, data, additive_build_file, additive_build_file_content, alias_rule, build_script_data, build_script_data_glob, build_script_deps, build_script_env, build_script_proc_macro_deps, build_script_rundir, build_script_rustc_env, build_script_toolchains, build_script_tools, compile_data, compile_data_glob, 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.from_specs(name, cargo_config, generate_binaries, generate_build_scripts, supported_platform_triples) crate.spec(artifact, branch, default_features, features, git, lib, package, rev, tag, version)
TAG CLASSES
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 |
manifests | A list of Cargo manifests (Cargo.toml files). | List of labels | optional | [] |
supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-fuchsia", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-linux-gnu", "aarch64-unknown-nixos-gnu", "aarch64-unknown-nto-qnx710", "arm-unknown-linux-gnueabi", "armv7-linux-androideabi", "armv7-unknown-linux-gnueabi", "i686-apple-darwin", "i686-linux-android", "i686-pc-windows-msvc", "i686-unknown-freebsd", "i686-unknown-linux-gnu", "powerpc-unknown-linux-gnu", "riscv32imc-unknown-none-elf", "riscv64gc-unknown-none-elf", "s390x-unknown-linux-gnu", "thumbv7em-none-eabi", "thumbv8m.main-none-eabi", "wasm32-unknown-unknown", "wasm32-wasi", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-fuchsia", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"] |
annotation
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_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_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 | [] |
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 authorative 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 taget 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 taget 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 taget 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 taget 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 | "*" |
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 |
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 |
supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-fuchsia", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-linux-gnu", "aarch64-unknown-nixos-gnu", "aarch64-unknown-nto-qnx710", "arm-unknown-linux-gnueabi", "armv7-linux-androideabi", "armv7-unknown-linux-gnueabi", "i686-apple-darwin", "i686-linux-android", "i686-pc-windows-msvc", "i686-unknown-freebsd", "i686-unknown-linux-gnu", "powerpc-unknown-linux-gnu", "riscv32imc-unknown-none-elf", "riscv64gc-unknown-none-elf", "s390x-unknown-linux-gnu", "thumbv7em-none-eabi", "thumbv8m.main-none-eabi", "wasm32-unknown-unknown", "wasm32-wasi", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-fuchsia", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"] |
spec
Attributes
Crate Universe
Crate Universe is a set of Bazel rule for generating Rust targets using Cargo.
This doc describes using crate_universe from a WORKSPACE file.
If you're using bzlmod, please see the bzlmod equivalent of this doc.
Setup
After loading rules_rust
in your workspace, set the following to begin using crate_universe
:
load("@rules_rust//crate_universe:repositories.bzl", "crate_universe_dependencies")
crate_universe_dependencies()
Note that if the current version of rules_rust
is not a release artifact, you may need to set additional
flags such as bootstrap = True
on the crate_universe_dependencies
call above or crates_repository::generator_urls in uses of crates_repository
.
Rules
Utility Macros
- crate_universe_dependencies
- crate.annotation
- crate.select
- crate.spec
- crate.workspace_member
- render_config
- splicing_config
Workflows
The crates_repository
rule (the primary repository rule of rules_rust
's cargo support) supports a number of different
ways users can express and organize their dependencies. The most common are listed below though there are more to be found in
the ./examples/crate_universe directory.
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 dependencies from there.
load("@rules_rust//crate_universe:defs.bzl", "crates_repository")
crates_repository(
name = "crate_index",
cargo_lockfile = "//:Cargo.lock",
lockfile = "//:Cargo.Bazel.lock",
manifests = ["//:Cargo.toml"],
)
load("@crate_index//:defs.bzl", "crate_repositories")
crate_repositories()
The generated crates_repository
contains helper macros which make collecting dependencies for Bazel targets simpler.
Notably, the all_crate_deps
and aliases
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 dependencies and alias definitions they return will automatically update BUILD targets.
load("@crate_index//:defs.bzl", "aliases", "all_crate_deps")
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "lib",
aliases = aliases(),
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,
),
deps = all_crate_deps(
normal_dev = True,
),
proc_macro_deps = all_crate_deps(
proc_macro_dev = True,
),
)
Direct Packages
In cases where Rust targets have heavy interractions with other Bazel targests (Cc, Proto, etc.),
maintaining Cargo.toml
files may have deminishing returns as things like rust-analyzer begin to be confused
about missing targets or environment variables defined only in Bazel. In workspaces like this, it may be desirable
to have a "Cargo free" setup. crates_repository
supports this through the packages
attribute.
load("@rules_rust//crate_universe:defs.bzl", "crate", "crates_repository", "render_config")
crates_repository(
name = "crate_index",
cargo_lockfile = "//:Cargo.lock",
lockfile = "//:Cargo.Bazel.lock",
packages = {
"async-trait": crate.spec(
version = "0.1.51",
),
"mockall": crate.spec(
version = "0.10.2",
),
"tokio": crate.spec(
version = "1.12.0",
),
},
# Setting the default package name to `""` forces the use of the macros defined in this repository
# to always use the root package when looking for dependencies or aliases. This should be considered
# optional as the repository also exposes alises for easy access to all dependencies.
render_config = render_config(
default_package_name = ""
),
)
load("@crate_index//:defs.bzl", "crate_repositories")
crate_repositories()
Consuming dependencies may be more ergonomic in this case through the aliases defined in the new repository.
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "lib",
deps = [
"@crate_index//:tokio",
],
proc_macro_deps = [
"@crate_index//:async-trait",
],
)
rust_test(
name = "unit_test",
crate = ":lib",
deps = [
"@crate_index//:mockall",
],
)
Binary dependencies
Neither of the above approaches supports depending on binary-only packages.
In order to depend on a Cargo package that contains binaries and no library, you will need to do one of the following:
-
Fork the package to add an empty lib.rs, which makes the package visible to Cargo metadata and compatible with the above approaches;
-
Or handwrite your own build target for the binary, use
http_archive
to import its source code, and usecrates_repository
to make build targets for its dependencies. This is demonstrated below using therustfilt
crate as an example.
# in WORKSPACE.bazel
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rustfilt",
build_file = "//rustfilt:BUILD.rustfilt.bazel",
sha256 = "c8d748b182c8f95224336d20dcc5609598af612581ce60cfb29da4dc8d0091f2",
strip_prefix = "rustfilt-0.2.1",
type = "tar.gz",
urls = ["https://static.crates.io/crates/rustfilt/rustfilt-0.2.1.crate"],
)
load("@rules_rust//crate_universe:defs.bzl", "crates_repository")
crates_repository(
name = "rustfilt_deps",
cargo_lockfile = "//rustfilt:Cargo.lock",
manifests = ["@rustfilt//:Cargo.toml"],
)
load("@rustfilt_deps//:defs.bzl", rustfilt_deps = "crate_repositories")
rustfilt_deps()
# in rustfilt/BUILD.rustfilt.bazel
load("@rules_rust//rust:defs.bzl", "rust_binary")
rust_binary(
name = "rustfilt",
srcs = glob(["src/**/*.rs"]),
edition = "2018",
deps = [
"@rustfilt_deps//:clap",
"@rustfilt_deps//:lazy_static",
"@rustfilt_deps//:regex",
"@rustfilt_deps//:rustc-demangle",
],
)
If you use either crates_repository
or crates_vendor
to depend on a Cargo
package that contains both a library crate and binaries, by default only the
library gets made available to Bazel. To generate Bazel targets for the binary
crates as well, you must opt in to it with an annotation on the package:
load("@rules_rust//crate_universe:defs.bzl", "crates_repository", "crate")
crates_repository(
name = "crate_index",
annotations = {
"thepackage": [crate.annotation(
gen_binaries = True,
# Or, to expose just a subset of the package's binaries by name:
gen_binaries = ["rustfilt"],
)],
},
# Or, to expose every binary of every package:
generate_binaries = True,
...
)
Dependencies API
After rendering dependencies, convenience macros may also be generated to provide convenient accessors to larger sections of the dependency graph.
Building crates with complicated dependencies
Some crates have build.rs scripts which are complicated to run. Typically these build C++ (or other languages), or attempt to find pre-installed libraries on the build machine.
There are a few approaches to making sure these run:
Some things work without intervention
Some build scripts will happily run without any support needed.
rules_rust already supplies a configured C++ toolchain as input to build script execution, and sets variables like CC
, CXX
, LD
, LDFLAGS
, etc as needed. Many crates which invoke a compiler with the default environment, or forward these env vars, will Just Work (e.g. if using cc-rs
).
rules_rust is open to PRs which make build scripts more likely to work by default with intervention assuming they're broadly applicable (e.g. setting extra widely-known env vars is probably fine, wiring up additional toolchains like cmake
that aren't present by default for most Bazel users probably isn't).
Supplying extra tools to build
Some build scripts can be made to work by pulling in some extra files and making them available to the build script.
Commonly this is done by passing the file to the build_script_data
annotation for the crate, and using build_script_env
to tell the build script where the file is. That env var may often use $(execroot)
to get the path to the label, or $${pwd}/
as a prefix if the path given is relative to the execroot (as will frequently happen when using a toolchain).A
There is an example of this in the "complicated dependencies" section of https://github.com/bazelbuild/rules_rust/blob/main/examples/crate_universe/WORKSPACE.bazel which builds libz-ng-sys.
Building with Bazel and supplying via an override
Some build scripts have hooks to allow replacing parts that are complicated to build with output prepared by Bazel.
We can use those hooks by specifying paths (generally using the build_script_data
and build_script_env
annotations) and pointing them at labels which Bazel will then build. These env vars may often use $(execroot)
to get the path to the label, or $${pwd}/
as a prefix if the path given is relative to the execroot (as will frequently happen when using a toolchain).
There is an example of this in the "complicated dependencies" section of https://github.com/bazelbuild/rules_rust/blob/main/examples/crate_universe/WORKSPACE.bazel which builds boring-sys.
crates_vendor
crates_vendor(name, annotations, bazel, buildifier, cargo_bazel, cargo_config, cargo_lockfile, generate_binaries, generate_build_scripts, generate_target_compatible_with, manifests, mode, packages, render_config, repository_name, splicing_config, supported_platform_triples, vendor_path)
A rule for defining Rust dependencies (crates) and writing targets for them to the current workspace.
This rule is useful for users whose workspaces are expected to be consumed in other workspaces as the
rendered BUILD
files reduce the number of workspace dependencies, allowing for easier loads. This rule
handles all the same workflows crate_universe
rules do.
Example:
Given the following workspace structure:
[workspace]/
WORKSPACE
BUILD
Cargo.toml
3rdparty/
BUILD
src/
main.rs
The following is something that'd be found in 3rdparty/BUILD
:
load("@rules_rust//crate_universe:defs.bzl", "crates_vendor", "crate")
crates_vendor(
name = "crates_vendor",
annotations = {
"rand": [crate.annotation(
default_features = False,
features = ["small_rng"],
)],
},
cargo_lockfile = "//:Cargo.Bazel.lock",
manifests = ["//:Cargo.toml"],
mode = "remote",
vendor_path = "crates",
tags = ["manual"],
)
The above creates a target that can be run to write BUILD
files into the 3rdparty
directory next to where the target is defined. To run it, simply call:
bazel run //3rdparty:crates_vendor
Repinning / Updating Dependencies
Repinning dependencies is controlled by both the CARGO_BAZEL_REPIN
environment variable or the --repin
flag to the crates_vendor
binary. To update dependencies, simply add the flag ro your bazel run
invocation.
bazel run //3rdparty:crates_vendor -- --repin
Under the hood, --repin
will trigger a cargo update
call against the generated workspace. The following table describes how to control particular values passed to the
cargo update
command.
Value | Cargo command |
---|---|
Any of [true , 1 , yes , on , workspace ] | cargo update --workspace |
Any of [full , eager , all ] | cargo update |
package_name | cargo upgrade --package package_name |
package_name@1.2.3 | cargo upgrade --package package_name --precise 1.2.3 |
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this target. | Name | required | |
annotations | Extra settings to apply to crates. See crate.annotation. | Dictionary: String -> List of strings | optional | {} |
bazel | The path to a bazel binary used to locate the output_base for the current workspace. | Label | optional | None |
buildifier | The path to a buildifier binary used to format generated BUILD files. | Label | optional | "@rules_rust//crate_universe/private/vendor:buildifier" |
cargo_bazel | The cargo-bazel binary to use for vendoring. If this attribute is not set, then a CARGO_BAZEL_GENERATOR_PATH action env will be used. | Label | optional | "@@cargo_bazel_bootstrap//:binary" |
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 |
generate_target_compatible_with | DEPRECATED: Moved to render_config . | Boolean | optional | True |
manifests | A list of Cargo manifests (Cargo.toml files). | List of labels | optional | [] |
mode | Flags determining how crates should be vendored. local is where crate source and BUILD files are written to the repository. remote is where only BUILD files are written and repository rules used to fetch source code. | String | optional | "remote" |
packages | A set of crates (packages) specifications to depend on. See crate.spec. | Dictionary: String -> String | optional | {} |
render_config | The configuration flags to use for rendering. Use //crate_universe:defs.bzl\%render_config to generate the value for this field. If unset, the defaults defined there will be used. | String | optional | "" |
repository_name | The name of the repository to generate for remote vendor modes. If unset, the label name will be used | String | optional | "" |
splicing_config | The configuration flags to use for splicing Cargo maniests. Use //crate_universe:defs.bzl\%rsplicing_config to generate the value for this field. If unset, the defaults defined there will be used. | String | optional | "" |
supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-fuchsia", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-linux-gnu", "aarch64-unknown-nixos-gnu", "aarch64-unknown-nto-qnx710", "arm-unknown-linux-gnueabi", "armv7-linux-androideabi", "armv7-unknown-linux-gnueabi", "i686-apple-darwin", "i686-linux-android", "i686-pc-windows-msvc", "i686-unknown-freebsd", "i686-unknown-linux-gnu", "powerpc-unknown-linux-gnu", "riscv32imc-unknown-none-elf", "riscv64gc-unknown-none-elf", "s390x-unknown-linux-gnu", "thumbv7em-none-eabi", "thumbv8m.main-none-eabi", "wasm32-unknown-unknown", "wasm32-wasi", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-fuchsia", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"] |
vendor_path | The path to a directory to write files into. Absolute paths will be treated as relative to the workspace root | String | optional | "crates" |
aliases
aliases(normal, normal_dev, proc_macro, proc_macro_dev, build, build_proc_macro, package_name)
Produces a map of Crate alias names to their original label
If no dependency kinds are specified, normal
and proc_macro
are used by default.
Setting any one flag will otherwise determine the contents of the returned dict.
PARAMETERS
RETURNS
dict: The aliases of all associated packages
all_crate_deps
all_crate_deps(normal, normal_dev, proc_macro, proc_macro_dev, build, build_proc_macro, package_name)
Finds the fully qualified label of all requested direct crate dependencies for the package where this macro is called.
If no parameters are set, all normal dependencies are returned. Setting any one flag will otherwise impact the contents of the returned list.
PARAMETERS
RETURNS
list: A list of labels to generated rust targets (str)
crate.annotation
crate.annotation(version, additive_build_file, additive_build_file_content, alias_rule, build_script_compile_data, build_script_data, build_script_tools, build_script_data_glob, build_script_deps, build_script_env, build_script_proc_macro_deps, build_script_rundir, build_script_rustc_env, build_script_toolchains, compile_data, compile_data_glob, crate_features, data, data_glob, deps, extra_aliased_targets, gen_binaries, disable_pipelining, gen_build_script, patch_args, patch_tool, patches, proc_macro_deps, rustc_env, rustc_env_files, rustc_flags, shallow_since, override_targets)
A collection of extra attributes and settings for a particular crate
PARAMETERS
Name | Description | Default Value |
---|---|---|
version | The version or semver-conditions to match with a crate. The wildcard * matches any version, including prerelease versions. | "*" |
additive_build_file | A file containing extra contents to write to the bottom of generated BUILD files. | None |
additive_build_file_content | Extra contents to write to the bottom of generated BUILD files. | None |
alias_rule | Alias rule to use instead of native.alias() . Overrides render_config's 'default_alias_rule'. | None |
build_script_compile_data | A list of labels to add to a crate's cargo_build_script::compile_data attribute. | None |
build_script_data | A list of labels to add to a crate's cargo_build_script::data attribute. | None |
build_script_tools | A list of labels to add to a crate's cargo_build_script::tools attribute. | None |
build_script_data_glob | A list of glob patterns to add to a crate's cargo_build_script::data attribute. | None |
build_script_deps | A list of labels to add to a crate's cargo_build_script::deps attribute. | None |
build_script_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | None |
build_script_proc_macro_deps | A list of labels to add to a crate's cargo_build_script::proc_macro_deps attribute. | None |
build_script_rundir | An override for the build script's rundir attribute. | None |
build_script_rustc_env | Additional environment variables to set on a crate's cargo_build_script::env attribute. | None |
build_script_toolchains | A list of labels to set on a crates's cargo_build_script::toolchains attribute. | None |
compile_data | A list of labels to add to a crate's rust_library::compile_data attribute. | None |
compile_data_glob | A list of glob patterns to add to a crate's rust_library::compile_data attribute. | None |
crate_features | A list of strings to add to a crate's rust_library::crate_features attribute. | None |
data | A list of labels to add to a crate's rust_library::data attribute. | None |
data_glob | A list of glob patterns to add to a crate's rust_library::data attribute. | None |
deps | A list of labels to add to a crate's rust_library::deps attribute. | None |
extra_aliased_targets | A list of targets to add to the generated aliases in the root crate_universe repository. | None |
gen_binaries | As a list, the subset of the crate's bins that should get rust_binary targets produced. Or True to generate all, False to generate none. | None |
disable_pipelining | If True, disables pipelining for library targets for this crate. | False |
gen_build_script | An authorative flag to determine whether or not to produce cargo_build_script targets for the current crate. | None |
patch_args | The patch_args attribute of a Bazel repository rule. See http_archive.patch_args | None |
patch_tool | The patch_tool attribute of a Bazel repository rule. See http_archive.patch_tool | None |
patches | The patches attribute of a Bazel repository rule. See http_archive.patches | None |
proc_macro_deps | A list of labels to add to a crate's rust_library::proc_macro_deps attribute. | None |
rustc_env | Additional variables to set on a crate's rust_library::rustc_env attribute. | None |
rustc_env_files | A list of labels to set on a crate's rust_library::rustc_env_files attribute. | None |
rustc_flags | A list of strings to set on a crate's rust_library::rustc_flags attribute. | None |
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. | None |
override_targets | A dictionary of alternate targets to use when something depends on this crate to allow the parent repo to provide its own version of this dependency. Keys can be proc-marco , custom-build , lib , bin . | None |
RETURNS
string: A json encoded string containing the specified version and separately all other inputs.
crate.select
crate.select(common, selects)
A Starlark Select for crate.annotation()
.
PARAMETERS
Name | Description | Default Value |
---|---|---|
common | A value that applies to all configurations. | none |
selects | A dict of target_triple to values. | none |
RETURNS
struct: A struct representing the Starlark Select.
crate.spec
crate.spec(package, version, artifact, lib, default_features, features, git, branch, tag, rev)
A constructor for a crate dependency.
See specifying dependencies in the Cargo book for more details.
PARAMETERS
RETURNS
string: A json encoded string of all inputs
crate.workspace_member
crate.workspace_member(version, sha256)
Define information for extra workspace members
PARAMETERS
Name | Description | Default Value |
---|---|---|
version | The semver of the crate to download. Must be an exact version. | none |
sha256 | The sha256 checksum of the .crate file. | None |
RETURNS
string: A json encoded string of all inputs
crate_deps
crate_deps(deps, package_name)
Finds the fully qualified label of the requested crates for the package where this macro is called.
PARAMETERS
Name | Description | Default Value |
---|---|---|
deps | The desired list of crate targets. | none |
package_name | The package name of the set of dependencies to look up. Defaults to native.package_name() . | None |
RETURNS
list: A list of labels to generated rust targets (str)
crate_repositories
crate_repositories()
A macro for defining repositories for all generated crates.
RETURNS
A list of repos visible to the module through the module extension.
crate_universe_dependencies
crate_universe_dependencies(rust_version, bootstrap, kwargs)
Define dependencies of the cargo-bazel
Rust target
PARAMETERS
RETURNS
list[struct(repo=str, is_dev_dep=bool)]: A list of the repositories defined by this macro.
render_config
render_config(build_file_template, crate_label_template, crate_repository_template, crates_module_template, default_alias_rule, default_package_name, generate_target_compatible_with, platforms_template, regen_command, vendor_mode, generate_rules_license_metadata)
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 |
PARAMETERS
Name | Description | Default Value |
---|---|---|
build_file_template | The base template to use for BUILD file names. The available format keys are [{name} , {version}`]. | "//:BUILD.{name}-{version}.bazel" |
crate_label_template | The base template to use for crate labels. The available format keys are [{repository} , {name} , {version} , {target} ]. | "@{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} ]. | "{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} ]. | "//:{file}" |
default_alias_rule | 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>: | "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 . | None |
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 . | True |
platforms_template | The base template to use for platform names. See platforms documentation. The available format keys are [{triple} ]. | "@rules_rust//rust/platform:{triple}" |
regen_command | An optional command to demonstrate how generated files should be regenerated. | None |
vendor_mode | An optional configuration for rendirng content to be rendered into repositories. | None |
generate_rules_license_metadata | Whether to generate rules license metedata | False |
RETURNS
string: A json encoded struct to match the Rust config::RenderConfig
struct
splicing_config
splicing_config(resolver_version)
Various settings used to configure Cargo manifest splicing behavior.
PARAMETERS
Name | Description | Default Value |
---|---|---|
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 . | "2" |
RETURNS
str: A json encoded string of the parameters provided
crates_repository
crates_repository(name, annotations, cargo_config, cargo_lockfile, generate_binaries, generate_build_scripts, generate_target_compatible_with, generator, generator_sha256s, generator_urls, isolated, lockfile, manifests, packages, quiet, render_config, repin_instructions, repo_mapping, rust_toolchain_cargo_template, rust_toolchain_rustc_template, rust_version, splicing_config, supported_platform_triples)
A rule for defining and downloading Rust dependencies (crates). This rule
handles all the same workflows crate_universe
rules do.
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 authorative 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. |
Example:
Given the following workspace structure:
[workspace]/
WORKSPACE.bazel
BUILD.bazel
Cargo.toml
Cargo.Bazel.lock
src/
main.rs
The following is something that'd be found in the WORKSPACE
file:
load("@rules_rust//crate_universe:defs.bzl", "crates_repository", "crate")
crates_repository(
name = "crate_index",
annotations = {
"rand": [crate.annotation(
default_features = False,
features = ["small_rng"],
)],
},
cargo_lockfile = "//:Cargo.Bazel.lock",
lockfile = "//:cargo-bazel-lock.json",
manifests = ["//:Cargo.toml"],
# Should match the version represented by the currently registered `rust_toolchain`.
rust_version = "1.60.0",
)
The above will create an external repository which contains aliases and macros for accessing Rust targets found in the dependency graph defined by the given manifests.
NOTE: The cargo_lockfile
and lockfile
must be manually created. The rule unfortunately does not yet create
it on its own. When initially setting up this rule, an empty file should be created and then
populated by repinning dependencies.
Repinning / Updating Dependencies
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 crate_index
, the easiest way to
repin dependencies is to run:
CARGO_BAZEL_REPIN=1 bazel sync --only=crate_index
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. The following table shows translations from environment
variable values to the equivilant cargo update command
that is called behind the scenes to update dependencies.
Value | Cargo command |
---|---|
Any of [true , 1 , yes , on , workspace ] | cargo update --workspace |
Any of [full , eager , all ] | cargo update |
package_name | cargo upgrade --package package_name |
package_name@1.2.3 | cargo upgrade --package package_name@1.2.3 |
package_name@1.2.3=4.5.6 | cargo upgrade --package package_name@1.2.3 --precise=4.5.6 |
If the crates_repository
is used multiple times in the same Bazel workspace (e.g. for multiple independent
Rust workspaces), it may additionally be useful to use the CARGO_BAZEL_REPIN_ONLY
environment variable, which
limits execution of the repinning to one or multiple instances of the crates_repository
rule via a comma-delimited
allowlist:
CARGO_BAZEL_REPIN=1 CARGO_BAZEL_REPIN_ONLY=crate_index bazel sync --only=crate_index
ATTRIBUTES
Name | Description | Type | Mandatory | Default |
---|---|---|---|---|
name | A unique name for this repository. | Name | required | |
annotations | Extra settings to apply to crates. See crate.annotation. | Dictionary: String -> List of strings | optional | {} |
cargo_config | A Cargo configuration file | Label | optional | None |
cargo_lockfile | The path used to store the crates_repository specific Cargo.lock file. In the case that your crates_repository corresponds directly with an existing Cargo.toml file which has a paired Cargo.lock file, that Cargo.lock file should be used here, which will keep the versions used by cargo and bazel in sync. | Label | required | |
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 |
generate_target_compatible_with | DEPRECATED: Moved to render_config . | Boolean | optional | True |
generator | The absolute label of a generator. Eg. @cargo_bazel_bootstrap//:cargo-bazel . This is typically used when bootstrapping | String | optional | "" |
generator_sha256s | Dictionary of host_triple -> sha256 for a cargo-bazel binary. | Dictionary: String -> String | optional | {} |
generator_urls | URL template from which to download the cargo-bazel binary. {host_triple} and will be filled in according to the host platform. | Dictionary: String -> String | optional | {} |
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 controled 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 | [] |
packages | A set of crates (packages) specifications to depend on. See crate.spec. | Dictionary: String -> String | optional | {} |
quiet | If stdout and stderr should not be printed to the terminal. | Boolean | optional | True |
render_config | The configuration flags to use for rendering. Use //crate_universe:defs.bzl\%render_config to generate the value for this field. If unset, the defaults defined there will be used. | String | optional | "" |
repin_instructions | Instructions to re-pin the repository if required. Many people have wrapper scripts for keeping dependencies up to date, and would like to point users to that instead of the default. | String | optional | "" |
repo_mapping | In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target , it should actually resolve that dependency within globally-declared @bar (@bar//some:target ).This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function). | 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'), {cfg} (eg. 'exec'), {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'), {cfg} (eg. 'exec'), {channel} (eg. 'stable'), and {tool} (eg. 'cargo.exe') will be replaced in the string if present. | String | optional | "@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}" |
rust_version | The version of Rust the currently registered toolchain is using. Eg. 1.56.0 , or nightly/2021-09-08 | String | optional | "1.81.0" |
splicing_config | The configuration flags to use for splicing Cargo maniests. Use //crate_universe:defs.bzl\%rsplicing_config to generate the value for this field. If unset, the defaults defined there will be used. | String | optional | "" |
supported_platform_triples | A set of all platform triples to consider when generating dependencies. | List of strings | optional | ["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-fuchsia", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-linux-gnu", "aarch64-unknown-nixos-gnu", "aarch64-unknown-nto-qnx710", "arm-unknown-linux-gnueabi", "armv7-linux-androideabi", "armv7-unknown-linux-gnueabi", "i686-apple-darwin", "i686-linux-android", "i686-pc-windows-msvc", "i686-unknown-freebsd", "i686-unknown-linux-gnu", "powerpc-unknown-linux-gnu", "riscv32imc-unknown-none-elf", "riscv64gc-unknown-none-elf", "s390x-unknown-linux-gnu", "thumbv7em-none-eabi", "thumbv8m.main-none-eabi", "wasm32-unknown-unknown", "wasm32-wasi", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-fuchsia", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"] |
ENVIRONMENT VARIABLES
This repository rule depends on the following environment variables:
CARGO_BAZEL_GENERATOR_URL
CARGO_BAZEL_GENERATOR_SHA256
CARGO_BAZEL_REPIN
REPIN
CARGO_BAZEL_REPIN_ONLY
CARGO_BAZEL_ISOLATED
CARGO_BAZEL_DEBUG
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
.