Rust rules

rust_benchmark

Builds a Rust benchmark test.

Warning: This rule is currently experimental. Rust Benchmark tests require the Bencher interface in the unstable libtest crate, which is behind the test unstable feature gate. As a result, using this rule would require using a nightly binary release of Rust.

Example:

Suppose you have the following directory structure for a Rust project with a library crate, fibonacci with benchmarks under the benches/ directory:

[workspace]/
  WORKSPACE
  fibonacci/
      BUILD
      src/
          lib.rs
      benches/
          fibonacci_bench.rs

fibonacci/src/lib.rs:

pub fn fibonacci(n: u64) -> u64 {
    if n < 2 {
        return n;
    }
    let mut n1: u64 = 0;
    let mut n2: u64 = 1;
    for _ in 1..n {
        let sum = n1 + n2;
        n1 = n2;
        n2 = sum;
    }
    n2
}

fibonacci/benches/fibonacci_bench.rs:

#![feature(test)]

extern crate test;
extern crate fibonacci;

use test::Bencher;

#[bench]
fn bench_fibonacci(b: &mut Bencher) {
    b.iter(|| fibonacci::fibonacci(40));
}

To build the benchmark test, add a rust_benchmark target:

fibonacci/BUILD:

package(default_visibility = ["//visibility:public"])

load("@rules_rust//rust:rust.bzl", "rust_library", "rust_benchmark")

rust_library(
  name = "fibonacci",
  srcs = ["src/lib.rs"],
)

rust_benchmark(
  name = "fibonacci_bench",
  srcs = ["benches/fibonacci_bench.rs"],
  deps = [":fibonacci"],
)

Run the benchmark test using: bazel run //fibonacci:fibonacci_bench.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
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{}
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_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
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[]
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[]
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
out_dir_tarDeprecated, do not use, see [#cargo_build_script] instead.LabeloptionalNone
proc_macro_depsList of rust_library targets with kind proc-macro 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_flagsList of compiler flags passed to rustc.List of stringsoptional[]
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[]
versionA version to inject in the cargo environment variable.Stringoptional“0.0.0”

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:rust.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:rust.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

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
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{}
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_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_type-Stringoptional“bin”
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[]
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[]
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
linker_scriptLink script to forward into linker via rustc options.LabeloptionalNone
out_binary-BooleanoptionalFalse
out_dir_tarDeprecated, do not use, see [#cargo_build_script] instead.LabeloptionalNone
proc_macro_depsList of rust_library targets with kind proc-macro 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_flagsList of compiler flags passed to rustc.List of stringsoptional[]
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[]
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.LabeloptionalNone
clang_flagsFlags to pass directly to the clang executable.List of stringsoptional[]
headerThe .h file to generate bindings for.LabeloptionalNone

rust_bindgen_toolchain

The tools required for the rust_bindgen rule.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
bindgenThe label of a bindgen executable.LabeloptionalNone
clangThe label of a clang executable.LabeloptionalNone
libclangA cc_library that provides bindgen's runtime dependency on libclang.LabeloptionalNone
libstdcxxA cc_library that satisfies libclang's libstdc++ dependency.LabeloptionalNone
rustfmtThe label of a rustfmt executable. If this is provided, generated sources will be formatted.LabeloptionalNone

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:rust.bzl", "rust_library", "rust_doc")

rust_library(
    name = "hello_lib",
    srcs = ["src/lib.rs"],
)

rust_doc(
    name = "hello_lib_doc",
    dep = ":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
depThe 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[]

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:rust.bzl", "rust_library", "rust_doc_test")

rust_library(
    name = "hello_lib",
    srcs = ["src/lib.rs"],
)

rust_doc_test(
    name = "hello_lib_doc_test",
    dep = ":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
depThe label of the target to run documentation tests for.

rust_doc_test can run documentation tests 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("//proto:proto.bzl", "rust_grpc_library")
load("//proto:toolchain.bzl", "GRPC_COMPILE_DEPS")

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"] + GRPC_COMPILE_DEPS,
)

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
rust_depsThe crates the generated library depends on.List of labelsoptional[Label(“//proto/raze:protobuf”), Label(“//proto/raze:grpc”), Label(“//proto/raze:tls_api”), Label(“//proto/raze:tls_api_stub”)]

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:rust.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
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{}
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_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_typeThe type of linkage to use for building this library. Options include “lib”, “rlib”, “dylib”, “cdylib”, “staticlib”, and “proc-macro”.

The exact output file will depend on the toolchain used.
Stringoptional“rlib”
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[]
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[]
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
out_dir_tarDeprecated, do not use, see [#cargo_build_script] instead.LabeloptionalNone
proc_macro_depsList of rust_library targets with kind proc-macro 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_flagsList of compiler flags passed to rustc.List of stringsoptional[]
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[]
versionA version to inject in the cargo environment variable.Stringoptional“0.0.0”

rust_proto_library

Builds a Rust library crate from a set of proto_librarys.

Example:

load("@rules_rust//proto:proto.bzl", "rust_proto_library")
load("@rules_rust//proto:toolchain.bzl", "PROTO_COMPILE_DEPS")

proto_library(
    name = "my_proto",
    srcs = ["my.proto"]
)

proto_rust_library(
    name = "rust",
    deps = [":my_proto"],
)

rust_binary(
    name = "my_proto_binary",
    srcs = ["my_proto_binary.rs"],
    deps = [":rust"] + PROTO_COMPILE_DEPS,
)

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
rust_depsThe crates the generated library depends on.List of labelsoptional[Label(“//proto/raze:protobuf”)]

rust_proto_toolchain

Declares a Rust Proto toolchain for use.

This is used to configure proto compilation and can be used to set different protobuf compiler plugin.

Example:

Suppose a new nicer gRPC plugin has came out. The new plugin can be used in Bazel by defining a new toolchain definition and declaration:

load('@rules_rust//proto:toolchain.bzl', 'rust_proto_toolchain')

rust_proto_toolchain(
   name="rust_proto_impl",
   grpc_plugin="@rust_grpc//:grpc_plugin",
   grpc_compile_deps=["@rust_grpc//:grpc_deps"],
)

toolchain(
    name="rust_proto",
    exec_compatible_with = [
        "@platforms//cpu:cpuX",
    ],
    target_compatible_with = [
        "@platforms//cpu:cpuX",
    ],
    toolchain = ":rust_proto_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//proto:BUILD for examples of defining the toolchain.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
editionThe edition used by the generated rust source.Stringoptional“2015”
grpc_pluginThe location of the Rust protobuf compiler plugin to generate rust gRPC stubs.Labeloptional//proto:protoc_gen_rust_grpc
proto_pluginThe location of the Rust protobuf compiler plugin used to generate rust sources.Labeloptional//proto:protoc_gen_rust
protocThe location of the protoc binary. It should be an executable target.Labeloptional@com_google_protobuf//:protoc

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) {
        println!("{} {}", &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:

hello_lib/BUILD:

package(default_visibility = ["//visibility:public"])

load("@rules_rust//rust:rust.bzl", "rust_library", "rust_test")

rust_library(
    name = "hello_lib",
    srcs = ["src/lib.rs"],
)

rust_test(
    name = "hello_lib_test",
    deps = [":hello_lib"],
)

Run the test with bazel build //hello_lib:hello_lib_test.

To run a crate or lib with the #[cfg(test)] configuration, handling inline tests, you should specify the crate directly like so.

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"],
)

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:

package(default_visibility = ["//visibility:public"])

load("@rules_rust//rust:rust.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 build //hello_lib:hello_lib_test.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
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{}
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_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
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[]
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[]
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
out_dir_tarDeprecated, do not use, see [#cargo_build_script] instead.LabeloptionalNone
proc_macro_depsList of rust_library targets with kind proc-macro 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_flagsList of compiler flags passed to rustc.List of stringsoptional[]
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[]
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",
    rustc = "@rust_cpuX//:rustc",
    rustc_lib = "@rust_cpuX//:rustc_lib",
    rust_lib = "@rust_cpuX//:rust_lib",
    rust_doc = "@rust_cpuX//:rustdoc",
    binary_ext = "",
    staticlib_ext = ".a",
    dylib_ext = ".so",
    stdlib_linkflags = ["-lpthread", "-ldl"],
    os = "linux",
)

toolchain(
    name = "rust_cpuX",
    exec_compatible_with = [
        "@platforms//cpu:cpuX",
    ],
    target_compatible_with = [
        "@platforms//cpu:cpuX",
    ],
    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
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
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.Stringoptional“2015”
dylib_extThe extension for dynamic libraries created from rustc.Stringrequired
exec_tripleThe platform triple for the toolchains execution environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurationsStringoptional""
opt_levelRustc optimization levels.Dictionary: String -> Stringoptional{“dbg”: “0”, “fastbuild”: “0”, “opt”: “3”}
osThe operating system for the current toolchainStringrequired
rust_docThe location of the rustdoc binary. Can be a direct source or a filegroup containing one item.LabeloptionalNone
rust_libThe rust standard library.LabeloptionalNone
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.LabeloptionalNone
staticlib_extThe extension for static libraries created from rustc.Stringrequired
stdlib_linkflagsAdditional linker libs used when std lib is linked, see https://github.com/rust-lang/rust/blob/master/src/libstd/build.rsList of stringsrequired
target_tripleThe platform triple for the toolchains target environment. For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurationsStringoptional""

rust_toolchain_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 rust_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
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.Stringoptional“2015”
exec_tripleThe Rust-style target that this compiler runs onStringrequired
extra_target_triplesAdditional rust-style targets that this set of toolchains should support.List of stringsoptional[]
iso_dateThe date of the tool (or None, if the version is a specific version).Stringoptional""
repo_mappingA dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.<p>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).Dictionary: String -> Stringrequired
rustfmt_versionThe version of the tool among “nightly”, “beta”, or an exact version.Stringoptional""
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_repositories for more details.Dictionary: String -> Stringoptional{}
toolchain_name_prefixThe per-target prefix expected for the rust_toolchain declarations in the parent workspace.Stringoptional""
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.gz”]
versionThe version of the tool among “nightly”, “beta”, or an exact version.Stringrequired

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_tripleThe Rust-style target triple for the compilation platformStringrequired
extra_target_triplesThe Rust-style triples for extra compilation targetsList of stringsoptional[]
parent_workspace_nameThe name of the other rust_toolchain_repositoryStringrequired
repo_mappingA dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.<p>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).Dictionary: String -> Stringrequired
toolchain_name_prefixThe per-target prefix expected for the rust_toolchain declarations in the parent workspace.Stringoptional""

rust_wasm_bindgen

Generates javascript and typescript bindings for a webassembly module.

To use the Rust WebAssembly bindgen rules, add the following to your WORKSPACE file to add the external repositories for the Rust bindgen toolchain (in addition to the Rust rules setup):

load("@rules_rust//wasm_bindgen:repositories.bzl", "rust_wasm_bindgen_repositories")

rust_wasm_bindgen_repositories()

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[]
wasm_fileThe .wasm file to generate bindings for.LabeloptionalNone

rust_wasm_bindgen_toolchain

The tools required for the rust_wasm_bindgen rule.

You can also use your own version of wasm-bindgen using the toolchain rules below:

load("@rules_rust//bindgen:bindgen.bzl", "rust_bindgen_toolchain")

rust_bindgen_toolchain(
    bindgen = "//my/raze:cargo_bin_wasm_bindgen",
)

toolchain(
    name = "wasm-bindgen-toolchain",
    toolchain = "wasm-bindgen-toolchain-impl",
    toolchain_type = "@rules_rust//wasm_bindgen:wasm_bindgen_toolchain",
)

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 executable.LabeloptionalNone

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:rust.bzl", "rust_binary", "rust_library")
load("@rules_rust//cargo:cargo_build_script.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 target name for the underlying rulenone
crate_nameName of the crate associated with this build script target.""
crate_featuresA list of features to enable for the build script.[]
versionThe semantic version (semver) of the crate.None
depsThe dependencies of the crate defined by crate_name.[]
build_script_envEnvironment variables for build scripts.{}
dataFiles or tools needed by the build script.[]
linksName of the native library this crate links against.None
kwargsForwards to the underlying rust_binary rule.none

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
clang_flagsFlags to pass directly to the clang executable.None
kwargsArguments to forward to the underlying rust_library rule.none

rust_bindgen_repositories

Declare dependencies needed for bindgen.

rust_proto_repositories

Declare dependencies needed for proto compilation.

rust_repositories

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 sha256 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
versionThe version of Rust. Either “nightly”, “beta”, or an exact version. Defaults to a modern version.“1.49.0”
iso_dateThe date of the nightly or beta release (or None, if the version is a specific version).None
rustfmt_versionThe version of rustfmt. Either “nightly”, “beta”, or an exact version. Defaults to version if not specified.None
editionThe rust edition to be used by default (2015 (default) or 2018)None
dev_componentsWhether to download the rustc-dev components (defaults to False). Requires version to be “nightly”.False
sha256sA dict associating tool subdirectories to sha256 hashes. Defaults to None.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.gz’][“https://static.rust-lang.org/dist/{}.tar.gz”]

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.

N.B. A “proxy repository” is needed to allow for registering the toolchain (with constraints) without actually downloading the toolchain.

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 onnone
extra_target_triplesAdditional rust-style targets that this set of toolchains should support. Defaults to [].[]
iso_dateThe date of the tool. Defaults to None.None
rustfmt_versionThe version of rustfmt to be associated with the toolchain. Defaults to None.None
editionThe rust edition to be used by default (2015 (if None) or 2018).None
dev_componentsWhether to download the rustc-dev components. Requires version to be “nightly”. Defaults to False.False
sha256sA dict associating tool subdirectories to sha256 hashes. See rust_repositories 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.gz’][“https://static.rust-lang.org/dist/{}.tar.gz”]

rust_wasm_bindgen_repositories

Declare dependencies needed for wasm-bindgen.

This macro will load crate dependencies of wasm-bindgen that are generated using [cargo raze][raze] inside the rules_rust repository. This makes the default toolchain @rules_rust//wasm_bindgen:default_wasm_bindgen_toolchain available. For more information on wasm_bindgen toolchains, see rust_wasm_bindgen_toolchain.