Rust rules

capture_clippy_output

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

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

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

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

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

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

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

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:

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
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

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
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

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

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

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

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

rust_grpc_library

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

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:

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:

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

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

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 rule.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
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

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

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

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

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

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:

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. The crate will be built using the same crate name as the underlying “:hello_lib” crate.

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:

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

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

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"
wasm_fileThe .wasm file or crate to generate bindings for.Labelrequired

rust_wasm_bindgen_toolchain

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

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

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

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

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

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

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

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

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

Dependencies used in the implementation of rules_rust.

rust_analyzer_toolchain_repository

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

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

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

Registers the default toolchains for the rules_rust bindgen rules.

PARAMETERS

NameDescriptionDefault Value
register_toolchainsWhether or not to register toolchains.True

rust_prost_dependencies

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

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

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

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

Register toolchains for proto compilation.

PARAMETERS

NameDescriptionDefault Value
register_toolchains - True

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

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-wasi"]
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 paramter only accepts one versions per channel. E.g. ["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"].["1.80.0", "nightly/2024-07-25"]

rust_repositories

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

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

rust_test_suite

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

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

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

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

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

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

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

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_lockfileThe lockfile of the crate_universe resolverLabelrequired
cargo_tomlThe path of the crate_universe resolver manifest (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.80.0"

rust_toolchain_repository_proxy

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

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