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