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