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