fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
26344d4c
0.7.0
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# buildifier: disable=module-docstring 16load ( "//rust/private:common.bzl" , "rust_common" ) 17load ( "//rust/private:rustc.bzl" , "rustc_compile_action" ) 18load ( 19"//rust/private:utils.bzl" , 20"compute_crate_name" , 21"dedent" , 22"determine_output_hash" , 23"expand_dict_value_locations" , 24"find_toolchain" , 25"get_import_macro_deps" , 26"transform_deps" , 27) 28 29# TODO(marco): Separate each rule into its own file. 30 31def _assert_no_deprecated_attributes ( _ctx ): 32"""Forces a failure if any deprecated attributes were specified 33 34Args: 35_ctx (ctx): The current rule's context object 36""" 37 pass 38 39def _assert_correct_dep_mapping ( ctx ): 40"""Forces a failure if proc_macro_deps and deps are mixed inappropriately 41 42Args: 43ctx (ctx): The current rule's context object 44""" 45for dep in ctx . attr . deps : 46if rust_common . crate_info in dep : 47if dep [ rust_common . crate_info ]. type == "proc-macro" : 48fail ( 49"{} listed {} in its deps, but it is a proc-macro. It should instead be in the bazel property proc_macro_deps." . format ( 50ctx . label , 51dep . label , 52), 53) 54for dep in ctx . attr . proc_macro_deps : 55type = dep [ rust_common . crate_info ]. type 56if type != "proc-macro" : 57fail ( 58"{} listed {} in its proc_macro_deps, but it is not proc-macro, it is a {}. It should probably instead be listed in deps." . format ( 59ctx . label , 60dep . label , 61type , 62), 63) 64 65def _determine_lib_name ( name , crate_type , toolchain , lib_hash = None ): 66"""See https://github.com/bazelbuild/rules_rust/issues/405 67 68Args: 69name (str): The name of the current target 70crate_type (str): The `crate_type` 71toolchain (rust_toolchain): The current `rust_toolchain` 72lib_hash (str, optional): The hashed crate root path 73 74Returns: 75str: A unique library name 76""" 77extension = None 78prefix = "" 79if crate_type in ( "dylib" , "cdylib" , "proc-macro" ): 80extension = toolchain . dylib_ext 81elif crate_type == "staticlib" : 82extension = toolchain . staticlib_ext 83elif crate_type in ( "lib" , "rlib" ): 84# All platforms produce 'rlib' here 85extension = ".rlib" 86prefix = "lib" 87elif crate_type == "bin" : 88fail ( "crate_type of 'bin' was detected in a rust_library. Please compile " + 89"this crate as a rust_binary instead." ) 90 91if not extension : 92fail (( "Unknown crate_type: {}. If this is a cargo-supported crate type, " + 93"please file an issue!" ). format ( crate_type )) 94 95prefix = "lib" 96if ( toolchain . target_triple . find ( "windows" ) != - 1 ) and crate_type not in ( "lib" , "rlib" ): 97prefix = "" 98if toolchain . target_arch == "wasm32" and crate_type == "cdylib" : 99prefix = "" 100 101return "{prefix}{name}{lib_hash}{extension}" . format ( 102prefix = prefix , 103name = name , 104lib_hash = "-" + lib_hash if lib_hash else "" , 105extension = extension , 106) 107 108def get_edition ( attr , toolchain , label ): 109"""Returns the Rust edition from either the current rule's attirbutes or the current `rust_toolchain` 110 111Args: 112attr (struct): The current rule's attributes 113toolchain (rust_toolchain): The `rust_toolchain` for the current target 114label (Label): The label of the target being built 115 116Returns: 117str: The target Rust edition 118""" 119if getattr ( attr , "edition" ): 120return attr . edition 121elif not toolchain . default_edition : 122fail ( "Attribute `edition` is required for {}." . format ( label )) 123else : 124return toolchain . default_edition 125 126def _transform_sources ( ctx , srcs , crate_root ): 127"""Creates symlinks of the source files if needed. 128 129Rustc assumes that the source files are located next to the crate root. 130In case of a mix between generated and non-generated source files, this 131we violate this assumption, as part of the sources will be located under 132bazel-out/... . In order to allow for targets that contain both generated 133and non-generated source files, we generate symlinks for all non-generated 134files. 135 136Args: 137ctx (struct): The current rule's context. 138srcs (List[File]): The sources listed in the `srcs` attribute 139crate_root (File): The file specified in the `crate_root` attribute, 140if it exists, otherwise None 141 142Returns: 143Tuple(List[File], File): The transformed srcs and crate_root 144""" 145has_generated_sources = len ([ src for src in srcs if not src . is_source ]) > 0 146 147if not has_generated_sources : 148return srcs , crate_root 149 150generated_sources = [] 151 152generated_root = crate_root 153 154if crate_root and ( crate_root . is_source or crate_root . root . path != ctx . bin_dir . path ): 155generated_root = ctx . actions . declare_file ( crate_root . basename ) 156ctx . actions . symlink ( 157output = generated_root , 158target_file = crate_root , 159progress_message = "Creating symlink to source file: {}" . format ( crate_root . path ), 160) 161if generated_root : 162generated_sources . append ( generated_root ) 163 164for src in srcs : 165# We took care of the crate root above. 166if src == crate_root : 167 continue 168if src . is_source or src . root . path != ctx . bin_dir . path : 169src_symlink = ctx . actions . declare_file ( src . basename ) 170ctx . actions . symlink ( 171output = src_symlink , 172target_file = src , 173progress_message = "Creating symlink to source file: {}" . format ( src . path ), 174) 175generated_sources . append ( src_symlink ) 176else : 177generated_sources . append ( src ) 178 179return generated_sources , generated_root 180 181def crate_root_src ( name , srcs , crate_type ): 182"""Determines the source file for the crate root, should it not be specified in `attr.crate_root`. 183 184Args: 185name (str): The name of the target. 186srcs (list): A list of all sources for the target Crate. 187crate_type (str): The type of this crate ("bin", "lib", "rlib", "cdylib", etc). 188 189Returns: 190File: The root File object for a given crate. See the following links for more details: 191- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#library 192- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#binaries 193""" 194default_crate_root_filename = "main.rs" if crate_type == "bin" else "lib.rs" 195 196crate_root = ( 197( srcs [ 0 ] if len ( srcs ) == 1 else None ) or 198_shortest_src_with_basename ( srcs , default_crate_root_filename ) or 199_shortest_src_with_basename ( srcs , name + ".rs" ) 200) 201if not crate_root : 202file_names = [ default_crate_root_filename , name + ".rs" ] 203fail ( "No {} source file found." . format ( " or " . join ( file_names )), "srcs" ) 204return crate_root 205 206def _shortest_src_with_basename ( srcs , basename ): 207"""Finds the shortest among the paths in srcs that match the desired basename. 208 209Args: 210srcs (list): A list of File objects 211basename (str): The target basename to match against. 212 213Returns: 214File: The File object with the shortest path that matches `basename` 215""" 216shortest = None 217for f in srcs : 218if f . basename == basename : 219if not shortest or len ( f . dirname ) < len ( shortest . dirname ): 220shortest = f 221return shortest 222 223def _rust_library_impl ( ctx ): 224"""The implementation of the `rust_library` rule. 225 226This rule provides CcInfo, so it can be used everywhere Bazel 227expects rules_cc, but care must be taken to have the correct 228dependencies on an allocator and std implemetation as needed. 229 230Args: 231ctx (ctx): The rule's context object 232 233Returns: 234list: A list of providers. 235""" 236return _rust_library_common ( ctx , "rlib" ) 237 238def _rust_static_library_impl ( ctx ): 239"""The implementation of the `rust_static_library` rule. 240 241This rule provides CcInfo, so it can be used everywhere Bazel 242expects rules_cc. 243 244Args: 245ctx (ctx): The rule's context object 246 247Returns: 248list: A list of providers. 249""" 250return _rust_library_common ( ctx , "staticlib" ) 251 252def _rust_shared_library_impl ( ctx ): 253"""The implementation of the `rust_shared_library` rule. 254 255This rule provides CcInfo, so it can be used everywhere Bazel 256expects rules_cc. 257 258On Windows, a PDB file containing debugging information is available under 259the key `pdb_file` in `OutputGroupInfo`. Similarly on macOS, a dSYM folder 260is available under the key `dsym_folder` in `OutputGroupInfo`. 261 262Args: 263ctx (ctx): The rule's context object 264 265Returns: 266list: A list of providers. 267""" 268return _rust_library_common ( ctx , "cdylib" ) 269 270def _rust_proc_macro_impl ( ctx ): 271"""The implementation of the `rust_proc_macro` rule. 272 273Args: 274ctx (ctx): The rule's context object 275 276Returns: 277list: A list of providers. 278""" 279return _rust_library_common ( ctx , "proc-macro" ) 280 281def _rust_library_common ( ctx , crate_type ): 282"""The common implementation of the library-like rules. 283 284Args: 285ctx (ctx): The rule's context object 286crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro 287 288Returns: 289list: A list of providers. See `rustc_compile_action` 290""" 291 292srcs , crate_root = _transform_sources ( ctx , ctx . files . srcs , getattr ( ctx . file , "crate_root" , None )) 293if not crate_root : 294crate_root = crate_root_src ( ctx . attr . name , srcs , "lib" ) 295_assert_no_deprecated_attributes ( ctx ) 296_assert_correct_dep_mapping ( ctx ) 297 298toolchain = find_toolchain ( ctx ) 299 300# Determine unique hash for this rlib. 301# Note that we don't include a hash for `cdylib` and `staticlib` since they are meant to be consumed externally 302# and having a deterministic name is important since it ends up embedded in the executable. This is problematic 303# when one needs to include the library with a specific filename into a larger application. 304# (see https://github.com/bazelbuild/rules_rust/issues/405#issuecomment-993089889 for more details) 305if crate_type in [ "cdylib" , "staticlib" ]: 306output_hash = None 307else : 308output_hash = determine_output_hash ( crate_root , ctx . label ) 309 310crate_name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ) 311rust_lib_name = _determine_lib_name ( 312crate_name , 313crate_type , 314toolchain , 315output_hash , 316) 317rust_lib = ctx . actions . declare_file ( rust_lib_name ) 318 319deps = transform_deps ( ctx . attr . deps ) 320proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 321 322return rustc_compile_action ( 323ctx = ctx , 324attr = ctx . attr , 325toolchain = toolchain , 326crate_info = rust_common . create_crate_info ( 327name = crate_name , 328type = crate_type , 329root = crate_root , 330srcs = depset ( srcs ), 331deps = depset ( deps ), 332proc_macro_deps = depset ( proc_macro_deps ), 333aliases = ctx . attr . aliases , 334output = rust_lib , 335edition = get_edition ( ctx . attr , toolchain , ctx . label ), 336rustc_env = ctx . attr . rustc_env , 337is_test = False , 338compile_data = depset ( ctx . files . compile_data ), 339owner = ctx . label , 340), 341output_hash = output_hash , 342) 343 344def _rust_binary_impl ( ctx ): 345"""The implementation of the `rust_binary` rule 346 347Args: 348ctx (ctx): The rule's context object 349 350Returns: 351list: A list of providers. See `rustc_compile_action` 352""" 353toolchain = find_toolchain ( ctx ) 354crate_name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ) 355_assert_correct_dep_mapping ( ctx ) 356 357output = ctx . actions . declare_file ( ctx . label . name + toolchain . binary_ext ) 358 359deps = transform_deps ( ctx . attr . deps ) 360proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 361 362srcs , crate_root = _transform_sources ( ctx , ctx . files . srcs , getattr ( ctx . file , "crate_root" , None )) 363if not crate_root : 364crate_root = crate_root_src ( ctx . attr . name , srcs , ctx . attr . crate_type ) 365 366return rustc_compile_action ( 367ctx = ctx , 368attr = ctx . attr , 369toolchain = toolchain , 370crate_info = rust_common . create_crate_info ( 371name = crate_name , 372type = ctx . attr . crate_type , 373root = crate_root , 374srcs = depset ( srcs ), 375deps = depset ( deps ), 376proc_macro_deps = depset ( proc_macro_deps ), 377aliases = ctx . attr . aliases , 378output = output , 379edition = get_edition ( ctx . attr , toolchain , ctx . label ), 380rustc_env = ctx . attr . rustc_env , 381is_test = False , 382compile_data = depset ( ctx . files . compile_data ), 383owner = ctx . label , 384), 385) 386 387def _rust_test_impl ( ctx ): 388"""The implementation of the `rust_test` rule. 389 390Args: 391ctx (ctx): The ctx object for the current target. 392 393Returns: 394list: The list of providers. See `rustc_compile_action` 395""" 396_assert_no_deprecated_attributes ( ctx ) 397_assert_correct_dep_mapping ( ctx ) 398 399toolchain = find_toolchain ( ctx ) 400 401srcs , crate_root = _transform_sources ( ctx , ctx . files . srcs , getattr ( ctx . file , "crate_root" , None )) 402crate_type = "bin" 403 404deps = transform_deps ( ctx . attr . deps ) 405proc_macro_deps = transform_deps ( ctx . attr . proc_macro_deps + get_import_macro_deps ( ctx )) 406 407if ctx . attr . crate : 408# Target is building the crate in `test` config 409crate = 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 410 411output_hash = determine_output_hash ( crate . root , ctx . label ) 412output = ctx . actions . declare_file ( 413"test-%s/%s%s" % ( 414output_hash , 415ctx . label . name , 416toolchain . binary_ext , 417), 418) 419 420# Optionally join compile data 421if crate . compile_data : 422compile_data = depset ( ctx . files . compile_data , transitive = [ crate . compile_data ]) 423else : 424compile_data = depset ( ctx . files . compile_data ) 425 426# Build the test binary using the dependency's srcs. 427crate_info = rust_common . create_crate_info ( 428name = crate . name , 429type = crate_type , 430root = crate . root , 431srcs = depset ( srcs , transitive = [ crate . srcs ]), 432deps = depset ( deps , transitive = [ crate . deps ]), 433proc_macro_deps = depset ( proc_macro_deps , transitive = [ crate . proc_macro_deps ]), 434aliases = ctx . attr . aliases , 435output = output , 436edition = crate . edition , 437rustc_env = ctx . attr . rustc_env , 438is_test = True , 439compile_data = compile_data , 440wrapped_crate_type = crate . type , 441owner = ctx . label , 442) 443else : 444if not crate_root : 445crate_root = crate_root_src ( ctx . attr . name , ctx . files . srcs , "lib" ) 446 447output_hash = determine_output_hash ( crate_root , ctx . label ) 448output = ctx . actions . declare_file ( 449"test-%s/%s%s" % ( 450output_hash , 451ctx . label . name , 452toolchain . binary_ext , 453), 454) 455 456# Target is a standalone crate. Build the test binary as its own crate. 457crate_info = rust_common . create_crate_info ( 458name = compute_crate_name ( ctx . workspace_name , ctx . label , toolchain , ctx . attr . crate_name ), 459type = crate_type , 460root = crate_root , 461srcs = depset ( srcs ), 462deps = depset ( deps ), 463proc_macro_deps = depset ( proc_macro_deps ), 464aliases = ctx . attr . aliases , 465output = output , 466edition = get_edition ( ctx . attr , toolchain , ctx . label ), 467rustc_env = ctx . attr . rustc_env , 468is_test = True , 469compile_data = depset ( ctx . files . compile_data ), 470owner = ctx . label , 471) 472 473providers = rustc_compile_action ( 474ctx = ctx , 475attr = ctx . attr , 476toolchain = toolchain , 477crate_info = crate_info , 478rust_flags = [ "--test" ] if ctx . attr . use_libtest_harness else [ "--cfg" , "test" ], 479) 480data = getattr ( ctx . attr , "data" , []) 481 482env = expand_dict_value_locations ( 483ctx , 484getattr ( ctx . attr , "env" , {}), 485data , 486) 487if toolchain . llvm_cov and ctx . configuration . coverage_enabled : 488if not toolchain . llvm_profdata : 489fail ( "toolchain.llvm_profdata is required if toolchain.llvm_cov is set." ) 490 491env [ "RUST_LLVM_COV" ] = toolchain . llvm_cov . path 492env [ "RUST_LLVM_PROFDATA" ] = toolchain . llvm_profdata . path 493providers . append ( testing . TestEnvironment ( env )) 494 495return providers 496 497_common_attrs = { 498"aliases" : attr . label_keyed_string_dict ( 499doc = dedent ( """\ 500Remap crates to a new name or moniker for linkage to this target 501 502These are other `rust_library` targets and will be presented as the new name given. 503""" ), 504), 505"compile_data" : attr . label_list ( 506doc = dedent ( """\ 507List of files used by this rule at compile time. 508 509This attribute can be used to specify any data files that are embedded into 510the library, such as via the 511[`include_str!`](https://doc.rust-lang.org/std/macro.include_str!.html) 512macro. 513""" ), 514allow_files = True , 515), 516"crate_features" : attr . string_list ( 517doc = dedent ( """\ 518List of features to enable for this crate. 519 520Features are defined in the code using the `#[cfg(feature = "foo")]` 521configuration option. The features listed here will be passed to `rustc` 522with `--cfg feature="${feature_name}"` flags. 523""" ), 524), 525"crate_name" : attr . string ( 526doc = dedent ( """\ 527Crate name to use for this target. 528 529This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. 530Defaults to the target name, with any hyphens replaced by underscores. 531""" ), 532), 533"crate_root" : attr . label ( 534doc = dedent ( """\ 535The file that will be passed to `rustc` to be used for building this crate. 536 537If `crate_root` is not set, then this rule will look for a `lib.rs` file (or `main.rs` for rust_binary) 538or the single file in `srcs` if `srcs` contains only one file. 539""" ), 540allow_single_file = [ ".rs" ], 541), 542"data" : attr . label_list ( 543doc = dedent ( """\ 544List of files used by this rule at compile time and runtime. 545 546If including data at compile time with include_str!() and similar, 547prefer `compile_data` over `data`, to prevent the data also being included 548in the runfiles. 549""" ), 550allow_files = True , 551), 552"deps" : attr . label_list ( 553doc = dedent ( """\ 554List of other libraries to be linked to this library target. 555 556These can be either other `rust_library` targets or `cc_library` targets if 557linking a native library. 558""" ), 559), 560"edition" : attr . string ( 561doc = "The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain." , 562), 563# Previously `proc_macro_deps` were a part of `deps`, and then proc_macro_host_transition was 564# used into cfg="host" using `@local_config_platform//:host`. 565# This fails for remote execution, which needs cfg="exec", and there isn't anything like 566# `@local_config_platform//:exec` exposed. 567"proc_macro_deps" : attr . label_list ( 568doc = dedent ( """\ 569List of `rust_library` targets with kind `proc-macro` used to help build this library target. 570""" ), 571cfg = "exec" , 572providers = [ rust_common . crate_info ], 573), 574"rustc_env" : attr . string_dict ( 575doc = dedent ( """\ 576Dictionary of additional `"key": "value"` environment variables to set for rustc. 577 578rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the 579location of a generated file or external tool. Cargo build scripts that wish to 580expand locations should use cargo_build_script()'s build_script_env argument instead, 581as build scripts are run in a different environment - see cargo_build_script()'s 582documentation for more. 583""" ), 584), 585"rustc_env_files" : attr . label_list ( 586doc = dedent ( """\ 587 Files containing additional environment variables to set for rustc. 588 589 These files should contain a single variable per line, of format 590 `NAME=value`, and newlines may be included in a value by ending a 591 line with a trailing back-slash (`\\\\`). 592 593The order that these files will be processed is unspecified , so 594multiple definitions of a particular variable are discouraged . 595 596Note that the variables here are subject to 597[ workspace status ]( https : // docs . bazel . build / versions / main / user - manual . html #workspace_status) 598stamping should the `stamp` attribute be enabled . Stamp variables 599should be wrapped in brackets in order to be resolved . E . g . 600`NAME={WORKSPACE_STATUS_VARIABLE}` . 601"""), 602allow_files = True, 603), 604"rustc_flags": attr.string_list( 605doc = dedent(""" \ 606List of compiler flags passed to `rustc` . 607 608These strings are subject to Make variable expansion for predefined 609source / output path variables like `$location` , `$execpath` , and 610`$rootpath` . This expansion is useful if you wish to passa generated 611file of arguments to rustc : `@$(location //package:target)` . 612"""), 613), 614# TODO(stardoc): How do we provide additional documentation to an inherited attribute? 615# "name": attr.string( 616# doc = "This name will also be used as the name of the crate built by this rule.", 617# `), 618"srcs": attr.label_list( 619doc = dedent(""" \ 620List of Rust `.rs` source files used to build the library . 621 622If `srcs` contains more than one file , then there must be a file either 623named `lib.rs` . Otherwise , `crate_root` must be set to the source file that 624is the root of the crate to be passed to rustc to build this crate . 625"""), 626allow_files = [".rs"], 627), 628"stamp": attr.int( 629doc = dedent(""" \ 630Whether to encode build information into the `Rustc` action . Possible values : 631 632- `stamp = 1` : Always stamp the build information into the `Rustc` action , even in \ 633[ -- nostamp ]( https : // docs . bazel . build / versions / main / user - manual . html #flag--stamp) builds. \ 634This setting should be avoided , since it potentially kills remote caching for the target and \ 635any downstream actions that depend on it . 636 637- `stamp = 0` : Always replace build information by constant values . This gives good build result caching . 638 639- `stamp = -1` : Embedding of build information is controlled by the \ 640[ -- [ no ] stamp ]( https : // docs . bazel . build / versions / main / user - manual . html #flag--stamp) flag. 641 642Stamped targets are not rebuilt unless their dependencies change . 643 644For example if a `rust_library` is stamped , and a `rust_binary` depends on that library , the stamped 645library won 't be rebuilt when we change sources of the `rust_binary` . This is different from how 646[ `cc_library.linkstamps` ]( https : // docs . bazel . build / versions / main / be / c - cpp . html #cc_library.linkstamp) 647behaves . 648"""), 649default = -1, 650values = [1, 0, -1], 651), 652"version": attr.string( 653doc = "A version to inject in the cargo environment variable.", 654default = "0.0.0", 655), 656"_cc_toolchain": attr.label( 657doc = ( 658"In order to use find_cc_toolchain, your rule has to depend " + 659"on C++ toolchain. See `@rules_cc//cc:find_cc_toolchain.bzl` " + 660"docs for details." 661), 662default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"), 663), 664"_collect_cc_coverage": attr.label( 665default = Label("//util:collect_coverage"), 666executable = True, 667cfg = "exec", 668), 669"_error_format": attr.label( 670default = Label("//:error_format"), 671), 672"_extra_exec_rustc_flags": attr.label( 673default = Label("//:extra_exec_rustc_flags"), 674), 675"_extra_rustc_flags": attr.label( 676default = Label("//:extra_rustc_flags"), 677), 678"_import_macro_dep": attr.label( 679default = Label("//util/import"), 680cfg = "exec", 681), 682"_process_wrapper": attr.label( 683doc = "A process wrapper for running rustc on all platforms.", 684default = Label("//util/process_wrapper"), 685executable = True, 686allow_single_file = True, 687cfg = "exec", 688), 689"_stamp_flag": attr.label( 690doc = "A setting used to determine whether or not the `--stamp` flag is enabled", 691default = Label("//rust/private:stamp"), 692), 693} 694 695_rust_test_attrs = { 696"crate": attr.label( 697mandatory = False, 698doc = dedent(""" \ 699Target inline tests declared in the given crate 700 701These tests are typically those that would be held out under 702 `#[cfg(test)]` declarations. 703"""), 704), 705"env": attr.string_dict( 706mandatory = False, 707doc = dedent(""" \ 708Specifies additional environment variables to set when the test is executed by bazel test . 709Values are subject to `$(rootpath)` , `$(execpath)` , location , and 710[ "Make variable" ]( https : // docs . bazel . build / versions / master / be / make - variables . html ) substitution . 711 712Execpath returns absolute path , and in order to be able to construct the absolute path we 713need to wrap the test binary in a launcher . Using a launcher comes with complications , such as 714more complicated debugger attachment . 715"""), 716), 717"use_libtest_harness": attr.bool( 718mandatory = False, 719default = True, 720doc = dedent(""" \ 721Whether to use `libtest` . For targets using this flag , individual tests can be run by using the 722[ -- test_arg ]( https : // docs . bazel . build / versions / 4.0 . 0 / command - line - reference . html #flag--test_arg) flag. 723E . g . `bazel test //src:rust_test --test_arg=foo::test::test_fn` . 724"""), 725), 726"_grep_includes": attr.label( 727allow_single_file = True, 728cfg = "exec", 729default = Label("@bazel_tools//tools/cpp:grep-includes"), 730executable = True, 731), 732} 733 734_common_providers = [ 735rust_common.crate_info, 736rust_common.dep_info, 737DefaultInfo, 738] 739 740rust_library = rule( 741implementation = _rust_library_impl, 742provides = _common_providers, 743attrs = dict(_common_attrs.items()), 744fragments = ["cpp"], 745host_fragments = ["cpp"], 746toolchains = [ 747str(Label("//rust:toolchain")), 748"@bazel_tools//tools/cpp:toolchain_type", 749], 750incompatible_use_toolchain_transition = True, 751doc = dedent(""" \ 752Builds a Rust library crate . 753 754Example : 755 756Suppose you have the following directory structure for a simple Rust library crate : 757 758`` `output 759[ workspace ] / 760WORKSPACE 761hello_lib / 762BUILD 763src / 764greeter . rs 765lib . rs 766`` ` 767 768`hello_lib/src/greeter.rs` : 769`` `rust 770pub struct Greeter { 771greeting : String , 772} 773 774impl Greeter { 775pub fn new ( greeting : & str ) -> Greeter { 776Greeter { greeting : greeting . to_string (), } 777} 778 779pub fn greet ( & self , thing : & str ) { 780println !( "{} {}" , & self . greeting , thing ) ; 781} 782} 783`` ` 784 785`hello_lib/src/lib.rs` : 786 787`` `rust 788pub mod greeter ; 789`` ` 790 791`hello_lib/BUILD` : 792`` `python 793package ( default_visibility = [ "//visibility:public" ]) 794 795load ( "@rules_rust//rust:defs.bzl" , "rust_library" ) 796 797rust_library ( 798name = "hello_lib" , 799srcs = [ 800"src/greeter.rs" , 801"src/lib.rs" , 802], 803) 804`` ` 805 806Build the library : 807`` `output 808 $bazel build // hello_lib 809INFO : Found 1 target ... 810Target // examples / rust / hello_lib : hello_lib up - to - date : 811bazel - bin / examples / rust / hello_lib / libhello_lib . rlib 812INFO : Elapsed time : 1.245 s , Critical Path : 1.01 s 813`` ` 814"""), 815) 816 817rust_static_library = rule( 818implementation = _rust_static_library_impl, 819attrs = dict(_common_attrs.items()), 820fragments = ["cpp"], 821host_fragments = ["cpp"], 822toolchains = [ 823str(Label("//rust:toolchain")), 824"@bazel_tools//tools/cpp:toolchain_type", 825], 826incompatible_use_toolchain_transition = True, 827doc = dedent(""" \ 828Builds a Rust static library . 829 830This static library will contain all transitively reachable crates and native objects . 831It is meant to be used when producing an artifact that is then consumed by some other build system 832( for example to produce an archive that Python program links against ). 833 834This rule provides CcInfo , so it can be used everywhere Bazel expects `rules_cc` . 835 836When building the whole binary in Bazel , use `rust_library` instead . 837"""), 838) 839 840rust_shared_library = rule( 841implementation = _rust_shared_library_impl, 842attrs = dict(_common_attrs.items()), 843fragments = ["cpp"], 844host_fragments = ["cpp"], 845toolchains = [ 846str(Label("//rust:toolchain")), 847"@bazel_tools//tools/cpp:toolchain_type", 848], 849incompatible_use_toolchain_transition = True, 850doc = dedent(""" \ 851Builds a Rust shared library . 852 853This shared library will contain all transitively reachable crates and native objects . 854It is meant to be used when producing an artifact that is then consumed by some other build system 855( for example to produce a shared library that Python program links against ). 856 857This rule provides CcInfo , so it can be used everywhere Bazel expects `rules_cc` . 858 859When building the whole binary in Bazel , use `rust_library` instead . 860"""), 861) 862 863rust_proc_macro = rule( 864implementation = _rust_proc_macro_impl, 865provides = _common_providers, 866attrs = dict(_common_attrs.items()), 867fragments = ["cpp"], 868host_fragments = ["cpp"], 869toolchains = [ 870str(Label("//rust:toolchain")), 871"@bazel_tools//tools/cpp:toolchain_type", 872], 873incompatible_use_toolchain_transition = True, 874doc = dedent(""" \ 875Builds a Rust proc - macro crate . 876"""), 877) 878 879_rust_binary_attrs = { 880"crate_type": attr.string( 881doc = dedent(""" \ 882Crate type that will be passed to `rustc` to be used for building this crate . 883 884This option is a temporary workaround and should be used only when building 885for WebAssembly targets ( // rust / platform : wasi and // rust / platform : wasm ). 886"""), 887default = "bin", 888), 889"linker_script": attr.label( 890doc = dedent(""" \ 891Link script to forward into linker via rustc options . 892"""), 893cfg = "exec", 894allow_single_file = True, 895), 896"out_binary": attr.bool( 897doc = ( 898"Force a target, regardless of it's `crate_type`, to always mark the " + 899"file as executable. This attribute is only used to support wasm targets but is " + 900"expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771." 901), 902default = False, 903), 904"_grep_includes": attr.label( 905allow_single_file = True, 906cfg = "exec", 907default = Label("@bazel_tools//tools/cpp:grep-includes"), 908executable = True, 909), 910} 911 912rust_binary = rule( 913implementation = _rust_binary_impl, 914provides = _common_providers, 915attrs = dict(_common_attrs.items() + _rust_binary_attrs.items()), 916executable = True, 917fragments = ["cpp"], 918host_fragments = ["cpp"], 919toolchains = [ 920str(Label("//rust:toolchain")), 921"@bazel_tools//tools/cpp:toolchain_type", 922], 923incompatible_use_toolchain_transition = True, 924doc = dedent(""" \ 925Builds a Rust binary crate . 926 927Example : 928 929Suppose you have the following directory structure for a Rust project with a 930library crate , `hello_lib` , and a binary crate , `hello_world` that uses the 931`hello_lib` library : 932 933`` `output 934[ workspace ] / 935WORKSPACE 936hello_lib / 937BUILD 938src / 939lib . rs 940hello_world / 941BUILD 942src / 943main . rs 944`` ` 945 946`hello_lib/src/lib.rs` : 947`` `rust 948pub struct Greeter { 949greeting : String , 950} 951 952impl Greeter { 953pub fn new ( greeting : & str ) -> Greeter { 954Greeter { greeting : greeting . to_string (), } 955} 956 957pub fn greet ( & self , thing : & str ) { 958println !( "{} {}" , & self . greeting , thing ) ; 959} 960} 961`` ` 962 963`hello_lib/BUILD` : 964`` `python 965package ( default_visibility = [ "//visibility:public" ]) 966 967load ( "@rules_rust//rust:defs.bzl" , "rust_library" ) 968 969rust_library ( 970name = "hello_lib" , 971srcs = [ "src/lib.rs" ], 972) 973`` ` 974 975`hello_world/src/main.rs` : 976`` `rust 977extern crate hello_lib ; 978 979fn main () { 980let hello = hello_lib :: Greeter :: new ( "Hello" ) ; 981hello . greet ( "world" ) ; 982} 983`` ` 984 985`hello_world/BUILD` : 986`` `python 987load ( "@rules_rust//rust:defs.bzl" , "rust_binary" ) 988 989rust_binary ( 990name = "hello_world" , 991srcs = [ "src/main.rs" ], 992deps = [ "//hello_lib" ], 993) 994`` ` 995 996Build and run `hello_world` : 997`` ` 998 $bazel run // hello_world 999INFO : Found 1 target ... 1000Target // examples / rust / hello_world : hello_world up - to - date : 1001bazel - bin / examples / rust / hello_world / hello_world 1002INFO : Elapsed time : 1.308 s , Critical Path : 1.22 s 1003 1004INFO : Running command line : bazel - bin / examples / rust / hello_world / hello_world 1005Hello world 1006`` ` 1007 1008On Windows , a PDB file containing debugging information is available under 1009the key `pdb_file` in `OutputGroupInfo` . Similarly on macOS , a dSYM folder 1010is available under the key `dsym_folder` in `OutputGroupInfo` . 1011"""), 1012) 1013 1014def _common_attrs_for_binary_without_process_wrapper(attrs): 1015new_attr = dict(attrs.items()) 1016 1017# use a fake process wrapper 1018new_attr["_process_wrapper"] = attr.label( 1019default = None, 1020executable = True, 1021allow_single_file = True, 1022cfg = "exec", 1023) 1024 1025# fix stamp = 0 1026new_attr["stamp"] = attr.int( 1027doc = dedent(""" \ 1028Fix `stamp = 0` as stamping is not supported when building without process_wrapper : 1029https : // github . com / bazelbuild / rules_rust / blob / 8 df4517d370b0c543a01ba38b63e1d5a4104b035 / rust / private / rustc . bzl #L955 1030"""), 1031default = 0, 1032values = [0], 1033) 1034 1035return new_attr 1036 1037# Provides an internal rust_{binary,library} to use that we can use to build the process 1038# wrapper, this breaks the dependency of rust_* on the process wrapper by 1039# setting it to None, which the functions in rustc detect and build accordingly. 1040rust_binary_without_process_wrapper = rule( 1041implementation = _rust_binary_impl, 1042provides = _common_providers, 1043attrs = dict(_common_attrs_for_binary_without_process_wrapper(_common_attrs).items() + _rust_binary_attrs.items()), 1044executable = True, 1045fragments = ["cpp"], 1046host_fragments = ["cpp"], 1047toolchains = [ 1048str(Label("//rust:toolchain")), 1049"@bazel_tools//tools/cpp:toolchain_type", 1050], 1051incompatible_use_toolchain_transition = True, 1052) 1053 1054rust_library_without_process_wrapper = rule( 1055implementation = _rust_library_impl, 1056provides = _common_providers, 1057attrs = dict(_common_attrs_for_binary_without_process_wrapper(_common_attrs).items()), 1058fragments = ["cpp"], 1059host_fragments = ["cpp"], 1060toolchains = [ 1061str(Label("//rust:toolchain")), 1062"@bazel_tools//tools/cpp:toolchain_type", 1063], 1064incompatible_use_toolchain_transition = True, 1065) 1066 1067rust_test = rule( 1068implementation = _rust_test_impl, 1069provides = _common_providers, 1070attrs = dict(_common_attrs.items() + 1071_rust_test_attrs.items()), 1072executable = True, 1073fragments = ["cpp"], 1074host_fragments = ["cpp"], 1075test = True, 1076toolchains = [ 1077str(Label("//rust:toolchain")), 1078"@bazel_tools//tools/cpp:toolchain_type", 1079], 1080incompatible_use_toolchain_transition = True, 1081doc = dedent(""" \ 1082Builds a Rust test crate . 1083 1084Examples : 1085 1086Suppose you have the following directory structure for a Rust library crate \ 1087with unit test code in the library sources : 1088 1089`` `output 1090[ workspace ] / 1091WORKSPACE 1092hello_lib / 1093BUILD 1094src / 1095lib . rs 1096`` ` 1097 1098`hello_lib/src/lib.rs` : 1099`` `rust 1100pub struct Greeter { 1101greeting : String , 1102} 1103 1104impl Greeter { 1105pub fn new ( greeting : & str ) -> Greeter { 1106Greeter { greeting : greeting . to_string (), } 1107} 1108 1109pub fn greet ( & self , thing : & str ) -> String { 1110format !( "{} {}" , & self . greeting , thing ) 1111} 1112} 1113 1114#[cfg(test)] 1115mod test { 1116use super :: Greeter ; 1117 1118#[test] 1119fn test_greeting () { 1120let hello = Greeter :: new ( "Hi" ) ; 1121assert_eq !( "Hi Rust" , hello . greet ( "Rust" )) ; 1122} 1123} 1124`` ` 1125 1126To build and run the tests , simply add a `rust_test` rule with no `srcs` 1127and only depends on the `hello_lib` `rust_library` target via the 1128`crate` attribute : 1129 1130`hello_lib/BUILD` : 1131`` `python 1132load ( "@rules_rust//rust:defs.bzl" , "rust_library" , "rust_test" ) 1133 1134rust_library ( 1135name = "hello_lib" , 1136srcs = [ "src/lib.rs" ], 1137) 1138 1139rust_test ( 1140name = "hello_lib_test" , 1141crate = ":hello_lib" , 1142# You may add other deps that are specific to the test configuration 1143deps = [ "//some/dev/dep" ], 1144`` ` 1145 1146Run the test with `bazel test //hello_lib:hello_lib_test` . The crate 1147will be built using the same crate name as the underlying ":hello_lib" 1148crate . 1149 1150### Example: `test` directory 1151 1152Integration tests that live in the [ `tests` directory ][ int - tests ], they are \ 1153essentially built as separate crates . Suppose you have the following directory \ 1154structure where `greeting.rs` is an integration test for the `hello_lib` \ 1155library crate : 1156 1157[ int - tests ]: http : // doc . rust - lang . org / book / testing . html #the-tests-directory 1158 1159`` `output 1160[ workspace ] / 1161WORKSPACE 1162hello_lib / 1163BUILD 1164src / 1165lib . rs 1166tests / 1167greeting . rs 1168`` ` 1169 1170`hello_lib/tests/greeting.rs` : 1171`` `rust 1172extern crate hello_lib ; 1173 1174use hello_lib ; 1175 1176#[test] 1177fn test_greeting () { 1178let hello = greeter :: Greeter :: new ( "Hello" ) ; 1179assert_eq !( "Hello world" , hello . greeting ( "world" )) ; 1180} 1181`` ` 1182 1183To build the `greeting.rs` integration test , simply add a `rust_test` target 1184with `greeting.rs` in `srcs` and a dependency on the `hello_lib` target : 1185 1186`hello_lib/BUILD` : 1187`` `python 1188load ( "@rules_rust//rust:defs.bzl" , "rust_library" , "rust_test" ) 1189 1190rust_library ( 1191name = "hello_lib" , 1192srcs = [ "src/lib.rs" ], 1193) 1194 1195rust_test ( 1196name = "greeting_test" , 1197srcs = [ "tests/greeting.rs" ], 1198deps = [ ":hello_lib" ], 1199) 1200`` ` 1201 1202Run the test with `bazel test //hello_lib:greeting_test` . 1203"""), 1204) 1205 1206def rust_test_suite(name, srcs, **kwargs): 1207""" A rule for creating a test suite for a set of `rust_test` targets . 1208 1209This rule can be used for setting up typical rust [ integration tests ][ it ]. Given the following 1210directory structure : 1211 1212`` `text 1213[ crate ] / 1214BUILD . bazel 1215src / 1216lib . rs 1217main . rs 1218tests / 1219integrated_test_a . rs 1220integrated_test_b . rs 1221integrated_test_c . rs 1222patterns / 1223fibonacci_test . rs 1224`` ` 1225 1226The rule can be used to generate [ rust_test ]( #rust_test) targets for each source file under `tests` 1227and a [ test_suite ][ ts ] which encapsulates all tests . 1228 1229`` `python 1230load ( "//rust:defs.bzl" , "rust_binary" , "rust_library" , "rust_test_suite" ) 1231 1232rust_library ( 1233name = "math_lib" , 1234srcs = [ "src/lib.rs" ], 1235) 1236 1237rust_binary ( 1238name = "math_bin" , 1239srcs = [ "src/main.rs" ], 1240) 1241 1242rust_test_suite ( 1243name = "integrated_tests_suite" , 1244srcs = glob ([ "tests/**" ]), 1245deps = [ ":math_lib" ], 1246) 1247`` ` 1248 1249[ it ]: https : // doc . rust - lang . org / rust - by - example / testing / integration_testing . html 1250[ ts ]: https : // docs . bazel . build / versions / master / be / general . html #test_suite 1251 1252Args : 1253name ( str ): The name of the `test_suite` . 1254srcs ( list ): All test sources , typically `glob(["tests/**/*.rs"])` . 1255** kwargs ( dict ): Additional keyword arguments for the underyling [ rust_test ]( #rust_test) targets. The 1256`tags` argument is also passed to the generated `test_suite` target . 1257 """ 1258 tests = [] 1259 1260 for src in srcs: 1261 if not src.endswith(".rs"): 1262 fail("srcs should have `.rs` extensions") 1263 1264 # Prefixed with `name` to allow parameterization with macros 1265 # The test name should not end with `.rs` 1266 test_name = name + "_" + src[:-3] 1267 rust_test( 1268 name = test_name, 1269 srcs = [src], 1270 **kwargs 1271 ) 1272 tests.append(test_name) 1273 1274 native.test_suite( 1275 name = name, 1276 tests = tests, 1277 tags = kwargs.get("tags", None), 1278 )