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