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