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

3rd party rules

Full API

You can also browse the full API in one page.

Rust

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

rust_binary

rust_binary(name, deps, srcs, data, aliases, alwayslink, binary_name, 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
binary_nameOverride the resulting binary file name. By default, the binary file will be named using the name attribute on this rule, however sometimes that is not deseriable.Stringoptional""
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
crate_typeCrate 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).
Stringoptional"bin"
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
envSpecifies 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 -> Stringoptional{}
experimental_use_cc_common_linkWhether 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.Integeroptional-1
linker_scriptLink script to forward into linker via rustc options.LabeloptionalNone
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
out_binaryForce 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.BooleanoptionalFalse
platformOptional platform to transition the binary to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional-1
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
disable_pipeliningDisables 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.BooleanoptionalFalse
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsOther dependencies to forward through this crate group.List of labelsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
experimental_use_cc_common_linkWhether 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.Integeroptional-1
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
platformOptional platform to transition the shared library to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
platformOptional platform to transition the static library to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crateTarget inline tests declared in the given crate

These tests are typically those that would be held out under #[cfg(test)] declarations.
LabeloptionalNone
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
envSpecifies 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 -> Stringoptional{}
env_inheritSpecifies additional environment variables to inherit from the external environment when the test is executed by bazel test.List of stringsoptional[]
experimental_use_cc_common_linkWhether 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.Integeroptional-1
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
platformOptional platform to transition the test to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
use_libtest_harnessWhether 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.BooleanoptionalTrue
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionDefault Value
nameThe name of the test_suite.none
srcsAll test sources, typically glob(["tests/**/*.rs"]).none
shared_srcsOptional argument for sources shared among tests, typically helper functions.[]
kwargsAdditional 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
crateThe 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.
Labelrequired
html_after_contentFile to add in <body>, after content.LabeloptionalNone
html_before_contentFile to add in <body>, before content.LabeloptionalNone
html_in_headerFile to add to <head>.LabeloptionalNone
markdown_cssCSS files to include via <link> in a rendered Markdown file.List of labelsoptional[]
rustc_flagsDeprecated: use rustdoc_flags insteadList of stringsoptional[]
rustdoc_flagsList 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 stringsoptional[]

rust_doc_test

rust_doc_test(name, deps, crate, proc_macro_deps)

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
crateThe 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.Labelrequired
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsRust targets to run clippy on.List of labelsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
targetsRust targets to run rustfmt --check on.List of labelsoptional[]

rustfmt_toolchain

rustfmt_toolchain(name, rustc, rustc_lib, rustfmt)

A toolchain for rustfmt

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
rustcThe location of the rustc binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
rustc_libThe libraries used by rustc during compilation.LabeloptionalNone
rustfmtThe location of the rustfmt binary. Can be a direct source or a filegroup containing one item.Labelrequired

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: Executes rustfmt --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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

Rust Proto

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/protobuf/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_librarys 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding gRPC stubs.List of labelsrequired
crate_nameCrate 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.
Stringoptional""
rust_depsThe crates the generated library depends on.List of labelsoptional[]
rustc_flagsList 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 stringsoptional[]

rust_prost_toolchain

rust_prost_toolchain(name, include_transitive_deps, prost_opts, prost_plugin, prost_plugin_flag,
                     prost_runtime, prost_types, proto_compiler, tonic_opts, tonic_plugin,
                     tonic_plugin_flag, tonic_runtime)

Rust Prost toolchain rule.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
include_transitive_depsWhether to include transitive dependencies. If set to True, all transitive dependencies will directly accessible by the dependent crate.BooleanoptionalFalse
prost_optsAdditional options to add to Prost.List of stringsoptional[]
prost_pluginAdditional plugins to add to Prost.Labelrequired
prost_plugin_flagProst plugin flag format. (e.g. --plugin=protoc-gen-prost=%s)Stringoptional"--plugin=protoc-gen-prost=%s"
prost_runtimeThe Prost runtime crates to use.Labelrequired
prost_typesThe Prost types crates to use.Labelrequired
proto_compilerThe protoc compiler to use. Note that this attribute is deprecated - prefer to use --incompatible_enable_proto_toolchain_resolution.LabeloptionalNone
tonic_optsAdditional options to add to Tonic.List of stringsoptional[]
tonic_pluginAdditional plugins to add to Tonic.LabeloptionalNone
tonic_plugin_flagTonic plugin flag format. (e.g. --plugin=protoc-gen-tonic=%s))Stringoptional"--plugin=protoc-gen-tonic=%s"
tonic_runtimeThe Tonic runtime crates to use.LabeloptionalNone

rust_proto_library

rust_proto_library(name, deps, crate_name, rust_deps, rustc_flags)

Builds a Rust library crate from a set of proto_librarys.

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding stubs.List of labelsrequired
crate_nameCrate 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.
Stringoptional""
rust_depsThe crates the generated library depends on.List of labelsoptional[]
rustc_flagsList 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 stringsoptional[]

rust_prost_dependencies

rust_prost_dependencies(bzlmod)

Declares repositories needed for prost.

PARAMETERS

NameDescriptionDefault Value
bzlmodWhether bzlmod is enabled.False

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

NameDescriptionDefault Value
nameThe name of the target.none
kwargsAdditional 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

NameDescriptionDefault Value
bzlmodWhether 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

NameDescriptionDefault Value
register_toolchains

-

True

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

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, merge_cc_lib_objects_into_rlib,
             wrap_static_fns)

Generates a rust source file from a cc_library and a header.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgen_flagsFlags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.List of stringsoptional[]
cc_libThe cc_library that contains the .h file. This is used to find the transitive includes.Labelrequired
clang_flagsFlags to pass directly to the clang executable.List of stringsoptional[]
headerThe .h file to generate bindings for.Labelrequired
merge_cc_lib_objects_into_rlibWhen True, objects from cc_lib will be copied into the rlib archive produced by the rust_library that depends on this rust_bindgen rule (using BuildInfo provider)BooleanoptionalTrue
wrap_static_fnsWhether 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).BooleanoptionalFalse

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgenThe label of a bindgen executable.LabeloptionalNone
clangThe label of a clang executable.LabeloptionalNone
default_rustfmtIf set, rust_bindgen targets will always format generated sources with rustfmt.BooleanoptionalTrue
libclangA cc_library that provides bindgen's runtime dependency on libclang.LabeloptionalNone
libstdcxxA 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.LabeloptionalNone

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

NameDescriptionDefault Value
nameA unique name for this target.none
headerThe label of the .h file to generate bindings for.none
cc_libThe label of the cc_library that contains the .h file. This is used to find the transitive includes.none
bindgen_flagsFlags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.None
bindgen_featuresThe features attribute for the rust_bindgen target.None
clang_flagsFlags to pass directly to the clang executable.None
wrap_static_fnsWhether 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",False
kwargsArguments to forward to the underlying rust_library rule.none

rust_bindgen_register_toolchains

rust_bindgen_register_toolchains(register_toolchains)

Registers the default toolchains for the rules_rust bindgen rules.

PARAMETERS

NameDescriptionDefault Value
register_toolchainsWhether or not to register toolchains.True

Rust Wasm Bindgen

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgen_flagsFlags to pass directly to the bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details.List of stringsoptional[]
targetThe type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details.Stringoptional"bundler"
target_archThe target architecture to use for the wasm-bindgen command line option.Stringoptional"wasm32"
wasm_fileThe .wasm file or crate to generate bindings for.Labelrequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgenThe label of a wasm-bindgen-cli executable.LabeloptionalNone

RustWasmBindgenInfo

RustWasmBindgenInfo(js, ts, wasm)

Info about wasm-bindgen outputs.

FIELDS

NameDescription
jsDepset[File]: The Javascript files produced by wasm-bindgen.
tsDepset[File]: The Typescript files produced by wasm-bindgen.
wasmFile: 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

NameDescriptionDefault Value
register_toolchainsWhether or not to register toolchains.True

Cargo

cargo_dep_env

cargo_dep_env(name, src, out_dir)

A rule for generating variables for dependent cargo_build_scripts without a build script. This is useful for using Bazel rules instead of a build script, while also generating configuration information for build scripts which depend on this crate.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
srcFile 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 (\\).
Labelrequired
out_dirFolder 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.
LabeloptionalNone

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

NameDescriptionDefault Value
nameThe name for the underlying rule. This should be the name of the package being compiled, optionally with a suffix of _bs. Otherwise, you can set the package name via pkg_name.none
editionThe rust edition to use for the internal binary crate.None
crate_nameCrate name to use for build script.None
crate_rootThe file that will be passed to rustc to be used for building this crate.None
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made.[]
crate_featuresA list of features to enable for the build script.[]
versionThe semantic version (semver) of the crate.None
depsThe build-dependencies of the crate.[]
link_depsThe subset of the (normal) dependencies of the crate that have the links attribute and therefore provide environment variables to this build script.[]
proc_macro_depsList of rust_proc_macro targets used to build the script.[]
build_script_envEnvironment variables for build scripts.{}
dataFiles needed by the build script.[]
compile_dataFiles needed for the compilation of the build script.[]
toolsTools (executables) needed by the build script.[]
linksName of the native library this crate links against.None
rundirA directory to cd to before the cargo_build_script is run. This should be a path relative to the exec root.

The default behaviour (and the behaviour if rundir is set to the empty string) is to change to the relative path corresponding to the cargo manifest directory, which replicates the normal behaviour of cargo so it is easy to write compatible build scripts.

If set to ., the cargo build script will run in the exec root.
None
rustc_envEnvironment variables to set in rustc when compiling the build script.{}
rustc_env_filesFiles containing additional environment variables to set for rustc when building the build script.[]
rustc_flagsList of compiler flags passed to rustc.[]
visibilityVisibility to apply to the generated build script output.None
tags(list of str, optional): Tags to apply to the generated build script output.None
aliasesRemap 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.None
pkg_nameOverride the package name used for the build script. This is useful if the build target name gets too long otherwise.None
kwargsForwards to the underlying rust_binary rule. An exception is the compatible_with attribute, which shouldn't be forwarded to the rust_binary, as the rust_binary is only built and used in exec mode. We propagate the compatible_with attribute to the _build_scirpt_run target.none

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

NameDescriptionDefault Value
envA map of environment variablesnone

RETURNS

str: A json encoded string of the environment variables

cargo_bootstrap_repository

cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_config, 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are madeList of labelsoptional[]
binaryThe binary to build (the --bin parameter for Cargo). If left empty, the repository name will be used.Stringoptional""
build_modeThe build mode the binary should be built withStringoptional"release"
cargo_configThe path of the Cargo configuration (Config.toml) file.LabeloptionalNone
cargo_lockfileThe lockfile of the crate_universe resolverLabelrequired
cargo_tomlThe path of the Cargo.toml file.Labelrequired
envA 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 -> Stringoptional{}
env_labelA 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 -> Stringoptional{}
repo_mappingIn 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 -> Stringoptional
rust_toolchain_cargo_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
rust_toolchain_rustc_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
timeoutMaximum duration of the Cargo build command in secondsIntegeroptional600
versionThe version of Rust the currently registered toolchain is using. Eg. 1.56.0, or nightly/2021-09-08Stringoptional"1.82.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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
proc_macro_srvThe path to a rust_analyzer_proc_macro_srv binary.LabeloptionalNone
rustcThe path to a rustc binary.Labelrequired
rustc_srcsThe source code of rustc.Labelrequired

rust_analyzer_aspect

rust_analyzer_aspect(name)

Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json

ASPECT ATTRIBUTES

NameType
depsString
proc_macro_depsString
crateString
actualString
protoString

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

Rust rules

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

cargo_dep_env

cargo_dep_env(name, src, out_dir)

A rule for generating variables for dependent cargo_build_scripts without a build script. This is useful for using Bazel rules instead of a build script, while also generating configuration information for build scripts which depend on this crate.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
srcFile 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 (\\).
Labelrequired
out_dirFolder 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.
LabeloptionalNone

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

incompatible_flag

incompatible_flag(name, issue)

A rule defining an incompatible flag.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
issueThe link to the github issue associated with this flagStringrequired

rust_analyzer_toolchain

rust_analyzer_toolchain(name, proc_macro_srv, rustc, rustc_srcs)

A toolchain for rust-analyzer.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
proc_macro_srvThe path to a rust_analyzer_proc_macro_srv binary.LabeloptionalNone
rustcThe path to a rustc binary.Labelrequired
rustc_srcsThe source code of rustc.Labelrequired

rust_binary

rust_binary(name, deps, srcs, data, aliases, alwayslink, binary_name, 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
binary_nameOverride the resulting binary file name. By default, the binary file will be named using the name attribute on this rule, however sometimes that is not deseriable.Stringoptional""
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
crate_typeCrate 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).
Stringoptional"bin"
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
envSpecifies 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 -> Stringoptional{}
experimental_use_cc_common_linkWhether 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.Integeroptional-1
linker_scriptLink script to forward into linker via rustc options.LabeloptionalNone
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
out_binaryForce 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.BooleanoptionalFalse
platformOptional platform to transition the binary to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional-1
versionA version to inject in the cargo environment variable.Stringoptional"0.0.0"

rust_bindgen

rust_bindgen(name, bindgen_flags, cc_lib, clang_flags, header, merge_cc_lib_objects_into_rlib,
             wrap_static_fns)

Generates a rust source file from a cc_library and a header.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgen_flagsFlags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.List of stringsoptional[]
cc_libThe cc_library that contains the .h file. This is used to find the transitive includes.Labelrequired
clang_flagsFlags to pass directly to the clang executable.List of stringsoptional[]
headerThe .h file to generate bindings for.Labelrequired
merge_cc_lib_objects_into_rlibWhen True, objects from cc_lib will be copied into the rlib archive produced by the rust_library that depends on this rust_bindgen rule (using BuildInfo provider)BooleanoptionalTrue
wrap_static_fnsWhether 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).BooleanoptionalFalse

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgenThe label of a bindgen executable.LabeloptionalNone
clangThe label of a clang executable.LabeloptionalNone
default_rustfmtIf set, rust_bindgen targets will always format generated sources with rustfmt.BooleanoptionalTrue
libclangA cc_library that provides bindgen's runtime dependency on libclang.LabeloptionalNone
libstdcxxA 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.LabeloptionalNone

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsRust targets to run clippy on.List of labelsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
crateThe 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.
Labelrequired
html_after_contentFile to add in <body>, after content.LabeloptionalNone
html_before_contentFile to add in <body>, before content.LabeloptionalNone
html_in_headerFile to add to <head>.LabeloptionalNone
markdown_cssCSS files to include via <link> in a rendered Markdown file.List of labelsoptional[]
rustc_flagsDeprecated: use rustdoc_flags insteadList of stringsoptional[]
rustdoc_flagsList 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 stringsoptional[]

rust_doc_test

rust_doc_test(name, deps, crate, proc_macro_deps)

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
crateThe 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.Labelrequired
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]

rust_grpc_library

rust_grpc_library(name, deps, crate_name, rust_deps, rustc_flags)

Builds a Rust library crate from a set of proto_librarys 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding gRPC stubs.List of labelsrequired
crate_nameCrate 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.
Stringoptional""
rust_depsThe crates the generated library depends on.List of labelsoptional[]
rustc_flagsList 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 stringsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
disable_pipeliningDisables 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.BooleanoptionalFalse
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsOther dependencies to forward through this crate group.List of labelsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"0.0.0"

rust_prost_toolchain

rust_prost_toolchain(name, include_transitive_deps, prost_opts, prost_plugin, prost_plugin_flag,
                     prost_runtime, prost_types, proto_compiler, tonic_opts, tonic_plugin,
                     tonic_plugin_flag, tonic_runtime)

Rust Prost toolchain rule.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
include_transitive_depsWhether to include transitive dependencies. If set to True, all transitive dependencies will directly accessible by the dependent crate.BooleanoptionalFalse
prost_optsAdditional options to add to Prost.List of stringsoptional[]
prost_pluginAdditional plugins to add to Prost.Labelrequired
prost_plugin_flagProst plugin flag format. (e.g. --plugin=protoc-gen-prost=%s)Stringoptional"--plugin=protoc-gen-prost=%s"
prost_runtimeThe Prost runtime crates to use.Labelrequired
prost_typesThe Prost types crates to use.Labelrequired
proto_compilerThe protoc compiler to use. Note that this attribute is deprecated - prefer to use --incompatible_enable_proto_toolchain_resolution.LabeloptionalNone
tonic_optsAdditional options to add to Tonic.List of stringsoptional[]
tonic_pluginAdditional plugins to add to Tonic.LabeloptionalNone
tonic_plugin_flagTonic plugin flag format. (e.g. --plugin=protoc-gen-tonic=%s))Stringoptional"--plugin=protoc-gen-tonic=%s"
tonic_runtimeThe Tonic runtime crates to use.LabeloptionalNone

rust_proto_library

rust_proto_library(name, deps, crate_name, rust_deps, rustc_flags)

Builds a Rust library crate from a set of proto_librarys.

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of proto_library dependencies that will be built. One crate for each proto_library will be created with the corresponding stubs.List of labelsrequired
crate_nameCrate 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.
Stringoptional""
rust_depsThe crates the generated library depends on.List of labelsoptional[]
rustc_flagsList 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 stringsoptional[]

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
experimental_use_cc_common_linkWhether 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.Integeroptional-1
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
platformOptional platform to transition the shared library to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
platformOptional platform to transition the static library to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
versionA version to inject in the cargo environment variable.Stringoptional"0.0.0"

rust_stdlib_filegroup

rust_stdlib_filegroup(name, srcs)

A dedicated filegroup-like rule for Rust stdlib artifacts.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
srcsThe list of targets/files that are components of the rust-stdlib file groupList of labelsrequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList 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 labelsoptional[]
srcsList 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 labelsoptional[]
dataList 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 labelsoptional[]
aliasesRemap 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 -> Stringoptional{}
alwayslinkIf 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.
BooleanoptionalFalse
compile_dataList 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 labelsoptional[]
crateTarget inline tests declared in the given crate

These tests are typically those that would be held out under #[cfg(test)] declarations.
LabeloptionalNone
crate_featuresList 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 stringsoptional[]
crate_nameCrate 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.
Stringoptional""
crate_rootThe 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.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
envSpecifies 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 -> Stringoptional{}
env_inheritSpecifies additional environment variables to inherit from the external environment when the test is executed by bazel test.List of stringsoptional[]
experimental_use_cc_common_linkWhether 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.Integeroptional-1
mallocOverride 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.
Labeloptional"@bazel_tools//tools/cpp:malloc"
platformOptional platform to transition the test to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
rustc_envDictionary 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 -> Stringoptional{}
rustc_env_filesFiles 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 labelsoptional[]
rustc_flagsList 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 stringsoptional[]
stampWhether 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.
Integeroptional0
use_libtest_harnessWhether 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.BooleanoptionalTrue
versionA version to inject in the cargo environment variable.Stringoptional"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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
allocator_libraryTarget that provides allocator functions when rust_library targets are embedded in a cc_binary.Labeloptional"@rules_rust//ffi/cc/allocator_library"
binary_extThe extension for binaries created from rustc.Stringrequired
cargoThe location of the cargo binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
cargo_clippyThe location of the cargo_clippy binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
clippy_driverThe location of the clippy-driver binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
debug_infoRustc debug info levels per opt levelDictionary: String -> Stringoptional{"dbg": "2", "fastbuild": "0", "opt": "0"}
default_editionThe edition to use for rust_* rules that don't specify an edition. If absent, every rule is required to specify its edition attribute.Stringoptional""
dylib_extThe extension for dynamic libraries created from rustc.Stringrequired
envEnvironment variables to set in actions.Dictionary: String -> Stringoptional{}
exec_tripleThe platform triple for the toolchains execution environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurationsStringrequired
experimental_link_std_dylibLabel to a boolean build setting that controls whether whether to link libstd dynamically.Labeloptional"@rules_rust//rust/settings:experimental_link_std_dylib"
experimental_use_cc_common_linkLabel to a boolean build setting that controls whether cc_common.link is used to link rust binaries.Labeloptional"@rules_rust//rust/settings:experimental_use_cc_common_link"
extra_exec_rustc_flagsExtra flags to pass to rustc in exec configurationList of stringsoptional[]
extra_rustc_flagsExtra 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 stringsoptional[]
extra_rustc_flags_for_crate_typesExtra flags to pass to rustc based on crate typeDictionary: String -> List of stringsoptional{}
global_allocator_libraryTarget that provides allocator functions for when a global allocator is present.Labeloptional"@rules_rust//ffi/cc/global_allocator_library"
llvm_covThe 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.LabeloptionalNone
llvm_profdataThe 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.LabeloptionalNone
llvm_toolsLLVM tools that are shipped with the Rust toolchain.LabeloptionalNone
opt_levelRustc optimization levels.Dictionary: String -> Stringoptional{"dbg": "0", "fastbuild": "0", "opt": "3"}
per_crate_rustc_flagsExtra flags to pass to rustc in non-exec configurationList of stringsoptional[]
rust_docThe location of the rustdoc binary. Can be a direct source or a filegroup containing one item.Labelrequired
rust_stdThe Rust standard library.Labelrequired
rustcThe location of the rustc binary. Can be a direct source or a filegroup containing one item.Labelrequired
rustc_libThe libraries used by rustc during compilation.LabeloptionalNone
rustfmtDeprecated: Instead see rustfmt_toolchainLabeloptionalNone
staticlib_extThe extension for static libraries created from rustc.Stringrequired
stdlib_linkflagsAdditional 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 stringsrequired
strip_levelRustc strip levels. For all potential options, see https://doc.rust-lang.org/rustc/codegen-options/index.html#stripDictionary: String -> Stringoptional{"dbg": "none", "fastbuild": "none", "opt": "debuginfo"}
target_jsonOverride the target_triple with a custom target specification. For more details see: https://doc.rust-lang.org/rustc/targets/custom.htmlStringoptional""
target_tripleThe platform triple for the toolchains target environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurationsStringoptional""

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgen_flagsFlags to pass directly to the bindgen executable. See https://github.com/rustwasm/wasm-bindgen/ for details.List of stringsoptional[]
targetThe type of output to generate. See https://rustwasm.github.io/wasm-bindgen/reference/deployment.html for details.Stringoptional"bundler"
target_archThe target architecture to use for the wasm-bindgen command line option.Stringoptional"wasm32"
wasm_fileThe .wasm file or crate to generate bindings for.Labelrequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgenThe label of a wasm-bindgen-cli executable.LabeloptionalNone

rustfmt_test

rustfmt_test(name, targets)

A test rule for performing rustfmt --check on a set of targets

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
targetsRust targets to run rustfmt --check on.List of labelsoptional[]

rustfmt_toolchain

rustfmt_toolchain(name, rustc, rustc_lib, rustfmt)

A toolchain for rustfmt

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
rustcThe location of the rustc binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
rustc_libThe libraries used by rustc during compilation.LabeloptionalNone
rustfmtThe location of the rustfmt binary. Can be a direct source or a filegroup containing one item.Labelrequired

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

NameDescription
aliasesDict[Label, String]: Renamed and aliased crates
compile_datadepset[File]: Compile data required by this crate.
compile_data_targetsdepset[Label]: Compile data targets required by this crate.
datadepset[File]: Compile data required by crates that use the current crate as a proc-macro.
depsdepset[DepVariantInfo]: This crate's (rust or cc) dependencies' providers.
editionstr: The edition of this crate.
is_testbool: If the crate is being compiled in a test context
metadataFile: The output from rustc from producing the output file. It is optional.
namestr: The name of this crate.
outputFile: The output File that will be produced, depends on crate type.
ownerLabel: The label of the target that produced this CrateInfo
proc_macro_depsdepset[DepVariantInfo]: This crate's rust proc_macro dependencies' providers.
rootFile: The source File entrypoint to this crate, eg. lib.rs
rustc_envDict[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_outputFile: The output from rustc from producing the output file. It is optional.
rustc_rmeta_outputFile: The rmeta file produced for this crate. It is optional.
srcsdepset[File]: All source Files that are part of the crate.
std_dylibFile: libstd.so file
typestr: The type of this crate (see rustc --crate-type).
wrapped_crate_typestr, 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

NameDescription
dep_envFile: File with environment variables direct dependencies build scripts rely upon.
direct_cratesdepset[AliasableDepInfo]
link_search_path_filesdepset[File]: All transitive files containing search paths to pass to the linker
transitive_build_infosdepset[BuildInfo]
transitive_crate_outputsdepset[File]: All transitive crate outputs.
transitive_cratesdepset[CrateInfo]
transitive_datadepset[File]: Data of all transitive non-macro dependencies.
transitive_metadata_outputsdepset[File]: All transitive metadata dependencies (.rmeta, for crates that provide them) and all transitive object dependencies (.rlib) for crates that don't provide metadata.
transitive_noncratesdepset[LinkerInput]: All transitive dependencies that aren't crates.
transitive_proc_macro_datadepset[File]: Data of all transitive proc-macro dependencies, and non-macro dependencies of those macros.

RustWasmBindgenInfo

RustWasmBindgenInfo(js, ts, wasm)

Info about wasm-bindgen outputs.

FIELDS

NameDescription
jsDepset[File]: The Javascript files produced by wasm-bindgen.
tsDepset[File]: The Typescript files produced by wasm-bindgen.
wasmFile: 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

NameDescription
alloc_filesList[File]: .a files related to the alloc module.
between_alloc_and_core_filesList[File]: .a files related to the compiler_builtins module.
between_core_and_std_filesList[File]: .a files related to all modules except adler, alloc, compiler_builtins, core, and std.
core_filesList[File]: .a files related to the core and adler modules
dot_a_filesDepset[File]: Generated .a files
memchr_filesDepset[File]: .a files associated with the memchr module.
panic_filesDepset[File]: .a files associated with panic_unwind and panic_abort.
self_contained_filesList[File]: All .o files from the self-contained directory.
srcsList[Target]: All targets from the original srcs attribute.
std_dylibFile: libstd.so file
std_filesDepset[File]: .a files associated with the std module.
std_rlibsList[File]: All .rlib files
test_filesDepset[File]: .a files associated with the test module.

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

NameDescriptionDefault Value
nameThe name for the underlying rule. This should be the name of the package being compiled, optionally with a suffix of _bs. Otherwise, you can set the package name via pkg_name.none
editionThe rust edition to use for the internal binary crate.None
crate_nameCrate name to use for build script.None
crate_rootThe file that will be passed to rustc to be used for building this crate.None
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made.[]
crate_featuresA list of features to enable for the build script.[]
versionThe semantic version (semver) of the crate.None
depsThe build-dependencies of the crate.[]
link_depsThe subset of the (normal) dependencies of the crate that have the links attribute and therefore provide environment variables to this build script.[]
proc_macro_depsList of rust_proc_macro targets used to build the script.[]
build_script_envEnvironment variables for build scripts.{}
dataFiles needed by the build script.[]
compile_dataFiles needed for the compilation of the build script.[]
toolsTools (executables) needed by the build script.[]
linksName of the native library this crate links against.None
rundirA directory to cd to before the cargo_build_script is run. This should be a path relative to the exec root.

The default behaviour (and the behaviour if rundir is set to the empty string) is to change to the relative path corresponding to the cargo manifest directory, which replicates the normal behaviour of cargo so it is easy to write compatible build scripts.

If set to ., the cargo build script will run in the exec root.
None
rustc_envEnvironment variables to set in rustc when compiling the build script.{}
rustc_env_filesFiles containing additional environment variables to set for rustc when building the build script.[]
rustc_flagsList of compiler flags passed to rustc.[]
visibilityVisibility to apply to the generated build script output.None
tags(list of str, optional): Tags to apply to the generated build script output.None
aliasesRemap 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.None
pkg_nameOverride the package name used for the build script. This is useful if the build target name gets too long otherwise.None
kwargsForwards to the underlying rust_binary rule. An exception is the compatible_with attribute, which shouldn't be forwarded to the rust_binary, as the rust_binary is only built and used in exec mode. We propagate the compatible_with attribute to the _build_scirpt_run target.none

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

NameDescriptionDefault Value
envA map of environment variablesnone

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

NameDescriptionDefault Value
nameThe name of the toolchain proxy repository contianing the registerable toolchain.none
versionThe version of the tool among "nightly", "beta', or an exact version.none
exec_compatible_withA list of constraints for the execution platform for this toolchain.[]
target_compatible_withA list of constraints for the target platform for this toolchain.[]
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details.None
urlsA 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
authAuth 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_archiveNone
auth_patternsOverride mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archiveNone

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

NameDescriptionDefault Value
nameA unique name for this target.none
headerThe label of the .h file to generate bindings for.none
cc_libThe label of the cc_library that contains the .h file. This is used to find the transitive includes.none
bindgen_flagsFlags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.None
bindgen_featuresThe features attribute for the rust_bindgen target.None
clang_flagsFlags to pass directly to the clang executable.None
wrap_static_fnsWhether 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",False
kwargsArguments to forward to the underlying rust_library rule.none

rust_bindgen_register_toolchains

rust_bindgen_register_toolchains(register_toolchains)

Registers the default toolchains for the rules_rust bindgen rules.

PARAMETERS

NameDescriptionDefault Value
register_toolchainsWhether or not to register toolchains.True

rust_prost_dependencies

rust_prost_dependencies(bzlmod)

Declares repositories needed for prost.

PARAMETERS

NameDescriptionDefault Value
bzlmodWhether bzlmod is enabled.False

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

NameDescriptionDefault Value
nameThe name of the target.none
kwargsAdditional 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

NameDescriptionDefault Value
bzlmodWhether 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

NameDescriptionDefault Value
register_toolchains

-

True

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, aliases)

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

NameDescriptionDefault Value
dev_componentsWhether to download the rustc-dev components (defaults to False). Requires version to be "nightly".False
editionThe rust edition to be used by default (2015, 2018, or 2021). If absent, every target is required to specify its edition attribute.None
allocator_libraryTarget that provides allocator functions when rust_library targets are embedded in a cc_binary.None
global_allocator_libraryTarget that provides allocator functions when global allocator is used with cc_common.link.None
register_toolchainsIf true, repositories will be generated to produce and register rust_toolchain targets.True
rustfmt_versionThe version of rustfmt. If none is supplied and only a single version in versions is given, then this defaults to that version, otherwise will default to the default nightly version.None
rust_analyzer_versionThe version of Rustc to pair with rust-analyzer.None
sha256sA dict associating tool subdirectories to sha256 hashes.None
extra_target_triplesAdditional rust-style targets that rust toolchains should support.["wasm32-unknown-unknown", "wasm32-wasip1"]
extra_rustc_flagsDictionary of target triples to list of extra flags to pass to rustc in non-exec configuration.None
extra_exec_rustc_flagsExtra flags to pass to rustc in exec configuration.None
urlsA 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"]
versionsA list of toolchain versions to download. This parameter only accepts one versions per channel. E.g. ["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"].["1.82.0", "nightly/2024-10-17"]
aliasesA mapping of "full" repository name to another name to use instead.{}

rust_repositories

rust_repositories(kwargs)

Deprecated: Use rules_rust_dependencies and rust_register_toolchains directly.

PARAMETERS

NameDescriptionDefault Value
kwargsKeyword arguments for the rust_register_toolchains macro.none

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, aliases)

Assembles a remote repository for the given toolchain params, produces a proxy repository to contain the toolchain declaration, and registers the toolchains.

PARAMETERS

NameDescriptionDefault Value
nameThe name of the generated repositorynone
versionsA 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_tripleThe Rust-style target that this compiler runs onnone
target_settingsA 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_libraryTarget that provides allocator functions when rust_library targets are embedded in a cc_binary.None
global_allocator_libraryTarget that provides allocator functions a global allocator is used with cc_common.link.None
extra_target_triplesAdditional 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_versionThe version of rustfmt to be associated with the toolchain.None
editionThe rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute.None
dev_componentsWhether to download the rustc-dev components. Requires version to be "nightly".False
extra_rustc_flagsDictionary of target triples to list of extra flags to pass to rustc in non-exec configuration.None
extra_exec_rustc_flagsExtra flags to pass to rustc in exec configuration.None
opt_levelDictionary of target triples to optimiztion config.None
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details.None
urlsA 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"]
authAuth 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_archiveNone
auth_patternsOverride mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archiveNone
register_toolchainIf True, the generated rust_toolchain target will become a registered toolchain.True
exec_compatible_withA list of constraints for the execution platform for this toolchain.None
default_target_compatible_withA list of constraints for the target platform for this toolchain when the exec platform is the same as the target platform.None
aliasesReplacement names to use for toolchains created by this macro.{}

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

NameDescriptionDefault Value
nameThe name of the test_suite.none
srcsAll test sources, typically glob(["tests/**/*.rs"]).none
shared_srcsOptional argument for sources shared among tests, typically helper functions.[]
kwargsAdditional 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

NameDescriptionDefault Value
nameThe name of the generated repositorynone
versionThe version of the tool among "nightly", "beta", or an exact version.none
exec_tripleThe Rust-style target that this compiler runs on.none
target_tripleThe Rust-style target to build for.none
exec_compatible_withA list of constraints for the execution platform for this toolchain.None
target_compatible_withA list of constraints for the target platform for this toolchain.None
target_settingsA list of config_settings that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution.[]
channelThe channel of the Rust toolchain.None
allocator_libraryTarget that provides allocator functions when rust_library targets are embedded in a cc_binary.None
global_allocator_libraryTarget that provides allocator functions when a global allocator is used with cc_common.link.None
rustfmt_versionThe version of rustfmt to be associated with the toolchain.None
editionThe rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute.None
dev_componentsWhether to download the rustc-dev components. Requires version to be "nightly". Defaults to False.False
extra_rustc_flagsExtra flags to pass to rustc in non-exec configuration.None
extra_exec_rustc_flagsExtra flags to pass to rustc in exec configuration.None
opt_levelOptimization level config for this toolchain.None
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details.None
urlsA 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"]
authAuth 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_archiveNone
auth_patternsA 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

NameDescriptionDefault Value
register_toolchainsWhether or not to register toolchains.True

rust_analyzer_aspect

rust_analyzer_aspect(name)

Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json

ASPECT ATTRIBUTES

NameType
depsString
proc_macro_depsString
crateString
actualString
protoString

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

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: Executes rustfmt --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

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired

cargo_bootstrap_repository

cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_config, 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are madeList of labelsoptional[]
binaryThe binary to build (the --bin parameter for Cargo). If left empty, the repository name will be used.Stringoptional""
build_modeThe build mode the binary should be built withStringoptional"release"
cargo_configThe path of the Cargo configuration (Config.toml) file.LabeloptionalNone
cargo_lockfileThe lockfile of the crate_universe resolverLabelrequired
cargo_tomlThe path of the Cargo.toml file.Labelrequired
envA 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 -> Stringoptional{}
env_labelA 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 -> Stringoptional{}
repo_mappingIn 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 -> Stringoptional
rust_toolchain_cargo_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
rust_toolchain_rustc_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
timeoutMaximum duration of the Cargo build command in secondsIntegeroptional600
versionThe version of Rust the currently registered toolchain is using. Eg. 1.56.0, or nightly/2021-09-08Stringoptional"1.82.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

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
exec_compatible_withA list of constraints for the execution platform for this toolchain.List of stringsoptional[]
repo_mappingIn 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 -> Stringoptional
target_compatible_withA list of constraints for the target platform for this toolchain.List of stringsoptional[]
target_settingsA 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 stringsoptional[]
toolchainThe name of the toolchain implementation target.Stringrequired
toolchain_typeThe toolchain type of the toolchain to declareStringrequired

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

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
allocator_libraryTarget that provides allocator functions when rust_library targets are embedded in a cc_binary.Stringoptional"@rules_rust//ffi/cc/allocator_library"
authAuth object compatible with repository_ctx.download to use when downloading files. See repository_ctx.download for more details.Dictionary: String -> Stringoptional{}
auth_patternsA list of patterns to match against urls for which the auth object should be used.List of stringsoptional[]
dev_componentsWhether to download the rustc-dev components (defaults to False). Requires version to be "nightly".BooleanoptionalFalse
editionThe rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its edition attribute.Stringoptional""
exec_tripleThe Rust-style target that this compiler runs onStringrequired
extra_exec_rustc_flagsExtra flags to pass to rustc in exec configurationList of stringsoptional[]
extra_rustc_flagsExtra flags to pass to rustc in non-exec configurationList of stringsoptional[]
global_allocator_libraryTarget that provides allocator functions when a global allocator is used with cc_common.link.Stringoptional"@rules_rust//ffi/cc/global_allocator_library"
netrc.netrc file to use for authentication; mirrors the eponymous attribute from http_archiveStringoptional""
opt_levelRustc optimization levels. For more details see the documentation for rust_toolchain.opt_level.Dictionary: String -> Stringoptional{}
repo_mappingIn 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 -> Stringoptional
rustfmt_versionThe version of the tool among "nightly", "beta", or an exact version.Stringoptional""
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_register_toolchains for more details.Dictionary: String -> Stringoptional{}
target_tripleThe Rust-style target that this compiler builds for.Stringrequired
urlsA 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 stringsoptional["https://static.rust-lang.org/dist/{}.tar.xz"]
versionThe version of the tool among "nightly", "beta", or an exact version.Stringrequired

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

  1. Setup
  2. Dependencies
  3. Crate reference

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.

  1. Cargo workspace
  2. Direct Dependencies
  3. 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, splicing_config, 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, splicing_config,
                 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

NameDescriptionTypeMandatoryDefault
nameThe name of the repo to generateNameoptional"crates"
cargo_configA Cargo configuration file.LabeloptionalNone
cargo_lockfileThe path to an existing Cargo.lock fileLabeloptionalNone
generate_binariesWhether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated.BooleanoptionalFalse
generate_build_scriptsWhether or not to generate cargo build scripts by default.BooleanoptionalTrue
manifestsA list of Cargo manifests (Cargo.toml files).List of labelsoptional[]
splicing_configThe 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.Stringoptional""
supported_platform_triplesA set of all platform triples to consider when generating dependencies.List of stringsoptional["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-fuchsia", "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", "wasm32-wasip1", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-fuchsia", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"]

annotation

Attributes

NameDescriptionTypeMandatoryDefault
depsA list of labels to add to a crate's rust_library::deps attribute.List of stringsoptional[]
dataA list of labels to add to a crate's rust_library::data attribute.List of stringsoptional[]
additive_build_fileA file containing extra contents to write to the bottom of generated BUILD files.LabeloptionalNone
additive_build_file_contentExtra contents to write to the bottom of generated BUILD files.Stringoptional""
alias_ruleAlias rule to use instead of native.alias(). Overrides render_config's 'default_alias_rule'.Stringoptional""
build_script_dataA list of labels to add to a crate's cargo_build_script::data attribute.List of stringsoptional[]
build_script_data_globA list of glob patterns to add to a crate's cargo_build_script::data attributeList of stringsoptional[]
build_script_depsA list of labels to add to a crate's cargo_build_script::deps attribute.List of stringsoptional[]
build_script_envAdditional environment variables to set on a crate's cargo_build_script::env attribute.Dictionary: String -> Stringoptional{}
build_script_proc_macro_depsA list of labels to add to a crate's cargo_build_script::proc_macro_deps attribute.List of stringsoptional[]
build_script_rundirAn override for the build script's rundir attribute.Stringoptional""
build_script_rustc_envAdditional environment variables to set on a crate's cargo_build_script::env attribute.Dictionary: String -> Stringoptional{}
build_script_toolchainsA list of labels to set on a crates's cargo_build_script::toolchains attribute.List of labelsoptional[]
build_script_toolsA list of labels to add to a crate's cargo_build_script::tools attribute.List of stringsoptional[]
compile_dataA list of labels to add to a crate's rust_library::compile_data attribute.List of stringsoptional[]
compile_data_globA list of glob patterns to add to a crate's rust_library::compile_data attribute.List of stringsoptional[]
crateThe name of the crate the annotation is applied toStringrequired
crate_featuresA list of strings to add to a crate's rust_library::crate_features attribute.List of stringsoptional[]
data_globA list of glob patterns to add to a crate's rust_library::data attribute.List of stringsoptional[]
disable_pipeliningIf True, disables pipelining for library targets for this crate.BooleanoptionalFalse
extra_aliased_targetsA list of targets to add to the generated aliases in the root crate_universe repository.Dictionary: String -> Stringoptional{}
gen_all_binariesIf true, generates rust_binary targets for all of the crates binsBooleanoptionalFalse
gen_binariesAs a list, the subset of the crate's bins that should get rust_binary targets produced.List of stringsoptional[]
gen_build_scriptAn authorative flag to determine whether or not to produce cargo_build_script targets for the current crate. Supported values are 'on', 'off', and 'auto'.Stringoptional"auto"
override_target_binAn optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.LabeloptionalNone
override_target_build_scriptAn optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.LabeloptionalNone
override_target_libAn optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.LabeloptionalNone
override_target_proc_macroAn optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.LabeloptionalNone
patch_argsThe patch_args attribute of a Bazel repository rule. See http_archive.patch_argsList of stringsoptional[]
patch_toolThe patch_tool attribute of a Bazel repository rule. See http_archive.patch_toolStringoptional""
patchesThe patches attribute of a Bazel repository rule. See http_archive.patchesList of labelsoptional[]
proc_macro_depsA list of labels to add to a crate's rust_library::proc_macro_deps attribute.List of stringsoptional[]
repositoriesA list of repository names specified from crate.from_cargo(name=...) that this annotation is applied to. Defaults to all repositories.List of stringsoptional[]
rustc_envAdditional variables to set on a crate's rust_library::rustc_env attribute.Dictionary: String -> Stringoptional{}
rustc_env_filesA list of labels to set on a crate's rust_library::rustc_env_files attribute.List of stringsoptional[]
rustc_flagsA list of strings to set on a crate's rust_library::rustc_flags attribute.List of stringsoptional[]
shallow_sinceAn optional timestamp used for crates originating from a git repository instead of a crate registry. This flag optimizes fetching the source code.Stringoptional""
versionThe versions of the crate the annotation is applied to. Defaults to all versions.Stringoptional"*"

from_specs

Generates a repo @crates from the defined spec tags

Attributes

NameDescriptionTypeMandatoryDefault
nameThe name of the repo to generateNameoptional"crates"
cargo_configA Cargo configuration file.LabeloptionalNone
generate_binariesWhether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated.BooleanoptionalFalse
generate_build_scriptsWhether or not to generate cargo build scripts by default.BooleanoptionalTrue
splicing_configThe 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.Stringoptional""
supported_platform_triplesA set of all platform triples to consider when generating dependencies.List of stringsoptional["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-fuchsia", "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", "wasm32-wasip1", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-fuchsia", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"]

spec

Attributes

NameDescriptionTypeMandatoryDefault
artifactSet to 'bin' to pull in a binary crate as an artifact dependency. Requires a nightly Cargo.Stringoptional""
branchThe git branch of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified. Specifying rev is recommended for fully-reproducible builds.Stringoptional""
default_featuresMaps to the default-features flag.BooleanoptionalTrue
featuresA list of features to use for the crate.List of stringsoptional[]
gitThe Git url to use for the crate. Cannot be used with version.Stringoptional""
libIf using artifact = 'bin', additionally setting lib = True declares a dependency on both the package's library and binary, as opposed to just the binary.BooleanoptionalFalse
packageThe explicit name of the package.Stringrequired
revThe git revision of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified.Stringoptional""
tagThe git tag of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified. Specifying rev is recommended for fully-reproducible builds.Stringoptional""
versionThe exact version of the crate. Cannot be used with git.Stringoptional""

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

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 use crates_repository to make build targets for its dependencies. This is demonstrated below using the rustfilt 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.

ValueCargo command
Any of [true, 1, yes, on, workspace]cargo update --workspace
Any of [full, eager, all]cargo update
package_namecargo upgrade --package package_name
package_name@1.2.3cargo upgrade --package package_name --precise 1.2.3

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
annotationsExtra settings to apply to crates. See crate.annotation.Dictionary: String -> List of stringsoptional{}
bazelThe path to a bazel binary used to locate the output_base for the current workspace.LabeloptionalNone
buildifierThe path to a buildifier binary used to format generated BUILD files.Labeloptional"@rules_rust//crate_universe/private/vendor:buildifier"
cargo_bazelThe cargo-bazel binary to use for vendoring. If this attribute is not set, then a CARGO_BAZEL_GENERATOR_PATH action env will be used.Labeloptional"@@cargo_bazel_bootstrap//:binary"
cargo_configA Cargo configuration file.LabeloptionalNone
cargo_lockfileThe path to an existing Cargo.lock fileLabeloptionalNone
generate_binariesWhether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated.BooleanoptionalFalse
generate_build_scriptsWhether or not to generate cargo build scripts by default.BooleanoptionalTrue
generate_target_compatible_withDEPRECATED: Moved to render_config.BooleanoptionalTrue
manifestsA list of Cargo manifests (Cargo.toml files).List of labelsoptional[]
modeFlags 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.Stringoptional"remote"
packagesA set of crates (packages) specifications to depend on. See crate.spec.Dictionary: String -> Stringoptional{}
render_configThe 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.Stringoptional""
repository_nameThe name of the repository to generate for remote vendor modes. If unset, the label name will be usedStringoptional""
splicing_configThe 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.Stringoptional""
supported_platform_triplesA set of all platform triples to consider when generating dependencies.List of stringsoptional["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-fuchsia", "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", "wasm32-wasip1", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-fuchsia", "x86_64-unknown-linux-gnu", "x86_64-unknown-nixos-gnu", "x86_64-unknown-none"]
vendor_pathThe path to a directory to write files into. Absolute paths will be treated as relative to the workspace rootStringoptional"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

NameDescriptionDefault Value
normalIf True, normal dependencies are included in the output list.False
normal_devIf True, normal dev dependencies will be included in the output list..False
proc_macroIf True, proc_macro dependencies are included in the output list.False
proc_macro_devIf True, dev proc_macro dependencies are included in the output list.False
buildIf True, build dependencies are included in the output list.False
build_proc_macroIf True, build proc_macro dependencies are included in the output list.False
package_nameThe package name of the set of dependencies to look up. Defaults to native.package_name() when unset.None

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

NameDescriptionDefault Value
normalIf True, normal dependencies are included in the output list.False
normal_devIf True, normal dev dependencies will be included in the output list..False
proc_macroIf True, proc_macro dependencies are included in the output list.False
proc_macro_devIf True, dev proc_macro dependencies are included in the output list.False
buildIf True, build dependencies are included in the output list.False
build_proc_macroIf True, build proc_macro dependencies are included in the output list.False
package_nameThe package name of the set of dependencies to look up. Defaults to native.package_name() when unset.None

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

NameDescriptionDefault Value
versionThe version or semver-conditions to match with a crate. The wildcard * matches any version, including prerelease versions."*"
additive_build_fileA file containing extra contents to write to the bottom of generated BUILD files.None
additive_build_file_contentExtra contents to write to the bottom of generated BUILD files.None
alias_ruleAlias rule to use instead of native.alias(). Overrides render_config's 'default_alias_rule'.None
build_script_compile_dataA list of labels to add to a crate's cargo_build_script::compile_data attribute.None
build_script_dataA list of labels to add to a crate's cargo_build_script::data attribute.None
build_script_toolsA list of labels to add to a crate's cargo_build_script::tools attribute.None
build_script_data_globA list of glob patterns to add to a crate's cargo_build_script::data attribute.None
build_script_depsA list of labels to add to a crate's cargo_build_script::deps attribute.None
build_script_envAdditional environment variables to set on a crate's cargo_build_script::env attribute.None
build_script_proc_macro_depsA list of labels to add to a crate's cargo_build_script::proc_macro_deps attribute.None
build_script_rundirAn override for the build script's rundir attribute.None
build_script_rustc_envAdditional environment variables to set on a crate's cargo_build_script::env attribute.None
build_script_toolchainsA list of labels to set on a crates's cargo_build_script::toolchains attribute.None
compile_dataA list of labels to add to a crate's rust_library::compile_data attribute.None
compile_data_globA list of glob patterns to add to a crate's rust_library::compile_data attribute.None
crate_featuresA list of strings to add to a crate's rust_library::crate_features attribute.None
dataA list of labels to add to a crate's rust_library::data attribute.None
data_globA list of glob patterns to add to a crate's rust_library::data attribute.None
depsA list of labels to add to a crate's rust_library::deps attribute.None
extra_aliased_targetsA list of targets to add to the generated aliases in the root crate_universe repository.None
gen_binariesAs 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_pipeliningIf True, disables pipelining for library targets for this crate.False
gen_build_scriptAn authorative flag to determine whether or not to produce cargo_build_script targets for the current crate.None
patch_argsThe patch_args attribute of a Bazel repository rule. See http_archive.patch_argsNone
patch_toolThe patch_tool attribute of a Bazel repository rule. See http_archive.patch_toolNone
patchesThe patches attribute of a Bazel repository rule. See http_archive.patchesNone
proc_macro_depsA list of labels to add to a crate's rust_library::proc_macro_deps attribute.None
rustc_envAdditional variables to set on a crate's rust_library::rustc_env attribute.None
rustc_env_filesA list of labels to set on a crate's rust_library::rustc_env_files attribute.None
rustc_flagsA list of strings to set on a crate's rust_library::rustc_flags attribute.None
shallow_sinceAn optional timestamp used for crates originating from a git repository instead of a crate registry. This flag optimizes fetching the source code.None
override_targetsA 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

NameDescriptionDefault Value
commonA value that applies to all configurations.none
selectsA 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

NameDescriptionDefault Value
packageThe explicit name of the package (used when attempting to alias a crate).None
versionThe exact version of the crate. Cannot be used with git.None
artifactSet to "bin" to pull in a binary crate as an artifact dependency. Requires a nightly Cargo.None
libIf using artifact = "bin", additionally setting lib = True declares a dependency on both the package's library and binary, as opposed to just the binary.None
default_featuresMaps to the default-features flag.True
featuresA list of features to use for the crate[]
gitThe Git url to use for the crate. Cannot be used with version.None
branchThe git branch of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified. Specifying rev is recommended for fully-reproducible builds.None
tagThe git tag of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified. Specifying rev is recommended for fully-reproducible builds.None
revThe git revision of the remote crate. Tied with the git param. Only one of branch, tag or rev may be specified.None

RETURNS

string: A json encoded string of all inputs

crate.workspace_member

crate.workspace_member(version, sha256)

Define information for extra workspace members

PARAMETERS

NameDescriptionDefault Value
versionThe semver of the crate to download. Must be an exact version.none
sha256The 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

NameDescriptionDefault Value
depsThe desired list of crate targets.none
package_nameThe 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

NameDescriptionDefault Value
rust_versionThe version of rust to use when generating dependencies."1.82.0"
bootstrapIf true, a cargo_bootstrap_repository target will be generated.False
kwargsArguments to pass through to cargo_bazel_bootstrap.none

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

keydefinition
nameThe name of the crate. Eg tokio
repositoryThe rendered repository name for the crate. Directly relates to crate_repository_template.
tripleA platform triple. Eg x86_64-unknown-linux-gnu
versionThe crate version. Eg 1.2.3
targetThe library or binary target of the crate
fileThe basename of a file

PARAMETERS

NameDescriptionDefault Value
build_file_templateThe base template to use for BUILD file names. The available format keys are [{name}, {version}`]."//:BUILD.{name}-{version}.bazel"
crate_label_templateThe base template to use for crate labels. The available format keys are [{repository}, {name}, {version}, {target}]."@{repository}__{name}-{version}//:{target}"
crate_repository_templateThe base template to use for Crate label repository names. The available format keys are [{repository}, {name}, {version}]."{repository}__{name}-{version}"
crates_module_templateThe 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_ruleAlias 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>:' that takes a single label parameter 'actual'. See '@crate_index//:alias_rules.bzl' for an example."alias"
default_package_nameThe 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_withWhether to generate target_compatible_with annotations on the generated BUILD files. This catches a target_triplebeing targeted that isn't declared in supported_platform_triples.True
platforms_templateThe base template to use for platform names. See platforms documentation. The available format keys are [{triple}]."@rules_rust//rust/platform:{triple}"
regen_commandAn optional command to demonstrate how generated files should be regenerated.None
vendor_modeAn optional configuration for rendirng content to be rendered into repositories.None
generate_rules_license_metadataWhether to generate rules license metedataFalse

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

NameDescriptionDefault Value
resolver_versionThe 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:

variableusage
CARGO_BAZEL_GENERATOR_SHA256The sha256 checksum of the file located at CARGO_BAZEL_GENERATOR_URL
CARGO_BAZEL_GENERATOR_URLThe URL of a cargo-bazel binary. This variable takes precedence over attributes and can use file:// for local paths
CARGO_BAZEL_ISOLATEDAn authorative flag as to whether or not the CARGO_HOME environment variable should be isolated from the host configuration
CARGO_BAZEL_REPINAn 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_ONLYA 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.

ValueCargo command
Any of [true, 1, yes, on, workspace]cargo update --workspace
Any of [full, eager, all]cargo update
package_namecargo upgrade --package package_name
package_name@1.2.3cargo upgrade --package package_name@1.2.3
package_name@1.2.3=4.5.6cargo 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

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
annotationsExtra settings to apply to crates. See crate.annotation.Dictionary: String -> List of stringsoptional{}
cargo_configA Cargo configuration fileLabeloptionalNone
cargo_lockfileThe 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.Labelrequired
generate_binariesWhether to generate rust_binary targets for all the binary crates in every package. By default only the rust_library targets are generated.BooleanoptionalFalse
generate_build_scriptsWhether or not to generate cargo build scripts by default.BooleanoptionalTrue
generate_target_compatible_withDEPRECATED: Moved to render_config.BooleanoptionalTrue
generatorThe absolute label of a generator. Eg. @cargo_bazel_bootstrap//:cargo-bazel. This is typically used when bootstrappingStringoptional""
generator_sha256sDictionary of host_triple -> sha256 for a cargo-bazel binary.Dictionary: String -> Stringoptional{}
generator_urlsURL template from which to download the cargo-bazel binary. {host_triple} and will be filled in according to the host platform.Dictionary: String -> Stringoptional{}
isolatedIf 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.BooleanoptionalTrue
lockfileThe 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.LabeloptionalNone
manifestsA list of Cargo manifests (Cargo.toml files).List of labelsoptional[]
packagesA set of crates (packages) specifications to depend on. See crate.spec.Dictionary: String -> Stringoptional{}
quietIf stdout and stderr should not be printed to the terminal.BooleanoptionalTrue
render_configThe 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.Stringoptional""
repin_instructionsInstructions 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.Stringoptional""
repo_mappingIn 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 -> Stringoptional
rust_toolchain_cargo_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
rust_toolchain_rustc_templateThe 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.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
rust_versionThe version of Rust the currently registered toolchain is using. Eg. 1.56.0, or nightly/2021-09-08Stringoptional"1.82.0"
splicing_configThe 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.Stringoptional""
supported_platform_triplesA set of all platform triples to consider when generating dependencies.List of stringsoptional["aarch64-apple-darwin", "aarch64-apple-ios", "aarch64-apple-ios-sim", "aarch64-linux-android", "aarch64-pc-windows-msvc", "aarch64-unknown-fuchsia", "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", "wasm32-wasip1", "x86_64-apple-darwin", "x86_64-apple-ios", "x86_64-linux-android", "x86_64-pc-windows-msvc", "x86_64-unknown-freebsd", "x86_64-unknown-fuchsia", "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.