fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
00d11769
patching
1# Copyright 2015 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Rust rule implementations""" 16 17load ( "@bazel_skylib//lib:paths.bzl" , "paths" ) 18load ( "//rust/private:common.bzl" , "COMMON_PROVIDERS" , "rust_common" ) 19load ( "//rust/private:providers.bzl" , "BuildInfo" ) 20load ( "//rust/private:rustc.bzl" , "rustc_compile_action" ) 21load ( 22"//rust/private:utils.bzl" , 23"can_build_metadata" , 24"compute_crate_name" , 25"crate_root_src" , 26"dedent" , 27"determine_lib_name" , 28"determine_output_hash" , 29"expand_dict_value_locations" , 30"find_toolchain" , 31"generate_output_diagnostics" , 32"get_edition" , 33"get_import_macro_deps" , 34"transform_deps" , 35"transform_sources" , 36) 37 38# TODO(marco): Separate each rule into its own file. 39 40def _assert_no_deprecated_attributes ( _ctx ): 41"""Forces a failure if any deprecated attributes were specified 42 43Args: 44_ctx (ctx): The current rule's context object 45""" 46 pass 47 48def _assert_correct_dep_mapping ( ctx ): 49"""Forces a failure if proc_macro_deps and deps are mixed inappropriately 50 51Args: 52ctx (ctx): The current rule's context object 53""" 54for dep in ctx . attr . deps : 55if rust_common . crate_info in dep : 56if dep [ rust_common . crate_info ]. type == "proc-macro" : 57fail ( 58"{} listed {} in its deps, but it is a proc-macro. It should instead be in the bazel property proc_macro_deps." . format ( 59ctx . label , 60dep . label , 61), 62) 63for dep in ctx . attr . proc_macro_deps : 64type = dep [ rust_common . crate_info ]. type 65if type != "proc-macro" : 66fail ( 67"{} listed {} in its proc_macro_deps, but it is not proc-macro, it is a {}. It should probably instead be listed in deps." . format ( 68ctx . label , 69dep . label , 70type , 71), 72) 73 74def _rust_library_impl ( ctx ): 75"""The implementation of the `rust_library` rule. 76 77This rule provides CcInfo, so it can be used everywhere Bazel 78expects rules_cc, but care must be taken to have the correct 79dependencies on an allocator and std implemetation as needed. 80 81Args: 82ctx (ctx): The rule's context object 83 84Returns: 85list: A list of providers. 86""" 87return _rust_library_common ( ctx , "rlib" ) 88 89def _rust_static_library_impl ( ctx ): 90"""The implementation of the `rust_static_library` rule. 91 92This rule provides CcInfo, so it can be used everywhere Bazel 93expects rules_cc. 94 95Args: 96ctx (ctx): The rule's context object 97 98Returns: 99list: A list of providers. 100""" 101return _rust_library_common ( ctx , "staticlib" ) 102 103def _rust_shared_library_impl ( ctx ): 104"""The implementation of the `rust_shared_library` rule. 105 106This rule provides CcInfo, so it can be used everywhere Bazel 107expects rules_cc. 108 109On Windows, a PDB file containing debugging information is available under 110the key `pdb_file` in `OutputGroupInfo`. Similarly on macOS, a dSYM folder 111is available under the key `dsym_folder` in `OutputGroupInfo`. 112 113Args: 114ctx (ctx): The rule's context object 115 116Returns: 117list: A list of providers. 118""" 119return _rust_library_common ( ctx , "cdylib" ) 120 121def _rust_proc_macro_impl ( ctx ): 122"""The implementation of the `rust_proc_macro` rule. 123 124Args: 125ctx (ctx): The rule's context object 126 127Returns: 128list: A list of providers. 129""" 130return _rust_library_common ( ctx , "proc-macro" ) 131 132def _rust_library_common ( ctx , crate_type ): 133"""The common implementation of the library-like rules. 134 135Args: 136ctx (ctx): The rule's context object 137crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro 138 139Returns: 140list: A list of providers. See `rustc_compile_action` 141""" 142_assert_no_deprecated_attributes ( ctx ) 143_assert_correct_dep_mapping ( ctx ) 144 145toolchain = find_toolchain ( ctx ) 146 147crate_name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ) 148 149crate_root = getattr ( ctx . file , "crate_root" , None ) 150if not crate_root : 151crate_root = crate_root_src ( ctx . attr . name , ctx . files . srcs , crate_type ) 152srcs , crate_root = transform_sources ( ctx , ctx . files . srcs , crate_root ) 153 154# Determine unique hash for this rlib. 155# Note that we don't include a hash for `cdylib` and `staticlib` since they are meant to be consumed externally 156# and having a deterministic name is important since it ends up embedded in the executable. This is problematic 157# when one needs to include the library with a specific filename into a larger application. 158# (see https://github.com/bazelbuild/rules_rust/issues/405#issuecomment-993089889 for more details) 159if crate_type in [ "cdylib" , "staticlib" ]: 160output_hash = None 161else : 162output_hash = determine_output_hash ( crate_root , ctx . label ) 163 164rust_lib_name = determine_lib_name ( 165crate_name , 166crate_type , 167toolchain , 168output_hash , 169) 170rust_lib = ctx . actions . declare_file ( rust_lib_name ) 171rust_metadata = None 172rustc_rmeta_output = None 173if can_build_metadata ( toolchain , ctx , crate_type ) and not ctx . attr . disable_pipelining : 174rust_metadata = ctx . actions . declare_file ( 175paths . replace_extension ( rust_lib_name , ".rmeta" ), 176sibling = rust_lib , 177) 178rustc_rmeta_output = generate_output_diagnostics ( ctx , rust_metadata ) 179 180deps = transform_deps ( ctx . attr . deps ) 181proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 182 183return rustc_compile_action ( 184ctx = ctx , 185attr = ctx . attr , 186toolchain = toolchain , 187output_hash = output_hash , 188crate_info_dict = dict ( 189name = crate_name , 190type = crate_type , 191root = crate_root , 192srcs = depset ( srcs ), 193deps = depset ( deps ), 194proc_macro_deps = depset ( proc_macro_deps ), 195aliases = ctx . attr . aliases , 196output = rust_lib , 197rustc_output = generate_output_diagnostics ( ctx , rust_lib ), 198metadata = rust_metadata , 199rustc_rmeta_output = rustc_rmeta_output , 200edition = get_edition ( ctx . attr , toolchain , ctx . label ), 201rustc_env = ctx . attr . rustc_env , 202rustc_env_files = ctx . files . rustc_env_files , 203is_test = False , 204data = depset ( ctx . files . data ), 205compile_data = depset ( ctx . files . compile_data ), 206compile_data_targets = depset ( ctx . attr . compile_data ), 207owner = ctx . label , 208), 209) 210 211def _rust_binary_impl ( ctx ): 212"""The implementation of the `rust_binary` rule 213 214Args: 215ctx (ctx): The rule's context object 216 217Returns: 218list: A list of providers. See `rustc_compile_action` 219""" 220toolchain = find_toolchain ( ctx ) 221crate_name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ) 222_assert_correct_dep_mapping ( ctx ) 223 224output = ctx . actions . declare_file ( ctx . label . name + toolchain . binary_ext ) 225 226deps = transform_deps ( ctx . attr . deps ) 227proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 228 229crate_root = getattr ( ctx . file , "crate_root" , None ) 230if not crate_root : 231crate_root = crate_root_src ( ctx . attr . name , ctx . files . srcs , ctx . attr . crate_type ) 232srcs , crate_root = transform_sources ( ctx , ctx . files . srcs , crate_root ) 233 234providers = rustc_compile_action ( 235ctx = ctx , 236attr = ctx . attr , 237toolchain = toolchain , 238crate_info_dict = dict ( 239name = crate_name , 240type = ctx . attr . crate_type , 241root = crate_root , 242srcs = depset ( srcs ), 243deps = depset ( deps ), 244proc_macro_deps = depset ( proc_macro_deps ), 245aliases = ctx . attr . aliases , 246output = output , 247rustc_output = generate_output_diagnostics ( ctx , output ), 248edition = get_edition ( ctx . attr , toolchain , ctx . label ), 249rustc_env = ctx . attr . rustc_env , 250rustc_env_files = ctx . files . rustc_env_files , 251is_test = False , 252data = depset ( ctx . files . data ), 253compile_data = depset ( ctx . files . compile_data ), 254compile_data_targets = depset ( ctx . attr . compile_data ), 255owner = ctx . label , 256), 257) 258 259providers . append ( RunEnvironmentInfo ( 260environment = expand_dict_value_locations ( 261ctx , 262ctx . attr . env , 263ctx . attr . data , 264), 265)) 266 267return providers 268 269def get_rust_test_flags ( attr ): 270"""Determine the desired rustc flags for test targets. 271 272Args: 273attr (dict): Attributes of a rule 274 275Returns: 276List: A list of test flags 277""" 278if getattr ( attr , "use_libtest_harness" , True ): 279rust_flags = [ "--test" ] 280else : 281rust_flags = [ "--cfg" , "test" ] 282 283return rust_flags 284 285def _rust_test_impl ( ctx ): 286"""The implementation of the `rust_test` rule. 287 288Args: 289ctx (ctx): The ctx object for the current target. 290 291Returns: 292list: The list of providers. See `rustc_compile_action` 293""" 294_assert_no_deprecated_attributes ( ctx ) 295_assert_correct_dep_mapping ( ctx ) 296 297toolchain = find_toolchain ( ctx ) 298 299crate_type = "bin" 300deps = transform_deps ( ctx . attr . deps ) 301proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 302 303if ctx . attr . crate and ctx . attr . srcs : 304fail ( "rust_test.crate and rust_test.srcs are mutually exclusive. Update {} to use only one of these attributes" . format ( 305ctx . label , 306)) 307 308if ctx . attr . crate : 309# Target is building the crate in `test` config 310crate = ctx . attr . crate [ rust_common . crate_info ] if rust_common . crate_info in ctx . attr . crate else ctx . attr . crate [ rust_common . test_crate_info ]. crate 311 312output_hash = determine_output_hash ( crate . root , ctx . label ) 313output = ctx . actions . declare_file ( 314"test-%s/%s%s" % ( 315output_hash , 316ctx . label . name , 317toolchain . binary_ext , 318), 319) 320 321srcs , crate_root = transform_sources ( ctx , ctx . files . srcs , getattr ( ctx . file , "crate_root" , None )) 322 323# Optionally join compile data 324if crate . compile_data : 325compile_data = depset ( ctx . files . compile_data , transitive = [ crate . compile_data ]) 326else : 327compile_data = depset ( ctx . files . compile_data ) 328if crate . compile_data_targets : 329compile_data_targets = depset ( ctx . attr . compile_data , transitive = [ crate . compile_data_targets ]) 330else : 331compile_data_targets = depset ( ctx . attr . compile_data ) 332rustc_env_files = ctx . files . rustc_env_files + crate . rustc_env_files 333 334# crate.rustc_env is already expanded upstream in rust_library rule implementation 335rustc_env = dict ( crate . rustc_env ) 336data_paths = depset ( direct = getattr ( ctx . attr , "data" , [])). to_list () 337rustc_env . update ( expand_dict_value_locations ( 338ctx , 339ctx . attr . rustc_env , 340data_paths , 341)) 342 343# Build the test binary using the dependency's srcs. 344crate_info_dict = dict ( 345name = crate . name , 346type = crate_type , 347root = crate . root , 348srcs = depset ( srcs , transitive = [ crate . srcs ]), 349deps = depset ( deps , transitive = [ crate . deps ]), 350proc_macro_deps = depset ( proc_macro_deps , transitive = [ crate . proc_macro_deps ]), 351aliases = ctx . attr . aliases , 352output = output , 353rustc_output = generate_output_diagnostics ( ctx , output ), 354edition = crate . edition , 355rustc_env = rustc_env , 356rustc_env_files = rustc_env_files , 357is_test = True , 358compile_data = compile_data , 359compile_data_targets = compile_data_targets , 360wrapped_crate_type = crate . type , 361owner = ctx . label , 362) 363else : 364crate_root = getattr ( ctx . file , "crate_root" , None ) 365 366if not crate_root : 367crate_root_type = "lib" if ctx . attr . use_libtest_harness else "bin" 368crate_root = crate_root_src ( ctx . attr . name , ctx . files . srcs , crate_root_type ) 369srcs , crate_root = transform_sources ( ctx , ctx . files . srcs , crate_root ) 370 371output_hash = determine_output_hash ( crate_root , ctx . label ) 372output = ctx . actions . declare_file ( 373"test-%s/%s%s" % ( 374output_hash , 375ctx . label . name , 376toolchain . binary_ext , 377), 378) 379 380data_paths = depset ( direct = getattr ( ctx . attr , "data" , [])). to_list () 381rustc_env = expand_dict_value_locations ( 382ctx , 383ctx . attr . rustc_env , 384data_paths , 385) 386 387# Target is a standalone crate. Build the test binary as its own crate. 388crate_info_dict = dict ( 389name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ), 390type = crate_type , 391root = crate_root , 392srcs = depset ( srcs ), 393deps = depset ( deps ), 394proc_macro_deps = depset ( proc_macro_deps ), 395aliases = ctx . attr . aliases , 396output = output , 397rustc_output = generate_output_diagnostics ( ctx , output ), 398edition = get_edition ( ctx . attr , toolchain , ctx . label ), 399rustc_env = rustc_env , 400rustc_env_files = ctx . files . rustc_env_files , 401is_test = True , 402compile_data = depset ( ctx . files . compile_data ), 403compile_data_targets = depset ( ctx . attr . compile_data ), 404owner = ctx . label , 405) 406 407providers = rustc_compile_action ( 408ctx = ctx , 409attr = ctx . attr , 410toolchain = toolchain , 411crate_info_dict = crate_info_dict , 412rust_flags = get_rust_test_flags ( ctx . attr ), 413skip_expanding_rustc_env = True , 414) 415data = getattr ( ctx . attr , "data" , []) 416 417env = expand_dict_value_locations ( 418ctx , 419getattr ( ctx . attr , "env" , {}), 420data , 421) 422if toolchain . llvm_cov and ctx . configuration . coverage_enabled : 423if not toolchain . llvm_profdata : 424fail ( "toolchain.llvm_profdata is required if toolchain.llvm_cov is set." ) 425 426if toolchain . _experimental_use_coverage_metadata_files : 427llvm_cov_path = toolchain . llvm_cov . path 428llvm_profdata_path = toolchain . llvm_profdata . path 429else : 430llvm_cov_path = toolchain . llvm_cov . short_path 431if llvm_cov_path . startswith ( "../" ): 432llvm_cov_path = llvm_cov_path [ len ( "../" ):] 433 434llvm_profdata_path = toolchain . llvm_profdata . short_path 435if llvm_profdata_path . startswith ( "../" ): 436llvm_profdata_path = llvm_profdata_path [ len ( "../" ):] 437 438env [ "RUST_LLVM_COV" ] = llvm_cov_path 439env [ "RUST_LLVM_PROFDATA" ] = llvm_profdata_path 440components = "{}/{}" . format ( ctx . label . workspace_root , ctx . label . package ). split ( "/" ) 441env [ "CARGO_MANIFEST_DIR" ] = "/" . join ([ c for c in components if c ]) 442providers . append ( testing . TestEnvironment ( env )) 443 444return providers 445 446def _rust_library_group_impl ( ctx ): 447dep_variant_infos = [] 448dep_variant_transitive_infos = [] 449runfiles = [] 450 451for dep in ctx . attr . deps : 452if rust_common . crate_info in dep : 453dep_variant_infos . append ( rust_common . dep_variant_info ( 454crate_info = dep [ rust_common . crate_info ] if rust_common . crate_info in dep else None , 455dep_info = dep [ rust_common . dep_info ] if rust_common . crate_info in dep else None , 456build_info = dep [ BuildInfo ] if BuildInfo in dep else None , 457cc_info = dep [ CcInfo ] if CcInfo in dep else None , 458crate_group_info = None , 459)) 460elif rust_common . crate_group_info in dep : 461dep_variant_transitive_infos . append ( dep [ rust_common . crate_group_info ]. dep_variant_infos ) 462else : 463fail ( "crate_group_info targets can only depend on rust_library or rust_library_group targets." ) 464 465if dep [ DefaultInfo ]. default_runfiles != None : 466runfiles . append ( dep [ DefaultInfo ]. default_runfiles ) 467 468return [ 469rust_common . crate_group_info ( 470dep_variant_infos = depset ( dep_variant_infos , transitive = dep_variant_transitive_infos ), 471), 472DefaultInfo ( runfiles = ctx . runfiles (). merge_all ( runfiles )), 473coverage_common . instrumented_files_info ( 474ctx , 475dependency_attributes = [ "deps" ], 476), 477] 478 479def _stamp_attribute ( default_value ): 480return attr . int ( 481doc = dedent ( """\ 482Whether to encode build information into the `Rustc` action. Possible values: 483 484- `stamp = 1`: Always stamp the build information into the `Rustc` action, even in \ 485[--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. \ 486This setting should be avoided, since it potentially kills remote caching for the target and \ 487any downstream actions that depend on it. 488 489- `stamp = 0`: Always replace build information by constant values. This gives good build result caching. 490 491- `stamp = -1`: Embedding of build information is controlled by the \ 492[--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag. 493 494Stamped targets are not rebuilt unless their dependencies change. 495 496For example if a `rust_library` is stamped, and a `rust_binary` depends on that library, the stamped 497library won't be rebuilt when we change sources of the `rust_binary`. This is different from how 498[`cc_library.linkstamps`](https://docs.bazel.build/versions/main/be/c-cpp.html#cc_library.linkstamp) 499behaves. 500""" ), 501default = default_value , 502values = [ 1 , 0 , - 1 ], 503) 504 505# Internal attributes core to Rustc actions. 506RUSTC_ATTRS = { 507"_cc_toolchain" : attr . label ( 508doc = ( 509"In order to use find_cc_toolchain, your rule has to depend " + 510"on C++ toolchain. See `@rules_cc//cc:find_cc_toolchain.bzl` " + 511"docs for details." 512), 513default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 514), 515"_error_format" : attr . label ( 516default = Label ( "//:error_format" ), 517), 518"_extra_exec_rustc_flag" : attr . label ( 519default = Label ( "//:extra_exec_rustc_flag" ), 520), 521"_extra_exec_rustc_flags" : attr . label ( 522default = Label ( "//:extra_exec_rustc_flags" ), 523), 524"_extra_rustc_flag" : attr . label ( 525default = Label ( "//:extra_rustc_flag" ), 526), 527"_extra_rustc_flags" : attr . label ( 528default = Label ( "//:extra_rustc_flags" ), 529), 530"_is_proc_macro_dep" : attr . label ( 531default = Label ( "//rust/private:is_proc_macro_dep" ), 532), 533"_is_proc_macro_dep_enabled" : attr . label ( 534default = Label ( "//rust/private:is_proc_macro_dep_enabled" ), 535), 536"_per_crate_rustc_flag" : attr . label ( 537default = Label ( "//:experimental_per_crate_rustc_flag" ), 538), 539"_process_wrapper" : attr . label ( 540doc = "A process wrapper for running rustc on all platforms." , 541default = Label ( "//util/process_wrapper" ), 542executable = True , 543allow_single_file = True , 544cfg = "exec" , 545), 546"_rustc_output_diagnostics" : attr . label ( 547default = Label ( "//:rustc_output_diagnostics" ), 548), 549} 550 551_common_attrs = { 552"aliases" : attr . label_keyed_string_dict ( 553doc = dedent ( """\ 554Remap crates to a new name or moniker for linkage to this target 555 556These are other `rust_library` targets and will be presented as the new name given. 557""" ), 558), 559"alwayslink" : attr . bool ( 560doc = dedent ( """\ 561If 1, any binary that depends (directly or indirectly) on this library 562will link in all the object files even if some contain no symbols referenced by the binary. 563 564This attribute is used by the C++ Starlark API when passing CcInfo providers. 565""" ), 566default = False , 567), 568"compile_data" : attr . label_list ( 569doc = dedent ( """\ 570List of files used by this rule at compile time. 571 572This attribute can be used to specify any data files that are embedded into 573the library, such as via the 574[`include_str!`](https://doc.rust-lang.org/std/macro.include_str!.html) 575macro. 576""" ), 577allow_files = True , 578), 579"crate_features" : attr . string_list ( 580doc = dedent ( """\ 581List of features to enable for this crate. 582 583Features are defined in the code using the `#[cfg(feature = "foo")]` 584configuration option. The features listed here will be passed to `rustc` 585with `--cfg feature="${feature_name}"` flags. 586""" ), 587), 588"crate_name" : attr . string ( 589doc = dedent ( """\ 590Crate name to use for this target. 591 592This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. 593Defaults to the target name, with any hyphens replaced by underscores. 594""" ), 595), 596"crate_root" : attr . label ( 597doc = dedent ( """\ 598The file that will be passed to `rustc` to be used for building this crate. 599 600If `crate_root` is not set, then this rule will look for a `lib.rs` file (or `main.rs` for rust_binary) 601or the single file in `srcs` if `srcs` contains only one file. 602""" ), 603allow_single_file = [ ".rs" ], 604), 605"data" : attr . label_list ( 606doc = dedent ( """\ 607List of files used by this rule at compile time and runtime. 608 609If including data at compile time with include_str!() and similar, 610prefer `compile_data` over `data`, to prevent the data also being included 611in the runfiles. 612""" ), 613allow_files = True , 614), 615"deps" : attr . label_list ( 616doc = dedent ( """\ 617List of other libraries to be linked to this library target. 618 619These can be either other `rust_library` targets or `cc_library` targets if 620linking a native library. 621""" ), 622), 623"edition" : attr . string ( 624doc = "The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain." , 625), 626# Previously `proc_macro_deps` were a part of `deps`, and then proc_macro_host_transition was 627# used into cfg="host" using `@local_config_platform//:host`. 628# This fails for remote execution, which needs cfg="exec", and there isn't anything like 629# `@local_config_platform//:exec` exposed. 630"proc_macro_deps" : attr . label_list ( 631doc = dedent ( """\ 632List of `rust_proc_macro` targets used to help build this library target. 633""" ), 634cfg = "exec" , 635providers = [ rust_common . crate_info ], 636), 637"rustc_env" : attr . string_dict ( 638doc = dedent ( """\ 639Dictionary of additional `"key": "value"` environment variables to set for rustc. 640 641rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the 642location of a generated file or external tool. Cargo build scripts that wish to 643expand locations should use cargo_build_script()'s build_script_env argument instead, 644as build scripts are run in a different environment - see cargo_build_script()'s 645documentation for more. 646""" ), 647), 648"rustc_env_files" : attr . label_list ( 649doc = dedent ( """\ 650 Files containing additional environment variables to set for rustc. 651 652 These files should contain a single variable per line, of format 653 `NAME=value`, and newlines may be included in a value by ending a 654 line with a trailing back-slash (`\\\\`). 655 656The order that these files will be processed is unspecified , so 657multiple definitions of a particular variable are discouraged . 658 659Note that the variables here are subject to 660[ workspace status ]( https : // docs . bazel . build / versions / main / user - manual . html #workspace_status) 661stamping should the `stamp` attribute be enabled . Stamp variables 662should be wrapped in brackets in order to be resolved . E . g . 663`NAME={WORKSPACE_STATUS_VARIABLE}` . 664"""), 665allow_files = True, 666), 667"rustc_flags": attr.string_list( 668doc = dedent(""" \ 669List of compiler flags passed to `rustc` . 670 671These strings are subject to Make variable expansion for predefined 672source / output path variables like `$location` , `$execpath` , and 673`$rootpath` . This expansion is useful if you wish to passa generated 674file of arguments to rustc : `@$(location //package:target)` . 675"""), 676), 677# TODO(stardoc): How do we provide additional documentation to an inherited attribute? 678# "name": attr.string( 679# doc = "This name will also be used as the name of the crate built by this rule.", 680# `), 681"srcs": attr.label_list( 682doc = dedent(""" \ 683List of Rust `.rs` source files used to build the library . 684 685If `srcs` contains more than one file , then there must be a file either 686named `lib.rs` . Otherwise , `crate_root` must be set to the source file that 687is the root of the crate to be passed to rustc to build this crate . 688"""), 689allow_files = [".rs"], 690# Allow use of --compile_one_dependency with rust targets. Support for this feature for 691# non-builtin rulesets is undocumented outside of the bazel source: 692# https://github.com/bazelbuild/bazel/blob/7.1.1/src/main/java/com/google/devtools/build/lib/packages/Attribute.java#L102 693flags = ["DIRECT_COMPILE_TIME_INPUT"], 694), 695"stamp": _stamp_attribute( 696default_value = 0, 697), 698"version": attr.string( 699doc = "A version to inject in the cargo environment variable.", 700default = "0.0.0", 701), 702"_stamp_flag": attr.label( 703doc = "A setting used to determine whether or not the `--stamp` flag is enabled", 704default = Label("//rust/private:stamp"), 705), 706} | RUSTC_ATTRS 707 708_coverage_attrs = { 709"_collect_cc_coverage": attr.label( 710default = Label("//util/collect_coverage"), 711executable = True, 712cfg = "exec", 713), 714# Bazel’s coverage runner 715# (https://github.com/bazelbuild/bazel/blob/6.0.0/tools/test/collect_coverage.sh) 716# needs a binary called “lcov_merge.” Its location is passed in the 717# LCOV_MERGER environmental variable. For builtin rules, this variable 718# is set automatically based on a magic “$lcov_merger” or 719# “:lcov_merger” attribute, but it’s not possible to create such 720# attributes in Starlark. Therefore we specify the variable ourselves. 721# Note that the coverage runner runs in the runfiles root instead of 722# the execution root, therefore we use “path” instead of “short_path.” 723"_lcov_merger": attr.label( 724default = configuration_field(fragment = "coverage", name = "output_generator"), 725executable = True, 726cfg = "exec", 727), 728} 729 730_experimental_use_cc_common_link_attrs = { 731"experimental_use_cc_common_link": attr.int( 732doc = ( 733"Whether to use cc_common.link to link rust binaries. " + 734"Possible values: [-1, 0, 1]. " + 735"-1 means use the value of the toolchain.experimental_use_cc_common_link " + 736"boolean build setting to determine. " + 737"0 means do not use cc_common.link (use rustc instead). " + 738"1 means use cc_common.link." 739), 740values = [-1, 0, 1], 741default = -1, 742), 743"malloc": attr.label( 744default = Label("@bazel_tools//tools/cpp:malloc"), 745doc = """ Override the default dependency on `malloc` . 746 747By default , Rust binaries linked with cc_common . link are linked against 748`@bazel_tools//tools/cpp:malloc"` , which is an empty library and the resulting binary will use 749libc 's `malloc` . This label must refer to a `cc_library` rule . 750""", 751mandatory = False, 752providers = [[CcInfo]], 753), # A late-bound attribute denoting the value of the `--custom_malloc` 754# command line flag (or None if the flag is not provided). 755"_custom_malloc": attr.label( 756default = configuration_field( 757fragment = "cpp", 758name = "custom_malloc", 759), 760providers = [[CcInfo]], 761), 762} 763 764_rust_test_attrs = dict({ 765"crate": attr.label( 766mandatory = False, 767doc = dedent(""" \ 768Target inline tests declared in the given crate 769 770These tests are typically those that would be held out under 771 `#[cfg(test)]` declarations. 772"""), 773), 774"env": attr.string_dict( 775mandatory = False, 776doc = dedent(""" \ 777Specifies additional environment variables to set when the test is executed by bazel test . 778Values are subject to `$(rootpath)` , `$(execpath)` , location , and 779[ "Make variable" ]( https : // docs . bazel . build / versions / master / be / make - variables . html ) substitution . 780"""), 781), 782"use_libtest_harness": attr.bool( 783mandatory = False, 784default = True, 785doc = dedent(""" \ 786Whether to use `libtest` . For targets using this flag , individual tests can be run by using the 787[ -- test_arg ]( https : // docs . bazel . build / versions / 4.0 . 0 / command - line - reference . html #flag--test_arg) flag. 788E . g . `bazel test //src:rust_test --test_arg=foo::test::test_fn` . 789"""), 790), 791"_use_grep_includes": attr.bool(default = True), 792}.items() + _coverage_attrs.items() + _experimental_use_cc_common_link_attrs.items()) 793 794rust_library = rule( 795implementation = _rust_library_impl, 796provides = COMMON_PROVIDERS, 797attrs = dict(_common_attrs.items() + { 798"disable_pipelining": attr.bool( 799default = False, 800doc = dedent(""" \ 801Disables pipelining for this rule if it is globally enabled . 802This will cause this rule to not produce a `.rmeta` file and all the dependent 803crates will instead use the `.rlib` file . 804"""), 805), 806}.items()), 807fragments = ["cpp"], 808toolchains = [ 809str(Label("//rust:toolchain_type")), 810"@bazel_tools//tools/cpp:toolchain_type", 811], 812doc = dedent(""" \ 813Builds a Rust library crate . 814 815Example : 816 817Suppose you have the following directory structure for a simple Rust library crate : 818 819`` `output 820[ workspace ] / 821WORKSPACE 822hello_lib / 823BUILD 824src / 825greeter . rs 826lib . rs 827`` ` 828 829`hello_lib/src/greeter.rs` : 830`` `rust 831pub struct Greeter { 832greeting : String , 833} 834 835impl Greeter { 836pub fn new ( greeting : & str ) -> Greeter { 837Greeter { greeting : greeting . to_string (), } 838} 839 840pub fn greet ( & self , thing : & str ) { 841println !( "{} {}" , & self . greeting , thing ) ; 842} 843} 844`` ` 845 846`hello_lib/src/lib.rs` : 847 848`` `rust 849pub mod greeter ; 850`` ` 851 852`hello_lib/BUILD` : 853`` `python 854package ( default_visibility = [ "//visibility:public" ]) 855 856load ( "@rules_rust//rust:defs.bzl" , "rust_library" ) 857 858rust_library ( 859name = "hello_lib" , 860srcs = [ 861"src/greeter.rs" , 862"src/lib.rs" , 863], 864) 865`` ` 866 867Build the library : 868`` `output 869 $bazel build // hello_lib 870INFO : Found 1 target ... 871Target // examples / rust / hello_lib : hello_lib up - to - date : 872bazel - bin / examples / rust / hello_lib / libhello_lib . rlib 873INFO : Elapsed time : 1.245 s , Critical Path : 1.01 s 874`` ` 875"""), 876) 877 878def _rust_static_library_transition_impl(settings, attr): 879return { 880"//command_line_option:platforms": str(attr.platform) if attr.platform else settings["//command_line_option:platforms"], 881} 882 883_rust_static_library_transition = transition( 884implementation = _rust_static_library_transition_impl, 885inputs = [ 886"//command_line_option:platforms", 887], 888outputs = [ 889"//command_line_option:platforms", 890], 891) 892 893rust_static_library = rule( 894implementation = _rust_static_library_impl, 895attrs = dict(_common_attrs.items() + { 896"platform": attr.label( 897doc = "Optional platform to transition the static library to.", 898default = None, 899), 900"_allowlist_function_transition": attr.label( 901default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 902), 903}.items()), 904fragments = ["cpp"], 905cfg = _rust_static_library_transition, 906toolchains = [ 907str(Label("//rust:toolchain_type")), 908"@bazel_tools//tools/cpp:toolchain_type", 909], 910provides = [CcInfo], 911doc = dedent(""" \ 912Builds a Rust static library . 913 914This static library will contain all transitively reachable crates and native objects . 915It is meant to be used when producing an artifact that is then consumed by some other build system 916( for example to produce an archive that Python program links against ). 917 918This rule provides CcInfo , so it can be used everywhere Bazel expects `rules_cc` . 919 920When building the whole binary in Bazel , use `rust_library` instead . 921"""), 922) 923 924def _rust_shared_library_transition_impl(settings, attr): 925return { 926"//command_line_option:platforms": str(attr.platform) if attr.platform else settings["//command_line_option:platforms"], 927} 928 929_rust_shared_library_transition = transition( 930implementation = _rust_shared_library_transition_impl, 931inputs = [ 932"//command_line_option:platforms", 933], 934outputs = [ 935"//command_line_option:platforms", 936], 937) 938 939rust_shared_library = rule( 940implementation = _rust_shared_library_impl, 941attrs = dict(_common_attrs.items() + _experimental_use_cc_common_link_attrs.items() + { 942"platform": attr.label( 943doc = "Optional platform to transition the shared library to.", 944default = None, 945), 946"_allowlist_function_transition": attr.label( 947default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 948), 949"_use_grep_includes": attr.bool(default = True), 950}.items()), 951fragments = ["cpp"], 952cfg = _rust_shared_library_transition, 953toolchains = [ 954str(Label("//rust:toolchain_type")), 955"@bazel_tools//tools/cpp:toolchain_type", 956], 957provides = [CcInfo], 958doc = dedent(""" \ 959Builds a Rust shared library . 960 961This shared library will contain all transitively reachable crates and native objects . 962It is meant to be used when producing an artifact that is then consumed by some other build system 963( for example to produce a shared library that Python program links against ). 964 965This rule provides CcInfo , so it can be used everywhere Bazel expects `rules_cc` . 966 967When building the whole binary in Bazel , use `rust_library` instead . 968"""), 969) 970 971def _proc_macro_dep_transition_impl(settings, _attr): 972if settings["//rust/private:is_proc_macro_dep_enabled"]: 973return {"//rust/private:is_proc_macro_dep": True} 974else: 975return [] 976 977_proc_macro_dep_transition = transition( 978inputs = ["//rust/private:is_proc_macro_dep_enabled"], 979outputs = ["//rust/private:is_proc_macro_dep"], 980implementation = _proc_macro_dep_transition_impl, 981) 982 983rust_proc_macro = rule( 984implementation = _rust_proc_macro_impl, 985provides = COMMON_PROVIDERS, 986# Start by copying the common attributes, then override the `deps` attribute 987# to apply `_proc_macro_dep_transition`. To add this transition we additionally 988# need to declare `_allowlist_function_transition`, see 989# https://docs.bazel.build/versions/main/skylark/config.html#user-defined-transitions. 990attrs = dict( 991_common_attrs.items(), 992_allowlist_function_transition = attr.label( 993default = Label("//tools/allowlists/function_transition_allowlist"), 994), 995deps = attr.label_list( 996doc = dedent(""" \ 997List of other libraries to be linked to this library target . 998 999These can be either other `rust_library` targets or `cc_library` targets if 1000linking a native library . 1001"""), 1002cfg = _proc_macro_dep_transition, 1003), 1004), 1005fragments = ["cpp"], 1006toolchains = [ 1007str(Label("//rust:toolchain_type")), 1008"@bazel_tools//tools/cpp:toolchain_type", 1009], 1010doc = dedent(""" \ 1011Builds a Rust proc - macro crate . 1012"""), 1013) 1014 1015_rust_binary_attrs = dict({ 1016"crate_type": attr.string( 1017doc = dedent(""" \ 1018Crate type that will be passed to `rustc` to be used for building this crate . 1019 1020This option is a temporary workaround and should be used only when building 1021for WebAssembly targets ( // rust / platform : wasi and // rust / platform : wasm ). 1022"""), 1023default = "bin", 1024), 1025"env": attr.string_dict( 1026mandatory = False, 1027doc = dedent(""" \ 1028Specifies additional environment variables to set when the target is executed by bazel run . 1029Values are subject to `$(rootpath)` , `$(execpath)` , location , and 1030[ "Make variable" ]( https : // docs . bazel . build / versions / master / be / make - variables . html ) substitution . 1031 1032Execpath returns absolute path , and in order to be able to construct the absolute path we 1033need to wrap the test binary in a launcher . Using a launcher comes with complications , such as 1034more complicated debugger attachment . 1035"""), 1036), 1037"linker_script": attr.label( 1038doc = dedent(""" \ 1039Link script to forward into linker via rustc options . 1040"""), 1041allow_single_file = True, 1042), 1043"out_binary": attr.bool( 1044doc = ( 1045"Force a target, regardless of it's `crate_type`, to always mark the " + 1046"file as executable. This attribute is only used to support wasm targets but is " + 1047"expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771." 1048), 1049default = False, 1050), 1051"stamp": _stamp_attribute(default_value = -1), 1052"_use_grep_includes": attr.bool(default = True), 1053}.items() + _experimental_use_cc_common_link_attrs.items()) 1054 1055def _rust_binary_transition_impl(settings, attr): 1056return { 1057"//command_line_option:platforms": str(attr.platform) if attr.platform else settings["//command_line_option:platforms"], 1058} 1059 1060_rust_binary_transition = transition( 1061implementation = _rust_binary_transition_impl, 1062inputs = [ 1063"//command_line_option:platforms", 1064], 1065outputs = [ 1066"//command_line_option:platforms", 1067], 1068) 1069 1070rust_binary = rule( 1071implementation = _rust_binary_impl, 1072provides = COMMON_PROVIDERS, 1073attrs = dict(_common_attrs.items() + _rust_binary_attrs.items() + { 1074"platform": attr.label( 1075doc = "Optional platform to transition the binary to.", 1076default = None, 1077), 1078"_allowlist_function_transition": attr.label( 1079default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 1080), 1081}.items()), 1082executable = True, 1083fragments = ["cpp"], 1084cfg = _rust_binary_transition, 1085toolchains = [ 1086str(Label("//rust:toolchain_type")), 1087"@bazel_tools//tools/cpp:toolchain_type", 1088], 1089doc = dedent(""" \ 1090Builds a Rust binary crate . 1091 1092Example : 1093 1094Suppose you have the following directory structure for a Rust project with a 1095library crate , `hello_lib` , and a binary crate , `hello_world` that uses the 1096`hello_lib` library : 1097 1098`` `output 1099[ workspace ] / 1100WORKSPACE 1101hello_lib / 1102BUILD 1103src / 1104lib . rs 1105hello_world / 1106BUILD 1107src / 1108main . rs 1109`` ` 1110 1111`hello_lib/src/lib.rs` : 1112`` `rust 1113pub struct Greeter { 1114greeting : String , 1115} 1116 1117impl Greeter { 1118pub fn new ( greeting : & str ) -> Greeter { 1119Greeter { greeting : greeting . to_string (), } 1120} 1121 1122pub fn greet ( & self , thing : & str ) { 1123println !( "{} {}" , & self . greeting , thing ) ; 1124} 1125} 1126`` ` 1127 1128`hello_lib/BUILD` : 1129`` `python 1130package ( default_visibility = [ "//visibility:public" ]) 1131 1132load ( "@rules_rust//rust:defs.bzl" , "rust_library" ) 1133 1134rust_library ( 1135name = "hello_lib" , 1136srcs = [ "src/lib.rs" ], 1137) 1138`` ` 1139 1140`hello_world/src/main.rs` : 1141`` `rust 1142extern crate hello_lib ; 1143 1144fn main () { 1145let hello = hello_lib :: Greeter :: new ( "Hello" ) ; 1146hello . greet ( "world" ) ; 1147} 1148`` ` 1149 1150`hello_world/BUILD` : 1151`` `python 1152load ( "@rules_rust//rust:defs.bzl" , "rust_binary" ) 1153 1154rust_binary ( 1155name = "hello_world" , 1156srcs = [ "src/main.rs" ], 1157deps = [ "//hello_lib" ], 1158) 1159`` ` 1160 1161Build and run `hello_world` : 1162`` ` 1163 $bazel run // hello_world 1164INFO : Found 1 target ... 1165Target // examples / rust / hello_world : hello_world up - to - date : 1166bazel - bin / examples / rust / hello_world / hello_world 1167INFO : Elapsed time : 1.308 s , Critical Path : 1.22 s 1168 1169INFO : Running command line : bazel - bin / examples / rust / hello_world / hello_world 1170Hello world 1171`` ` 1172 1173On Windows , a PDB file containing debugging information is available under 1174the key `pdb_file` in `OutputGroupInfo` . Similarly on macOS , a dSYM folder 1175is available under the key `dsym_folder` in `OutputGroupInfo` . 1176"""), 1177) 1178 1179def _common_attrs_for_binary_without_process_wrapper(attrs): 1180new_attr = dict(attrs) 1181 1182# use a fake process wrapper 1183new_attr["_process_wrapper"] = attr.label( 1184default = None, 1185executable = True, 1186allow_single_file = True, 1187cfg = "exec", 1188) 1189 1190new_attr["_bootstrap_process_wrapper"] = attr.label( 1191default = Label("//util/process_wrapper:bootstrap_process_wrapper"), 1192executable = True, 1193allow_single_file = True, 1194cfg = "exec", 1195) 1196 1197# fix stamp = 0 1198new_attr["stamp"] = attr.int( 1199doc = dedent(""" \ 1200Fix `stamp = 0` as stamping is not supported when building without process_wrapper : 1201https : // github . com / bazelbuild / rules_rust / blob / 8 df4517d370b0c543a01ba38b63e1d5a4104b035 / rust / private / rustc . bzl #L955 1202"""), 1203default = 0, 1204values = [0], 1205) 1206 1207return new_attr 1208 1209# Provides an internal rust_{binary,library} to use that we can use to build the process 1210# wrapper, this breaks the dependency of rust_* on the process wrapper by 1211# setting it to None, which the functions in rustc detect and build accordingly. 1212rust_binary_without_process_wrapper = rule( 1213implementation = _rust_binary_impl, 1214provides = COMMON_PROVIDERS, 1215attrs = _common_attrs_for_binary_without_process_wrapper(_common_attrs.items() + _rust_binary_attrs.items() + { 1216"platform": attr.label( 1217doc = "Optional platform to transition the binary to.", 1218default = None, 1219), 1220"_allowlist_function_transition": attr.label( 1221default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 1222), 1223}.items()), 1224executable = True, 1225fragments = ["cpp"], 1226cfg = _rust_binary_transition, 1227toolchains = [ 1228str(Label("//rust:toolchain_type")), 1229"@bazel_tools//tools/cpp:toolchain_type", 1230], 1231) 1232 1233rust_library_without_process_wrapper = rule( 1234implementation = _rust_library_impl, 1235provides = COMMON_PROVIDERS, 1236attrs = dict(_common_attrs_for_binary_without_process_wrapper(_common_attrs).items()), 1237fragments = ["cpp"], 1238toolchains = [ 1239str(Label("//rust:toolchain_type")), 1240"@bazel_tools//tools/cpp:toolchain_type", 1241], 1242) 1243 1244def _rust_test_transition_impl(settings, attr): 1245return { 1246"//command_line_option:platforms": str(attr.platform) if attr.platform else settings["//command_line_option:platforms"], 1247} 1248 1249_rust_test_transition = transition( 1250implementation = _rust_test_transition_impl, 1251inputs = [ 1252"//command_line_option:platforms", 1253], 1254outputs = [ 1255"//command_line_option:platforms", 1256], 1257) 1258 1259rust_test = rule( 1260implementation = _rust_test_impl, 1261provides = COMMON_PROVIDERS, 1262attrs = dict(_common_attrs.items() + _rust_test_attrs.items() + { 1263"platform": attr.label( 1264doc = "Optional platform to transition the test to.", 1265default = None, 1266), 1267"_allowlist_function_transition": attr.label( 1268default = "@bazel_tools//tools/allowlists/function_transition_allowlist", 1269), 1270}.items()), 1271executable = True, 1272fragments = ["cpp"], 1273cfg = _rust_test_transition, 1274test = True, 1275toolchains = [ 1276str(Label("//rust:toolchain_type")), 1277"@bazel_tools//tools/cpp:toolchain_type", 1278], 1279doc = dedent(""" \ 1280Builds a Rust test crate . 1281 1282Examples : 1283 1284Suppose you have the following directory structure for a Rust library crate \ 1285with unit test code in the library sources : 1286 1287`` `output 1288[ workspace ] / 1289WORKSPACE 1290hello_lib / 1291BUILD 1292src / 1293lib . rs 1294`` ` 1295 1296`hello_lib/src/lib.rs` : 1297`` `rust 1298pub struct Greeter { 1299greeting : String , 1300} 1301 1302impl Greeter { 1303pub fn new ( greeting : & str ) -> Greeter { 1304Greeter { greeting : greeting . to_string (), } 1305} 1306 1307pub fn greet ( & self , thing : & str ) -> String { 1308format !( "{} {}" , & self . greeting , thing ) 1309} 1310} 1311 1312#[cfg(test)] 1313mod test { 1314use super :: Greeter ; 1315 1316#[test] 1317fn test_greeting () { 1318let hello = Greeter :: new ( "Hi" ) ; 1319assert_eq !( "Hi Rust" , hello . greet ( "Rust" )) ; 1320} 1321} 1322`` ` 1323 1324To build and run the tests , simply add a `rust_test` rule with no `srcs` 1325and only depends on the `hello_lib` `rust_library` target via the 1326`crate` attribute : 1327 1328`hello_lib/BUILD` : 1329`` `python 1330load ( "@rules_rust//rust:defs.bzl" , "rust_library" , "rust_test" ) 1331 1332rust_library ( 1333name = "hello_lib" , 1334srcs = [ "src/lib.rs" ], 1335) 1336 1337rust_test ( 1338name = "hello_lib_test" , 1339crate = ":hello_lib" , 1340# You may add other deps that are specific to the test configuration 1341deps = [ "//some/dev/dep" ], 1342) 1343`` ` 1344 1345Run the test with `bazel test //hello_lib:hello_lib_test` . The crate 1346will be built using the same crate name as the underlying ":hello_lib" 1347crate . 1348 1349### Example: `test` directory 1350 1351Integration tests that live in the [ `tests` directory ][ int - tests ], they are \ 1352essentially built as separate crates . Suppose you have the following directory \ 1353structure where `greeting.rs` is an integration test for the `hello_lib` \ 1354library crate : 1355 1356[ int - tests ]: http : // doc . rust - lang . org / book / testing . html #the-tests-directory 1357 1358`` `output 1359[ workspace ] / 1360WORKSPACE 1361hello_lib / 1362BUILD 1363src / 1364lib . rs 1365tests / 1366greeting . rs 1367`` ` 1368 1369`hello_lib/tests/greeting.rs` : 1370`` `rust 1371extern crate hello_lib ; 1372 1373use hello_lib ; 1374 1375#[test] 1376fn test_greeting () { 1377let hello = greeter :: Greeter :: new ( "Hello" ) ; 1378assert_eq !( "Hello world" , hello . greeting ( "world" )) ; 1379} 1380`` ` 1381 1382To build the `greeting.rs` integration test , simply add a `rust_test` target 1383with `greeting.rs` in `srcs` and a dependency on the `hello_lib` target : 1384 1385`hello_lib/BUILD` : 1386`` `python 1387load ( "@rules_rust//rust:defs.bzl" , "rust_library" , "rust_test" ) 1388 1389rust_library ( 1390name = "hello_lib" , 1391srcs = [ "src/lib.rs" ], 1392) 1393 1394rust_test ( 1395name = "greeting_test" , 1396srcs = [ "tests/greeting.rs" ], 1397deps = [ ":hello_lib" ], 1398) 1399`` ` 1400 1401Run the test with `bazel test //hello_lib:greeting_test` . 1402"""), 1403) 1404 1405def rust_test_suite(name, srcs, shared_srcs = [], **kwargs): 1406""" A rule for creating a test suite for a set of `rust_test` targets . 1407 1408This rule can be used for setting up typical rust [ integration tests ][ it ]. Given the following 1409directory structure : 1410 1411`` `text 1412[ crate ] / 1413BUILD . bazel 1414src / 1415lib . rs 1416main . rs 1417tests / 1418integrated_test_a . rs 1419integrated_test_b . rs 1420integrated_test_c . rs 1421patterns / 1422fibonacci_test . rs 1423helpers / 1424mod . rs 1425`` ` 1426 1427The rule can be used to generate [ rust_test ]( #rust_test) targets for each source file under `tests` 1428and a [ test_suite ][ ts ] which encapsulates all tests . 1429 1430`` `python 1431load ( "//rust:defs.bzl" , "rust_binary" , "rust_library" , "rust_test_suite" ) 1432 1433rust_library ( 1434name = "math_lib" , 1435srcs = [ "src/lib.rs" ], 1436) 1437 1438rust_binary ( 1439name = "math_bin" , 1440srcs = [ "src/main.rs" ], 1441) 1442 1443rust_test_suite ( 1444name = "integrated_tests_suite" , 1445srcs = glob ([ "tests/**" ]), 1446shared_srcs = glob ([ "tests/helpers/**" ]), 1447deps = [ ":math_lib" ], 1448) 1449`` ` 1450 1451[ it ]: https : // doc . rust - lang . org / rust - by - example / testing / integration_testing . html 1452[ ts ]: https : // docs . bazel . build / versions / master / be / general . html #test_suite 1453 1454Args : 1455name ( str ): The name of the `test_suite` . 1456srcs ( list ): All test sources , typically `glob(["tests/**/*.rs"])` . 1457shared_srcs ( list ): Optional argument for sources shared among tests , typically helper functions . 1458** kwargs ( dict ): Additional keyword arguments for the underyling [ rust_test ]( #rust_test) targets. The 1459`tags` argument is also passed to the generated `test_suite` target . 1460""" 1461tests = [] 1462 1463for src in srcs: 1464if not src.endswith(".rs"): 1465fail("srcs should have `.rs` extensions") 1466 1467if src in shared_srcs: 1468continue 1469 1470# Prefixed with `name` to allow parameterization with macros 1471# The test name should not end with `.rs` 1472test_name = name + "_" + src[:-3] 1473rust_test( 1474name = test_name, 1475crate_root = src, 1476srcs = [src] + shared_srcs, 1477**kwargs 1478) 1479tests.append(test_name) 1480 1481native.test_suite( 1482name = name, 1483tests = tests, 1484tags = kwargs.get("tags", None), 1485) 1486 1487rust_library_group = rule( 1488implementation = _rust_library_group_impl, 1489provides = [rust_common.crate_group_info], 1490attrs = { 1491"deps": attr.label_list( 1492doc = "Other dependencies to forward through this crate group.", 1493providers = [[rust_common.crate_group_info], [rust_common.crate_info]], 1494), 1495}, 1496doc = dedent(""" \ 1497Functions as an alias for a set of dependencies . 1498 1499Specifically , the following are equivalent : 1500 1501`` `starlark 1502rust_library_group ( 1503name = "crate_group" , 1504deps = [ 1505":crate1" , 1506":crate2" , 1507], 1508) 1509 1510rust_library ( 1511name = "foobar" , 1512deps = [ ":crate_group" ], 1513... 1514) 1515`` ` 1516 1517and 1518 1519`` `starlark 1520rust_library ( 1521name = "foobar" , 1522deps = [ 1523":crate1" , 1524":crate2" , 1525], 1526... 1527) 1528`` ` 1529 """), 1530)