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