fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
4e5fac59
0.9.0
1# Copyright 2018 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"""Functionality for constructing actions that invoke the Rust compiler""" 16 17load ( 18"@bazel_tools//tools/build_defs/cc:action_names.bzl" , 19"CPP_LINK_EXECUTABLE_ACTION_NAME" , 20) 21load ( "//rust/private:common.bzl" , "rust_common" ) 22load ( "//rust/private:providers.bzl" , _BuildInfo = "BuildInfo" ) 23load ( "//rust/private:stamp.bzl" , "is_stamping_enabled" ) 24load ( 25"//rust/private:utils.bzl" , 26"abs" , 27"expand_dict_value_locations" , 28"expand_list_element_locations" , 29"find_cc_toolchain" , 30"get_lib_name" , 31"get_preferred_artifact" , 32"is_exec_configuration" , 33"make_static_lib_symlink" , 34"relativize" , 35) 36 37BuildInfo = _BuildInfo 38 39AliasableDepInfo = provider ( 40doc = "A provider mapping an alias name to a Crate's information." , 41fields = { 42"dep" : "CrateInfo" , 43"name" : "str" , 44}, 45) 46 47_error_format_values = [ "human" , "json" , "short" ] 48 49ErrorFormatInfo = provider ( 50doc = "Set the --error-format flag for all rustc invocations" , 51fields = { "error_format" : "(string) [" + ", " . join ( _error_format_values ) + "]" }, 52) 53 54ExtraRustcFlagsInfo = provider ( 55doc = "Pass each value as an additional flag to non-exec rustc invocations" , 56fields = { "extra_rustc_flags" : "List[string] Extra flags to pass to rustc in non-exec configuration" }, 57) 58 59ExtraExecRustcFlagsInfo = provider ( 60doc = "Pass each value as an additional flag to exec rustc invocations" , 61fields = { "extra_exec_rustc_flags" : "List[string] Extra flags to pass to rustc in exec configuration" }, 62) 63 64IsProcMacroDepInfo = provider ( 65doc = "Records if this is a transitive dependency of a proc-macro." , 66fields = { "is_proc_macro_dep" : "Boolean" }, 67) 68 69def _is_proc_macro_dep_impl ( ctx ): 70return IsProcMacroDepInfo ( is_proc_macro_dep = ctx . build_setting_value ) 71 72is_proc_macro_dep = rule ( 73doc = "Records if this is a transitive dependency of a proc-macro." , 74implementation = _is_proc_macro_dep_impl , 75build_setting = config . bool ( flag = True ), 76) 77 78IsProcMacroDepEnabledInfo = provider ( 79doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro." , 80fields = { "enabled" : "Boolean" }, 81) 82 83def _is_proc_macro_dep_enabled_impl ( ctx ): 84return IsProcMacroDepEnabledInfo ( enabled = ctx . build_setting_value ) 85 86is_proc_macro_dep_enabled = rule ( 87doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro." , 88implementation = _is_proc_macro_dep_enabled_impl , 89build_setting = config . bool ( flag = True ), 90) 91 92def _get_rustc_env ( attr , toolchain , crate_name ): 93"""Gathers rustc environment variables 94 95Args: 96attr (struct): The current target's attributes 97toolchain (rust_toolchain): The current target's rust toolchain context 98crate_name (str): The name of the crate to be compiled 99 100Returns: 101dict: Rustc environment variables 102""" 103version = attr . version if hasattr ( attr , "version" ) else "0.0.0" 104major , minor , patch = version . split ( "." , 2 ) 105if "-" in patch : 106patch , pre = patch . split ( "-" , 1 ) 107else : 108pre = "" 109result = { 110"CARGO_CFG_TARGET_ARCH" : toolchain . target_arch , 111"CARGO_CFG_TARGET_OS" : toolchain . os , 112"CARGO_CRATE_NAME" : crate_name , 113"CARGO_PKG_AUTHORS" : "" , 114"CARGO_PKG_DESCRIPTION" : "" , 115"CARGO_PKG_HOMEPAGE" : "" , 116"CARGO_PKG_NAME" : attr . name , 117"CARGO_PKG_VERSION" : version , 118"CARGO_PKG_VERSION_MAJOR" : major , 119"CARGO_PKG_VERSION_MINOR" : minor , 120"CARGO_PKG_VERSION_PATCH" : patch , 121"CARGO_PKG_VERSION_PRE" : pre , 122} 123if hasattr ( attr , "_is_proc_macro_dep_enabled" ) and attr . _is_proc_macro_dep_enabled [ IsProcMacroDepEnabledInfo ]. enabled : 124is_proc_macro_dep = "0" 125if hasattr ( attr , "_is_proc_macro_dep" ) and attr . _is_proc_macro_dep [ IsProcMacroDepInfo ]. is_proc_macro_dep : 126is_proc_macro_dep = "1" 127result [ "BAZEL_RULES_RUST_IS_PROC_MACRO_DEP" ] = is_proc_macro_dep 128return result 129 130def get_compilation_mode_opts ( ctx , toolchain ): 131"""Gathers rustc flags for the current compilation mode (opt/debug) 132 133Args: 134ctx (ctx): The current rule's context object 135toolchain (rust_toolchain): The current rule's `rust_toolchain` 136 137Returns: 138struct: See `_rust_toolchain_impl` for more details 139""" 140comp_mode = ctx . var [ "COMPILATION_MODE" ] 141if not comp_mode in toolchain . compilation_mode_opts : 142fail ( "Unrecognized compilation mode {} for toolchain." . format ( comp_mode )) 143 144return toolchain . compilation_mode_opts [ comp_mode ] 145 146def _are_linkstamps_supported ( feature_configuration , has_grep_includes ): 147# Are linkstamps supported by the C++ toolchain? 148return ( cc_common . is_enabled ( feature_configuration = feature_configuration , feature_name = "linkstamps" ) and 149# Is Bazel recent enough to support Starlark linkstamps? 150hasattr ( cc_common , "register_linkstamp_compile_action" ) and 151# The current rule doesn't define _grep_includes attribute; this 152# attribute is required for compiling linkstamps. 153has_grep_includes ) 154 155def _should_use_pic ( cc_toolchain , feature_configuration , crate_type ): 156"""Whether or not [PIC][pic] should be enabled 157 158[pic]: https://en.wikipedia.org/wiki/Position-independent_code 159 160Args: 161cc_toolchain (CcToolchainInfo): The current `cc_toolchain`. 162feature_configuration (FeatureConfiguration): Feature configuration to be queried. 163crate_type (str): A Rust target's crate type. 164 165Returns: 166bool: Whether or not [PIC][pic] should be enabled. 167""" 168if crate_type in ( "cdylib" , "dylib" ): 169return cc_toolchain . needs_pic_for_dynamic_libraries ( feature_configuration = feature_configuration ) 170return False 171 172def _is_proc_macro ( crate_info ): 173return "proc-macro" in ( crate_info . type , crate_info . wrapped_crate_type ) 174 175def collect_deps ( 176deps , 177proc_macro_deps , 178aliases , 179are_linkstamps_supported = False ): 180"""Walks through dependencies and collects the transitive dependencies. 181 182Args: 183deps (list): The deps from ctx.attr.deps. 184proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps. 185aliases (dict): A dict mapping aliased targets to their actual Crate information. 186are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps.. 187 188Returns: 189tuple: Returns a tuple of: 190DepInfo, 191BuildInfo, 192linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries. 193 194""" 195direct_crates = [] 196transitive_crates = [] 197transitive_noncrates = [] 198transitive_build_infos = [] 199transitive_link_search_paths = [] 200build_info = None 201linkstamps = [] 202transitive_crate_outputs = [] 203transitive_metadata_outputs = [] 204 205aliases = { k . label : v for k , v in aliases . items ()} 206for dep in depset ( transitive = [ deps , proc_macro_deps ]). to_list (): 207( crate_info , dep_info ) = _get_crate_and_dep_info ( dep ) 208cc_info = _get_cc_info ( dep ) 209dep_build_info = _get_build_info ( dep ) 210 211if cc_info and are_linkstamps_supported : 212linkstamps . append ( cc_info . linking_context . linkstamps ()) 213 214if crate_info : 215# This dependency is a rust_library 216 217# When crate_info.owner is set, we use it. When the dep type is Target we get the 218# label from dep.label 219owner = getattr ( crate_info , "owner" , dep . label if type ( dep ) == "Target" else None ) 220 221direct_crates . append ( AliasableDepInfo ( 222name = aliases . get ( owner , crate_info . name ), 223dep = crate_info , 224)) 225 226transitive_crates . append ( 227depset ( 228[ crate_info ], 229transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_crates ], 230), 231) 232 233# If this dependency produces metadata, add it to the metadata outputs. 234# If it doesn't (for example a custom library that exports crate_info), 235# we depend on crate_info.output. 236depend_on = crate_info . metadata 237if not crate_info . metadata : 238depend_on = crate_info . output 239 240# If this dependency is a proc_macro, it still can be used for lib crates 241# that produce metadata. 242# In that case, we don't depend on its metadata dependencies. 243transitive_metadata_outputs . append ( 244depset ( 245[ depend_on ], 246transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_metadata_outputs ], 247), 248) 249 250transitive_crate_outputs . append ( 251depset ( 252[ crate_info . output ], 253transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_crate_outputs ], 254), 255) 256 257if "proc-macro" not in [ crate_info . type , crate_info . wrapped_crate_type ]: 258transitive_noncrates . append ( dep_info . transitive_noncrates ) 259transitive_link_search_paths . append ( dep_info . link_search_path_files ) 260 261transitive_build_infos . append ( dep_info . transitive_build_infos ) 262 263elif cc_info : 264# This dependency is a cc_library 265transitive_noncrates . append ( cc_info . linking_context . linker_inputs ) 266elif dep_build_info : 267if build_info : 268fail ( "Several deps are providing build information, " + 269"only one is allowed in the dependencies" ) 270build_info = dep_build_info 271transitive_build_infos . append ( depset ([ build_info ])) 272transitive_link_search_paths . append ( depset ([ build_info . link_search_paths ])) 273else : 274fail ( "rust targets can only depend on rust_library, rust_*_library or cc_library " + 275"targets." ) 276 277transitive_crates_depset = depset ( transitive = transitive_crates ) 278 279return ( 280rust_common . dep_info ( 281direct_crates = depset ( direct_crates ), 282transitive_crates = transitive_crates_depset , 283transitive_noncrates = depset ( 284transitive = transitive_noncrates , 285order = "topological" , #dylib link flag ordering matters . 286), 287transitive_crate_outputs = depset ( transitive = transitive_crate_outputs ), 288transitive_metadata_outputs = depset ( transitive = transitive_metadata_outputs ), 289transitive_build_infos = depset ( transitive = transitive_build_infos ), 290link_search_path_files = depset ( transitive = transitive_link_search_paths ), 291dep_env = build_info . dep_env if build_info else None , 292), 293build_info , 294depset ( transitive = linkstamps ), 295) 296 297def _collect_libs_from_linker_inputs ( linker_inputs , use_pic ): 298# TODO: We could let the user choose how to link, instead of always preferring to link static libraries. 299return [ 300get_preferred_artifact ( lib , use_pic ) 301for li in linker_inputs 302for lib in li . libraries 303] 304 305def _get_crate_and_dep_info ( dep ): 306if type ( dep ) == "Target" and rust_common . crate_info in dep : 307return ( dep [ rust_common . crate_info ], dep [ rust_common . dep_info ]) 308elif type ( dep ) == "struct" and hasattr ( dep , "crate_info" ): 309return ( dep . crate_info , dep . dep_info ) 310return ( None , None ) 311 312def _get_cc_info ( dep ): 313if type ( dep ) == "Target" and CcInfo in dep : 314return dep [ CcInfo ] 315elif type ( dep ) == "struct" and hasattr ( dep , "cc_info" ): 316return dep . cc_info 317return None 318 319def _get_build_info ( dep ): 320if type ( dep ) == "Target" and BuildInfo in dep : 321return dep [ BuildInfo ] 322elif type ( dep ) == "struct" and hasattr ( dep , "build_info" ): 323return dep . build_info 324return None 325 326def get_cc_user_link_flags ( ctx ): 327"""Get the current target's linkopt flags 328 329Args: 330ctx (ctx): The current rule's context object 331 332Returns: 333depset: The flags passed to Bazel by --linkopt option. 334""" 335return ctx . fragments . cpp . linkopts 336 337def get_linker_and_args ( ctx , attr , cc_toolchain , feature_configuration , rpaths ): 338"""Gathers cc_common linker information 339 340Args: 341ctx (ctx): The current target's context object 342attr (struct): Attributes to use in gathering linker args 343cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables. 344feature_configuration (FeatureConfiguration): Feature configuration to be queried. 345rpaths (depset): Depset of directories where loader will look for libraries at runtime. 346 347 348Returns: 349tuple: A tuple of the following items: 350- (str): The tool path for given action. 351- (sequence): A flattened command line flags for given action. 352- (dict): Environment variables to be set for given action. 353""" 354user_link_flags = get_cc_user_link_flags ( ctx ) 355 356# Add linkopt's from dependencies. This includes linkopts from transitive 357# dependencies since they get merged up. 358for dep in getattr ( attr , "deps" , []): 359if CcInfo in dep and dep [ CcInfo ]. linking_context : 360for linker_input in dep [ CcInfo ]. linking_context . linker_inputs . to_list (): 361for flag in linker_input . user_link_flags : 362user_link_flags . append ( flag ) 363link_variables = cc_common . create_link_variables ( 364feature_configuration = feature_configuration , 365cc_toolchain = cc_toolchain , 366is_linking_dynamic_library = False , 367runtime_library_search_directories = rpaths , 368user_link_flags = user_link_flags , 369) 370link_args = cc_common . get_memory_inefficient_command_line ( 371feature_configuration = feature_configuration , 372action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 373variables = link_variables , 374) 375link_env = cc_common . get_environment_variables ( 376feature_configuration = feature_configuration , 377action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 378variables = link_variables , 379) 380ld = cc_common . get_tool_for_action ( 381feature_configuration = feature_configuration , 382action_name = CPP_LINK_EXECUTABLE_ACTION_NAME , 383) 384 385return ld , link_args , link_env 386 387def _process_build_scripts ( 388build_info , 389dep_info , 390compile_inputs ): 391"""Gathers the outputs from a target's `cargo_build_script` action. 392 393Args: 394build_info (BuildInfo): The target Build's dependency info. 395dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 396compile_inputs (depset): A set of all files that will participate in the build. 397 398Returns: 399tuple: A tuple: A tuple of the following items: 400- (depset[File]): A list of all build info `OUT_DIR` File objects 401- (str): The `OUT_DIR` of the current build info 402- (File): An optional path to a generated environment file from a `cargo_build_script` target 403- (depset[File]): All direct and transitive build flags from the current build info. 404""" 405extra_inputs , out_dir , build_env_file , build_flags_files = _create_extra_input_args ( build_info , dep_info ) 406compile_inputs = depset ( transitive = [ extra_inputs , compile_inputs ]) 407return compile_inputs , out_dir , build_env_file , build_flags_files 408 409def _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , lib ): 410"""Constructs a disambiguating symlink for a library dependency. 411 412Args: 413actions (Actions): The rule's context actions object. 414toolchain: The Rust toolchain object. 415crate_info (CrateInfo): The target crate's info. 416lib (File): The library to symlink to. 417 418Returns: 419(File): The disambiguating symlink for the library. 420""" 421# FIXME: Once the relative order part of the native-link-modifiers rustc 422# feature is stable, we should be able to eliminate the need to construct 423# symlinks by passing the full paths to the libraries. 424# https://github.com/rust-lang/rust/issues/81490. 425 426# Take the absolute value of hash() since it could be negative. 427path_hash = abs ( hash ( lib . path )) 428lib_name = get_lib_name ( lib , for_windows = toolchain . os . startswith ( "windows" )) 429 430prefix = "lib" 431extension = ".a" 432if toolchain . os . startswith ( "windows" ): 433prefix = "" 434extension = ".lib" 435 436# Ensure the symlink follows the lib<name>.a pattern on Unix-like platforms 437# or <name>.lib on Windows. 438# Add a hash of the original library path to disambiguate libraries with the same basename. 439symlink_name = "{}{}-{}{}" . format ( prefix , lib_name , path_hash , extension ) 440 441# Add the symlink to a target crate-specific _ambiguous_libs/ subfolder, 442# to avoid possible collisions with sibling crates that may depend on the 443# same ambiguous libraries. 444symlink = actions . declare_file ( "_ambiguous_libs/" + crate_info . output . basename + "/" + symlink_name ) 445actions . symlink ( 446output = symlink , 447target_file = lib , 448progress_message = "Creating symlink to ambiguous lib: {}" . format ( lib . path ), 449) 450return symlink 451 452def _disambiguate_libs ( actions , toolchain , crate_info , dep_info , use_pic ): 453"""Constructs disambiguating symlinks for ambiguous library dependencies. 454 455The symlinks are all created in a _ambiguous_libs/ subfolder specific to 456the target crate to avoid possible collisions with sibling crates that may 457depend on the same ambiguous libraries. 458 459Args: 460actions (Actions): The rule's context actions object. 461toolchain: The Rust toolchain object. 462crate_info (CrateInfo): The target crate's info. 463dep_info: (DepInfo): The target crate's dependency info. 464use_pic: (boolean): Whether the build should use PIC. 465 466Returns: 467dict[String, File]: A mapping from ambiguous library paths to their 468disambiguating symlink. 469""" 470# FIXME: Once the relative order part of the native-link-modifiers rustc 471# feature is stable, we should be able to eliminate the need to construct 472# symlinks by passing the full paths to the libraries. 473# https://github.com/rust-lang/rust/issues/81490. 474 475# A dictionary from file paths of ambiguous libraries to the corresponding 476# symlink. 477ambiguous_libs = {} 478 479# A dictionary maintaining a mapping from preferred library name to the 480# last visited artifact with that name. 481visited_libs = {} 482for link_input in dep_info . transitive_noncrates . to_list (): 483for lib in link_input . libraries : 484# FIXME: Dynamic libs are not disambiguated right now, there are 485# cases where those have a non-standard name with version (e.g., 486# //test/unit/versioned_libs). We hope that the link modifiers 487# stabilization will come before we need to make this work. 488if _is_dylib ( lib ): 489 continue 490artifact = get_preferred_artifact ( lib , use_pic ) 491name = get_lib_name ( artifact , for_windows = toolchain . os . startswith ( "windows" )) 492 493# On Linux-like platforms, normally library base names start with 494# `lib`, following the pattern `lib[name].(a|lo)` and we pass 495# -lstatic=name. 496# On Windows, the base name looks like `name.lib` and we pass 497# -lstatic=name. 498# FIXME: Under the native-link-modifiers unstable rustc feature, 499# we could use -lstatic:+verbatim instead. 500needs_symlink_to_standardize_name = ( 501( toolchain . os . startswith ( "linux" ) or toolchain . os . startswith ( "mac" ) or toolchain . os . startswith ( "darwin" )) and 502artifact . basename . endswith ( ".a" ) and not artifact . basename . startswith ( "lib" ) 503) or ( 504toolchain . os . startswith ( "windows" ) and not artifact . basename . endswith ( ".lib" ) 505) 506 507# Detect cases where we need to disambiguate library dependencies 508# by constructing symlinks. 509if ( 510needs_symlink_to_standardize_name or 511# We have multiple libraries with the same name. 512( name in visited_libs and visited_libs [ name ]. path != artifact . path ) 513): 514# Disambiguate the previously visited library (if we just detected 515# that it is ambiguous) and the current library. 516if name in visited_libs : 517old_path = visited_libs [ name ]. path 518if old_path not in ambiguous_libs : 519ambiguous_libs [ old_path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , visited_libs [ name ]) 520ambiguous_libs [ artifact . path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , artifact ) 521 522visited_libs [ name ] = artifact 523return ambiguous_libs 524 525def _depend_on_metadata ( crate_info , force_depend_on_objects ): 526"""Determines if we can depend on metadata for this crate. 527 528By default (when pipelining is disabled or when the crate type needs to link against 529objects) we depend on the set of object files (.rlib). 530When pipelining is enabled and the crate type supports depending on metadata, 531we depend on metadata files only (.rmeta). 532In some rare cases, even if both of those conditions are true, we still want to 533depend on objects. This is what force_depend_on_objects is. 534 535Args: 536crate_info (CrateInfo): The Crate to determine this for. 537force_depend_on_objects (bool): if set we will not depend on metadata. 538 539Returns: 540Whether we can depend on metadata for this crate. 541""" 542if force_depend_on_objects : 543return False 544 545return crate_info . type in ( "rlib" , "lib" ) 546 547def collect_inputs ( 548ctx , 549file , 550files , 551linkstamps , 552toolchain , 553cc_toolchain , 554feature_configuration , 555crate_info , 556dep_info , 557build_info , 558stamp = False , 559force_depend_on_objects = False ): 560"""Gather's the inputs and required input information for a rustc action 561 562Args: 563ctx (ctx): The rule's context object. 564file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 565files (list): A list of all inputs (`ctx.files`). 566linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries. 567toolchain (rust_toolchain): The current `rust_toolchain`. 568cc_toolchain (CcToolchainInfo): The current `cc_toolchain`. 569feature_configuration (FeatureConfiguration): Feature configuration to be queried. 570crate_info (CrateInfo): The Crate information of the crate to process build scripts for. 571dep_info (DepInfo): The target Crate's dependency information. 572build_info (BuildInfo): The target Crate's build settings. 573stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 574https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 575force_depend_on_objects (bool, optional): Forces dependencies of this rule to be objects rather than 576metadata, even for libraries. This is used in rustdoc tests. 577 578Returns: 579tuple: A tuple: A tuple of the following items: 580- (list): A list of all build info `OUT_DIR` File objects 581- (str): The `OUT_DIR` of the current build info 582- (File): An optional path to a generated environment file from a `cargo_build_script` target 583- (depset[File]): All direct and transitive build flag files from the current build info 584- (list[File]): Linkstamp outputs 585- (dict[String, File]): Ambiguous libs, see `_disambiguate_libs`. 586""" 587linker_script = getattr ( file , "linker_script" ) if hasattr ( file , "linker_script" ) else None 588 589linker_depset = cc_toolchain . all_files 590 591use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type ) 592 593# Pass linker inputs only for linking-like actions, not for example where 594# the output is rlib. This avoids quadratic behavior where transitive noncrates are 595# flattened on each transitive rust_library dependency. 596additional_transitive_inputs = [] 597ambiguous_libs = {} 598if crate_info . type in ( "staticlib" , "proc-macro" ): 599additional_transitive_inputs = _collect_libs_from_linker_inputs ( 600dep_info . transitive_noncrates . to_list (), 601use_pic , 602) 603elif crate_info . type in ( "bin" , "dylib" , "cdylib" ): 604linker_inputs = dep_info . transitive_noncrates . to_list () 605ambiguous_libs = _disambiguate_libs ( ctx . actions , toolchain , crate_info , dep_info , use_pic ) 606additional_transitive_inputs = _collect_libs_from_linker_inputs ( linker_inputs , use_pic ) + [ 607additional_input 608for linker_input in linker_inputs 609for additional_input in linker_input . additional_inputs 610] + ambiguous_libs . values () 611 612# Compute linkstamps. Use the inputs of the binary as inputs to the 613# linkstamp action to ensure linkstamps are rebuilt whenever binary inputs 614# change. 615linkstamp_outs = [] 616 617transitive_crate_outputs = dep_info . transitive_crate_outputs 618if _depend_on_metadata ( crate_info , force_depend_on_objects ): 619transitive_crate_outputs = dep_info . transitive_metadata_outputs 620 621nolinkstamp_compile_inputs = depset ( 622getattr ( files , "data" , []) + 623([ build_info . rustc_env , build_info . flags ] if build_info else []) + 624([ toolchain . target_json ] if toolchain . target_json else []) + 625([] if linker_script == None else [ linker_script ]), 626transitive = [ 627linker_depset , 628crate_info . srcs , 629transitive_crate_outputs , 630depset ( additional_transitive_inputs ), 631crate_info . compile_data , 632toolchain . all_files , 633], 634) 635 636if crate_info . type in ( "bin" , "cdylib" ): 637# There is no other way to register an action for each member of a depset than 638# flattening the depset as of 2021-10-12. Luckily, usually there is only one linkstamp 639# in a build, and we only flatten the list on binary targets that perform transitive linking, 640# so it's extremely unlikely that this call to `to_list()` will ever be a performance 641# problem. 642for linkstamp in linkstamps . to_list (): 643# The linkstamp output path is based on the binary crate 644# name and the input linkstamp path. This is to disambiguate 645# the linkstamp outputs produced by multiple binary crates 646# that depend on the same linkstamp. We use the same pattern 647# for the output name as the one used by native cc rules. 648out_name = "_objs/" + crate_info . output . basename + "/" + linkstamp . file (). path [: - len ( linkstamp . file (). extension )] + "o" 649linkstamp_out = ctx . actions . declare_file ( out_name ) 650linkstamp_outs . append ( linkstamp_out ) 651cc_common . register_linkstamp_compile_action ( 652actions = ctx . actions , 653cc_toolchain = cc_toolchain , 654feature_configuration = feature_configuration , 655grep_includes = ctx . file . _grep_includes , 656source_file = linkstamp . file (), 657output_file = linkstamp_out , 658compilation_inputs = linkstamp . hdrs (), 659inputs_for_validation = nolinkstamp_compile_inputs , 660label_replacement = str ( ctx . label ), 661output_replacement = crate_info . output . path , 662) 663 664# If stamping is enabled include the volatile and stable status info file 665stamp_info = [ ctx . version_file , ctx . info_file ] if stamp else [] 666 667compile_inputs = depset ( 668linkstamp_outs + stamp_info , 669transitive = [ 670nolinkstamp_compile_inputs , 671], 672) 673 674build_env_files = getattr ( files , "rustc_env_files" , []) 675compile_inputs , out_dir , build_env_file , build_flags_files = _process_build_scripts ( build_info , dep_info , compile_inputs ) 676if build_env_file : 677build_env_files = [ f for f in build_env_files ] + [ build_env_file ] 678compile_inputs = depset ( build_env_files , transitive = [ compile_inputs ]) 679 680return compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs 681 682def construct_arguments ( 683ctx , 684attr , 685file , 686toolchain , 687tool_path , 688cc_toolchain , 689feature_configuration , 690crate_info , 691dep_info , 692linkstamp_outs , 693ambiguous_libs , 694output_hash , 695rust_flags , 696out_dir , 697build_env_files , 698build_flags_files , 699emit = [ "dep-info" , "link" ], 700force_all_deps_direct = False , 701force_link = False , 702stamp = False , 703remap_path_prefix = "." , 704use_json_output = False , 705build_metadata = False , 706force_depend_on_objects = False ): 707"""Builds an Args object containing common rustc flags 708 709Args: 710ctx (ctx): The rule's context object 711attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context. 712file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 713toolchain (rust_toolchain): The current target's `rust_toolchain` 714tool_path (str): Path to rustc 715cc_toolchain (CcToolchain): The CcToolchain for the current target. 716feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features. 717crate_info (CrateInfo): The CrateInfo provider of the target crate 718dep_info (DepInfo): The DepInfo provider of the target crate 719linkstamp_outs (list): Linkstamp outputs of native dependencies 720ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 721output_hash (str): The hashed path of the crate root 722rust_flags (list): Additional flags to pass to rustc 723out_dir (str): The path to the output directory for the target Crate. 724build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions. 725build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags 726emit (list): Values for the --emit flag to rustc. 727force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 728to the commandline as opposed to -L. 729force_link (bool, optional): Whether to add link flags to the command regardless of `emit`. 730stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 731https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 732remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to a falsey value, no prefix will be set. 733use_json_output (bool): Have rustc emit json and process_wrapper parse json messages to output rendered output. 734build_metadata (bool): Generate CLI arguments for building *only* .rmeta files. This requires use_json_output. 735force_depend_on_objects (bool): Force using `.rlib` object files instead of metadata (`.rmeta`) files even if they are available. 736 737Returns: 738tuple: A tuple of the following items 739- (struct): A struct of arguments used to run the `Rustc` action 740- process_wrapper_flags (Args): Arguments for the process wrapper 741- rustc_path (Args): Arguments for invoking rustc via the process wrapper 742- rustc_flags (Args): Rust flags for the Rust compiler 743- all (list): A list of all `Args` objects in the order listed above. 744This is to be passed to the `arguments` parameter of actions 745- (dict): Common rustc environment variables 746""" 747if build_metadata and not use_json_output : 748fail ( "build_metadata requires parse_json_output" ) 749 750output_dir = getattr ( crate_info . output , "dirname" , None ) 751linker_script = getattr ( file , "linker_script" , None ) 752 753env = _get_rustc_env ( attr , toolchain , crate_info . name ) 754 755# Wrapper args first 756process_wrapper_flags = ctx . actions . args () 757 758for build_env_file in build_env_files : 759process_wrapper_flags . add ( "--env-file" , build_env_file ) 760 761process_wrapper_flags . add_all ( build_flags_files , before_each = "--arg-file" ) 762 763# Certain rust build processes expect to find files from the environment 764# variable `$CARGO_MANIFEST_DIR`. Examples of this include pest, tera, 765# asakuma. 766# 767# The compiler and by extension proc-macros see the current working 768# directory as the Bazel exec root. This is what `$CARGO_MANIFEST_DIR` 769# would default to but is often the wrong value (e.g. if the source is in a 770# sub-package or if we are building something in an external repository). 771# Hence, we need to set `CARGO_MANIFEST_DIR` explicitly. 772# 773# Since we cannot get the `exec_root` from starlark, we cheat a little and 774# use `${pwd}` which resolves the `exec_root` at action execution time. 775process_wrapper_flags . add ( "--subst" , "pwd=${pwd}" ) 776 777# If stamping is enabled, enable the functionality in the process wrapper 778if stamp : 779process_wrapper_flags . add ( "--volatile-status-file" , ctx . version_file ) 780process_wrapper_flags . add ( "--stable-status-file" , ctx . info_file ) 781 782# Both ctx.label.workspace_root and ctx.label.package are relative paths 783# and either can be empty strings. Avoid trailing/double slashes in the path. 784components = "${{pwd}}/{}/{}" . format ( ctx . label . workspace_root , ctx . label . package ). split ( "/" ) 785env [ "CARGO_MANIFEST_DIR" ] = "/" . join ([ c for c in components if c ]) 786 787if out_dir != None : 788env [ "OUT_DIR" ] = "${pwd}/" + out_dir 789 790# Handle that the binary name and crate name may be different. 791# 792# If a target name contains a - then cargo (and rules_rust) will generate a 793# crate name with _ instead. Accordingly, rustc will generate a output 794# file (executable, or rlib, or whatever) with _ not -. But when cargo 795# puts a binary in the target/${config} directory, and sets environment 796# variables like `CARGO_BIN_EXE_${binary_name}` it will use the - version 797# not the _ version. So we rename the rustc-generated file (with _s) to 798# have -s if needed. 799emit_with_paths = emit 800if crate_info . type == "bin" and crate_info . output != None : 801generated_file = crate_info . name + toolchain . binary_ext 802src = "/" . join ([ crate_info . output . dirname , generated_file ]) 803dst = crate_info . output . path 804if src != dst : 805emit_with_paths = [( "link=" + dst if val == "link" else val ) for val in emit ] 806 807# Arguments for launching rustc from the process wrapper 808rustc_path = ctx . actions . args () 809rustc_path . add ( "--" ) 810rustc_path . add ( tool_path ) 811 812# Rustc arguments 813rustc_flags = ctx . actions . args () 814rustc_flags . set_param_file_format ( "multiline" ) 815rustc_flags . use_param_file ( "@%s" , use_always = False ) 816rustc_flags . add ( crate_info . root ) 817rustc_flags . add ( "--crate-name=" + crate_info . name ) 818rustc_flags . add ( "--crate-type=" + crate_info . type ) 819 820error_format = "human" 821if hasattr ( attr , "_error_format" ): 822error_format = attr . _error_format [ ErrorFormatInfo ]. error_format 823 824if use_json_output : 825# If --error-format was set to json, we just pass the output through 826# Otherwise process_wrapper uses the "rendered" field. 827process_wrapper_flags . add ( "--rustc-output-format" , "json" if error_format == "json" else "rendered" ) 828 829# Configure rustc json output by adding artifact notifications. 830# These will always be filtered out by process_wrapper and will be use to terminate 831# rustc when appropriate. 832json = [ "artifacts" ] 833if error_format == "short" : 834json . append ( "diagnostic-short" ) 835elif error_format == "human" and toolchain . os != "windows" : 836# If the os is not windows, we can get colorized output. 837json . append ( "diagnostic-rendered-ansi" ) 838 839rustc_flags . add ( "--json=" + "," . join ( json )) 840 841error_format = "json" 842 843if build_metadata : 844# Configure process_wrapper to terminate rustc when metadata are emitted 845process_wrapper_flags . add ( "--rustc-quit-on-rmeta" , "true" ) 846 847rustc_flags . add ( "--error-format=" + error_format ) 848 849# Mangle symbols to disambiguate crates with the same name. This could 850# happen only for non-final artifacts where we compute an output_hash, 851# e.g., rust_library. 852# 853# For "final" artifacts and ones intended for distribution outside of 854# Bazel, such as rust_binary, rust_static_library and rust_shared_library, 855# where output_hash is None we don't need to add these flags. 856if output_hash : 857extra_filename = "-" + output_hash 858rustc_flags . add ( "--codegen=metadata=" + extra_filename ) 859rustc_flags . add ( "--codegen=extra-filename=" + extra_filename ) 860 861if output_dir : 862rustc_flags . add ( "--out-dir=" + output_dir ) 863 864compilation_mode = get_compilation_mode_opts ( ctx , toolchain ) 865rustc_flags . add ( "--codegen=opt-level=" + compilation_mode . opt_level ) 866rustc_flags . add ( "--codegen=debuginfo=" + compilation_mode . debug_info ) 867 868# For determinism to help with build distribution and such 869if remap_path_prefix : 870rustc_flags . add ( "--remap-path-prefix=${{pwd}}={}" . format ( remap_path_prefix )) 871 872if emit : 873rustc_flags . add ( "--emit=" + "," . join ( emit_with_paths )) 874if error_format != "json" : 875# Color is not compatible with json output. 876rustc_flags . add ( "--color=always" ) 877rustc_flags . add ( "--target=" + toolchain . target_flag_value ) 878if hasattr ( attr , "crate_features" ): 879rustc_flags . add_all ( getattr ( attr , "crate_features" ), before_each = "--cfg" , format_each = 'feature="%s"' ) 880if linker_script : 881rustc_flags . add ( linker_script . path , format = "--codegen=link-arg=-T%s" ) 882 883# Gets the paths to the folders containing the standard library (or libcore) 884rust_std_paths = toolchain . rust_std_paths . to_list () 885 886# Tell Rustc where to find the standard library 887rustc_flags . add_all ( rust_std_paths , before_each = "-L" , format_each = "%s" ) 888rustc_flags . add_all ( rust_flags ) 889 890# Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681 891data_paths = depset ( direct = getattr ( attr , "data" , []) + getattr ( attr , "compile_data" , [])). to_list () 892 893rustc_flags . add_all ( 894expand_list_element_locations ( 895ctx , 896getattr ( attr , "rustc_flags" , []), 897data_paths , 898), 899) 900add_edition_flags ( rustc_flags , crate_info ) 901 902# Link! 903if ( "link" in emit and crate_info . type not in [ "rlib" , "lib" ]) or force_link : 904# Rust's built-in linker can handle linking wasm files. We don't want to attempt to use the cc 905# linker since it won't understand. 906if toolchain . target_arch != "wasm32" : 907if output_dir : 908use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type ) 909rpaths = _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ) 910else : 911rpaths = depset ([]) 912ld , link_args , link_env = get_linker_and_args ( ctx , attr , cc_toolchain , feature_configuration , rpaths ) 913env . update ( link_env ) 914rustc_flags . add ( "--codegen=linker=" + ld ) 915rustc_flags . add_joined ( "--codegen" , link_args , join_with = " " , format_joined = "link-args=%s" ) 916 917_add_native_link_flags ( rustc_flags , dep_info , linkstamp_outs , ambiguous_libs , crate_info . type , toolchain , cc_toolchain , feature_configuration ) 918 919use_metadata = _depend_on_metadata ( crate_info , force_depend_on_objects ) 920 921# These always need to be added, even if not linking this crate. 922add_crate_link_flags ( rustc_flags , dep_info , force_all_deps_direct , use_metadata ) 923 924needs_extern_proc_macro_flag = _is_proc_macro ( crate_info ) and crate_info . edition != "2015" 925if needs_extern_proc_macro_flag : 926rustc_flags . add ( "--extern" ) 927rustc_flags . add ( "proc_macro" ) 928 929if toolchain . llvm_cov and ctx . configuration . coverage_enabled : 930rustc_flags . add ( "--codegen=instrument-coverage" ) 931 932# Make bin crate data deps available to tests. 933for data in getattr ( attr , "data" , []): 934if rust_common . crate_info in data : 935dep_crate_info = data [ rust_common . crate_info ] 936if dep_crate_info . type == "bin" : 937# Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists 938env_basename = dep_crate_info . output . basename [: - ( 1 + len ( dep_crate_info . output . extension ))] if len ( dep_crate_info . output . extension ) > 0 else dep_crate_info . output . basename 939env [ "CARGO_BIN_EXE_" + env_basename ] = dep_crate_info . output . short_path 940 941# Add environment variables from the Rust toolchain. 942env . update ( toolchain . env ) 943 944# Update environment with user provided variables. 945env . update ( expand_dict_value_locations ( 946ctx , 947crate_info . rustc_env , 948data_paths , 949)) 950 951# Ensure the sysroot is set for the target platform 952env [ "SYSROOT" ] = toolchain . sysroot 953 954if toolchain . _rename_first_party_crates : 955env [ "RULES_RUST_THIRD_PARTY_DIR" ] = toolchain . _third_party_dir 956 957# extra_rustc_flags apply to the target configuration, not the exec configuration. 958if hasattr ( ctx . attr , "_extra_rustc_flags" ) and not is_exec_configuration ( ctx ): 959rustc_flags . add_all ( ctx . attr . _extra_rustc_flags [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 960 961if hasattr ( ctx . attr , "_extra_rustc_flag" ) and not is_exec_configuration ( ctx ): 962rustc_flags . add_all ( ctx . attr . _extra_rustc_flag [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 963 964if hasattr ( ctx . attr , "_extra_exec_rustc_flags" ) and is_exec_configuration ( ctx ): 965rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flags [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 966 967if hasattr ( ctx . attr , "_extra_exec_rustc_flag" ) and is_exec_configuration ( ctx ): 968rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flag [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 969 970# Create a struct which keeps the arguments separate so each may be tuned or 971# replaced where necessary 972args = struct ( 973process_wrapper_flags = process_wrapper_flags , 974rustc_path = rustc_path , 975rustc_flags = rustc_flags , 976all = [ process_wrapper_flags , rustc_path , rustc_flags ], 977) 978 979return args , env 980 981def rustc_compile_action ( 982ctx , 983attr , 984toolchain , 985crate_info , 986output_hash = None , 987rust_flags = [], 988force_all_deps_direct = False ): 989"""Create and run a rustc compile action based on the current rule's attributes 990 991Args: 992ctx (ctx): The rule's context object 993attr (struct): Attributes to use for the rust compile action 994toolchain (rust_toolchain): The current `rust_toolchain` 995crate_info (CrateInfo): The CrateInfo provider for the current target. 996output_hash (str, optional): The hashed path of the crate root. Defaults to None. 997rust_flags (list, optional): Additional flags to pass to rustc. Defaults to []. 998force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 999to the commandline as opposed to -L. 1000 1001Returns: 1002list: A list of the following providers: 1003- (CrateInfo): info for the crate we just built; same as `crate_info` parameter. 1004- (DepInfo): The transitive dependencies of this crate. 1005- (DefaultInfo): The output file for this crate, and its runfiles. 1006""" 1007build_metadata = getattr ( crate_info , "metadata" , None ) 1008 1009cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 1010 1011dep_info , build_info , linkstamps = collect_deps ( 1012deps = crate_info . deps , 1013proc_macro_deps = crate_info . proc_macro_deps , 1014aliases = crate_info . aliases , 1015are_linkstamps_supported = _are_linkstamps_supported ( 1016feature_configuration = feature_configuration , 1017has_grep_includes = hasattr ( ctx . attr , "_grep_includes" ), 1018), 1019) 1020 1021# Determine if the build is currently running with --stamp 1022stamp = is_stamping_enabled ( attr ) 1023 1024compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 1025ctx = ctx , 1026file = ctx . file , 1027files = ctx . files , 1028linkstamps = linkstamps , 1029toolchain = toolchain , 1030cc_toolchain = cc_toolchain , 1031feature_configuration = feature_configuration , 1032crate_info = crate_info , 1033dep_info = dep_info , 1034build_info = build_info , 1035stamp = stamp , 1036) 1037 1038# If we build metadata, we need to keep the command line of the two invocations 1039# (rlib and rmeta) as similar as possible, otherwise rustc rejects the rmeta as 1040# a candidate. 1041# Because of that we need to add emit=metadata to both the rlib and rmeta invocation. 1042emit = [ "dep-info" , "link" ] 1043if build_metadata : 1044emit . append ( "metadata" ) 1045 1046args , env_from_args = construct_arguments ( 1047ctx = ctx , 1048attr = attr , 1049file = ctx . file , 1050toolchain = toolchain , 1051tool_path = toolchain . rustc . path , 1052cc_toolchain = cc_toolchain , 1053emit = emit , 1054feature_configuration = feature_configuration , 1055crate_info = crate_info , 1056dep_info = dep_info , 1057linkstamp_outs = linkstamp_outs , 1058ambiguous_libs = ambiguous_libs , 1059output_hash = output_hash , 1060rust_flags = rust_flags , 1061out_dir = out_dir , 1062build_env_files = build_env_files , 1063build_flags_files = build_flags_files , 1064force_all_deps_direct = force_all_deps_direct , 1065stamp = stamp , 1066use_json_output = bool ( build_metadata ), 1067) 1068 1069args_metadata = None 1070if build_metadata : 1071args_metadata , _ = construct_arguments ( 1072ctx = ctx , 1073attr = attr , 1074file = ctx . file , 1075toolchain = toolchain , 1076tool_path = toolchain . rustc . path , 1077cc_toolchain = cc_toolchain , 1078emit = emit , 1079feature_configuration = feature_configuration , 1080crate_info = crate_info , 1081dep_info = dep_info , 1082linkstamp_outs = linkstamp_outs , 1083ambiguous_libs = ambiguous_libs , 1084output_hash = output_hash , 1085rust_flags = rust_flags , 1086out_dir = out_dir , 1087build_env_files = build_env_files , 1088build_flags_files = build_flags_files , 1089force_all_deps_direct = force_all_deps_direct , 1090stamp = stamp , 1091use_json_output = True , 1092build_metadata = True , 1093) 1094 1095env = dict ( ctx . configuration . default_shell_env ) 1096env . update ( env_from_args ) 1097 1098if hasattr ( attr , "version" ) and attr . version != "0.0.0" : 1099formatted_version = " v{}" . format ( attr . version ) 1100else : 1101formatted_version = "" 1102 1103outputs = [ crate_info . output ] 1104 1105# For a cdylib that might be added as a dependency to a cc_* target on Windows, it is important to include the 1106# interface library that rustc generates in the output files. 1107interface_library = None 1108if toolchain . os == "windows" and crate_info . type == "cdylib" : 1109# Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc 1110# expects (see https://github.com/rust-lang/rust/pull/29520 for more context). 1111interface_library = ctx . actions . declare_file ( crate_info . output . basename + ".lib" , sibling = crate_info . output ) 1112outputs . append ( interface_library ) 1113 1114# The action might generate extra output that we don't want to include in the `DefaultInfo` files. 1115action_outputs = list ( outputs ) 1116 1117# Rustc generates a pdb file (on Windows) or a dsym folder (on macos) so provide it in an output group for crate 1118# types that benefit from having debug information in a separate file. 1119pdb_file = None 1120dsym_folder = None 1121if crate_info . type in ( "cdylib" , "bin" ) and not crate_info . is_test : 1122if toolchain . os == "windows" : 1123pdb_file = ctx . actions . declare_file ( crate_info . output . basename [: - len ( crate_info . output . extension )] + "pdb" , sibling = crate_info . output ) 1124action_outputs . append ( pdb_file ) 1125elif toolchain . os == "darwin" : 1126dsym_folder = ctx . actions . declare_directory ( crate_info . output . basename + ".dSYM" , sibling = crate_info . output ) 1127action_outputs . append ( dsym_folder ) 1128 1129if ctx . executable . _process_wrapper : 1130# Run as normal 1131ctx . actions . run ( 1132executable = ctx . executable . _process_wrapper , 1133inputs = compile_inputs , 1134outputs = action_outputs , 1135env = env , 1136arguments = args . all , 1137mnemonic = "Rustc" , 1138progress_message = "Compiling Rust {} {}{} ({} files)" . format ( 1139crate_info . type , 1140ctx . label . name , 1141formatted_version , 1142len ( crate_info . srcs . to_list ()), 1143), 1144) 1145if args_metadata : 1146ctx . actions . run ( 1147executable = ctx . executable . _process_wrapper , 1148inputs = compile_inputs , 1149outputs = [ build_metadata ], 1150env = env , 1151arguments = args_metadata . all , 1152mnemonic = "RustcMetadata" , 1153progress_message = "Compiling Rust metadata {} {}{} ({} files)" . format ( 1154crate_info . type , 1155ctx . label . name , 1156formatted_version , 1157len ( crate_info . srcs . to_list ()), 1158), 1159) 1160else : 1161# Run without process_wrapper 1162if build_env_files or build_flags_files or stamp or build_metadata : 1163fail ( "build_env_files, build_flags_files, stamp, build_metadata are not supported when building without process_wrapper" ) 1164ctx . actions . run ( 1165executable = toolchain . rustc , 1166inputs = compile_inputs , 1167outputs = action_outputs , 1168env = env , 1169arguments = [ args . rustc_flags ], 1170mnemonic = "Rustc" , 1171progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)" . format ( 1172crate_info . type , 1173ctx . label . name , 1174formatted_version , 1175len ( crate_info . srcs . to_list ()), 1176), 1177) 1178 1179coverage_runfiles = [] 1180if toolchain . llvm_cov and ctx . configuration . coverage_enabled and crate_info . is_test : 1181coverage_runfiles = [ toolchain . llvm_cov , toolchain . llvm_profdata ] 1182 1183runfiles = ctx . runfiles ( 1184files = getattr ( ctx . files , "data" , []) + coverage_runfiles , 1185collect_data = True , 1186) 1187 1188# TODO: Remove after some resolution to 1189# https://github.com/bazelbuild/rules_rust/issues/771 1190out_binary = getattr ( attr , "out_binary" , False ) 1191 1192providers = [ 1193DefaultInfo ( 1194# nb. This field is required for cc_library to depend on our output. 1195files = depset ( outputs ), 1196runfiles = runfiles , 1197executable = crate_info . output if crate_info . type == "bin" or crate_info . is_test or out_binary else None , 1198), 1199coverage_common . instrumented_files_info ( 1200ctx , 1201dependency_attributes = [ "deps" , "crate" ], 1202extensions = [ "rs" ], 1203source_attributes = [ "srcs" ], 1204), 1205] 1206 1207if crate_info . type in [ "staticlib" , "cdylib" ]: 1208# These rules are not supposed to be depended on by other rust targets, and 1209# as such they shouldn't provide a CrateInfo. However, one may still want to 1210# write a rust_test for them, so we provide the CrateInfo wrapped in a provider 1211# that rust_test understands. 1212providers . extend ([ rust_common . test_crate_info ( crate = crate_info ), dep_info ]) 1213else : 1214providers . extend ([ crate_info , dep_info ]) 1215 1216if toolchain . target_arch != "wasm32" : 1217providers += establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ) 1218if pdb_file : 1219providers . append ( OutputGroupInfo ( pdb_file = depset ([ pdb_file ]))) 1220if dsym_folder : 1221providers . append ( OutputGroupInfo ( dsym_folder = depset ([ dsym_folder ]))) 1222 1223return providers 1224 1225def _is_dylib ( dep ): 1226return not bool ( dep . static_library or dep . pic_static_library ) 1227 1228def _collect_nonstatic_linker_inputs ( cc_info ): 1229shared_linker_inputs = [] 1230for linker_input in cc_info . linking_context . linker_inputs . to_list (): 1231dylibs = [ 1232lib 1233for lib in linker_input . libraries 1234if _is_dylib ( lib ) 1235] 1236if dylibs : 1237shared_linker_inputs . append ( cc_common . create_linker_input ( 1238owner = linker_input . owner , 1239libraries = depset ( dylibs ), 1240)) 1241return shared_linker_inputs 1242 1243def establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ): 1244"""If the produced crate is suitable yield a CcInfo to allow for interop with cc rules 1245 1246Args: 1247ctx (ctx): The rule's context object 1248attr (struct): Attributes to use in gathering CcInfo 1249crate_info (CrateInfo): The CrateInfo provider of the target crate 1250toolchain (rust_toolchain): The current `rust_toolchain` 1251cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo` 1252feature_configuration (FeatureConfiguration): Feature configuration to be queried. 1253interface_library (File): Optional interface library for cdylib crates on Windows. 1254 1255Returns: 1256list: A list containing the CcInfo provider 1257""" 1258 1259# A test will not need to produce CcInfo as nothing can depend on test targets 1260if crate_info . is_test : 1261return [] 1262 1263# Only generate CcInfo for particular crate types 1264if crate_info . type not in ( "staticlib" , "cdylib" , "rlib" , "lib" ): 1265return [] 1266 1267# TODO: Remove after some resolution to 1268# https://github.com/bazelbuild/rules_rust/issues/771 1269if getattr ( attr , "out_binary" , False ): 1270return [] 1271 1272if crate_info . type == "staticlib" : 1273library_to_link = cc_common . create_library_to_link ( 1274actions = ctx . actions , 1275feature_configuration = feature_configuration , 1276cc_toolchain = cc_toolchain , 1277static_library = crate_info . output , 1278# TODO(hlopko): handle PIC/NOPIC correctly 1279pic_static_library = crate_info . output , 1280) 1281elif crate_info . type in ( "rlib" , "lib" ): 1282# bazel hard-codes a check for endswith((".a", ".pic.a", 1283# ".lib")) in create_library_to_link, so we work around that 1284# by creating a symlink to the .rlib with a .a extension. 1285dot_a = make_static_lib_symlink ( ctx . actions , crate_info . output ) 1286 1287# TODO(hlopko): handle PIC/NOPIC correctly 1288library_to_link = cc_common . create_library_to_link ( 1289actions = ctx . actions , 1290feature_configuration = feature_configuration , 1291cc_toolchain = cc_toolchain , 1292static_library = dot_a , 1293# TODO(hlopko): handle PIC/NOPIC correctly 1294pic_static_library = dot_a , 1295) 1296elif crate_info . type == "cdylib" : 1297library_to_link = cc_common . create_library_to_link ( 1298actions = ctx . actions , 1299feature_configuration = feature_configuration , 1300cc_toolchain = cc_toolchain , 1301dynamic_library = crate_info . output , 1302interface_library = interface_library , 1303) 1304else : 1305fail ( "Unexpected case" ) 1306 1307link_input = cc_common . create_linker_input ( 1308owner = ctx . label , 1309libraries = depset ([ library_to_link ]), 1310) 1311 1312linking_context = cc_common . create_linking_context ( 1313# TODO - What to do for no_std? 1314linker_inputs = depset ([ link_input ]), 1315) 1316 1317cc_infos = [ 1318CcInfo ( linking_context = linking_context ), 1319toolchain . stdlib_linkflags , 1320] 1321 1322for dep in getattr ( attr , "deps" , []): 1323if CcInfo in dep : 1324# A Rust staticlib or shared library doesn't need to propagate linker inputs 1325# of its dependencies, except for shared libraries. 1326if crate_info . type in [ "cdylib" , "staticlib" ]: 1327shared_linker_inputs = _collect_nonstatic_linker_inputs ( dep [ CcInfo ]) 1328if shared_linker_inputs : 1329linking_context = cc_common . create_linking_context ( 1330linker_inputs = depset ( shared_linker_inputs ), 1331) 1332cc_infos . append ( CcInfo ( linking_context = linking_context )) 1333else : 1334cc_infos . append ( dep [ CcInfo ]) 1335 1336if crate_info . type in ( "rlib" , "lib" ) and toolchain . libstd_and_allocator_ccinfo : 1337# TODO: if we already have an rlib in our deps, we could skip this 1338cc_infos . append ( toolchain . libstd_and_allocator_ccinfo ) 1339 1340return [ cc_common . merge_cc_infos ( cc_infos = cc_infos )] 1341 1342def add_edition_flags ( args , crate ): 1343"""Adds the Rust edition flag to an arguments object reference 1344 1345Args: 1346args (Args): A reference to an Args object 1347crate (CrateInfo): A CrateInfo provider 1348""" 1349if crate . edition != "2015" : 1350args . add ( "--edition={}" . format ( crate . edition )) 1351 1352def _create_extra_input_args ( build_info , dep_info ): 1353"""Gather additional input arguments from transitive dependencies 1354 1355Args: 1356build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs. 1357dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 1358 1359Returns: 1360tuple: A tuple of the following items: 1361- (depset[File]): A list of all build info `OUT_DIR` File objects 1362- (str): The `OUT_DIR` of the current build info 1363- (File): An optional generated environment file from a `cargo_build_script` target 1364- (depset[File]): All direct and transitive build flag files from the current build info. 1365""" 1366input_files = [] 1367 1368# Arguments to the commandline line wrapper that are going to be used 1369# to create the final command line 1370out_dir = None 1371build_env_file = None 1372build_flags_files = [] 1373 1374if build_info : 1375out_dir = build_info . out_dir . path 1376build_env_file = build_info . rustc_env 1377build_flags_files . append ( build_info . flags ) 1378build_flags_files . append ( build_info . link_flags ) 1379input_files . append ( build_info . out_dir ) 1380input_files . append ( build_info . link_flags ) 1381 1382return ( 1383depset ( input_files , transitive = [ dep_info . link_search_path_files ]), 1384out_dir , 1385build_env_file , 1386depset ( build_flags_files , transitive = [ dep_info . link_search_path_files ]), 1387) 1388 1389def _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ): 1390"""Determine the artifact's rpaths relative to the bazel root for runtime linking of shared libraries. 1391 1392Args: 1393toolchain (rust_toolchain): The current `rust_toolchain` 1394output_dir (str): The output directory of the current target 1395dep_info (DepInfo): The current target's dependency info 1396use_pic: If set, prefers pic_static_library over static_library. 1397 1398Returns: 1399depset: A set of relative paths from the output directory to each dependency 1400""" 1401 1402# Windows has no rpath equivalent, so always return an empty depset. 1403if toolchain . os == "windows" : 1404return depset ([]) 1405 1406dylibs = [ 1407get_preferred_artifact ( lib , use_pic ) 1408for linker_input in dep_info . transitive_noncrates . to_list () 1409for lib in linker_input . libraries 1410if _is_dylib ( lib ) 1411] 1412if not dylibs : 1413return depset ([]) 1414 1415# For darwin, dylibs compiled by Bazel will fail to be resolved at runtime 1416# without a version of Bazel that includes 1417# https://github.com/bazelbuild/bazel/pull/13427. This is known to not be 1418# included in Bazel 4.1 and below. 1419if toolchain . os != "linux" and toolchain . os != "darwin" : 1420fail ( "Runtime linking is not supported on {}, but found {}" . format ( 1421toolchain . os , 1422dep_info . transitive_noncrates , 1423)) 1424 1425# Multiple dylibs can be present in the same directory, so deduplicate them. 1426return depset ([ 1427relativize ( lib_dir , output_dir ) 1428for lib_dir in _get_dir_names ( dylibs ) 1429]) 1430 1431def _get_dir_names ( files ): 1432"""Returns a list of directory names from the given list of File objects 1433 1434Args: 1435files (list): A list of File objects 1436 1437Returns: 1438list: A list of directory names for all files 1439""" 1440dirs = {} 1441for f in files : 1442dirs [ f . dirname ] = None 1443return dirs . keys () 1444 1445def add_crate_link_flags ( args , dep_info , force_all_deps_direct = False , use_metadata = False ): 1446"""Adds link flags to an Args object reference 1447 1448Args: 1449args (Args): An arguments object reference 1450dep_info (DepInfo): The current target's dependency info 1451force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 1452to the commandline as opposed to -L. 1453use_metadata (bool, optional): Build command line arugments using metadata for crates that provide it. 1454""" 1455 1456direct_crates = depset ( 1457transitive = [ 1458dep_info . direct_crates , 1459dep_info . transitive_crates , 1460], 1461) if force_all_deps_direct else dep_info . direct_crates 1462 1463crate_to_link_flags = _crate_to_link_flag_metadata if use_metadata else _crate_to_link_flag 1464args . add_all ( direct_crates , uniquify = True , map_each = crate_to_link_flags ) 1465 1466args . add_all ( 1467dep_info . transitive_crates , 1468map_each = _get_crate_dirname , 1469uniquify = True , 1470format_each = "-Ldependency=%s" , 1471) 1472 1473def _crate_to_link_flag_metadata ( crate ): 1474"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1475 1476Args: 1477crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1478 1479Returns: 1480list: Link flags for the given provider 1481""" 1482 1483# This is AliasableDepInfo, we should use the alias as a crate name 1484if hasattr ( crate , "dep" ): 1485name = crate . name 1486crate_info = crate . dep 1487else : 1488name = crate . name 1489crate_info = crate 1490 1491lib_or_meta = crate_info . metadata 1492if not crate_info . metadata : 1493lib_or_meta = crate_info . output 1494return [ "--extern={}={}" . format ( name , lib_or_meta . path )] 1495 1496def _crate_to_link_flag ( crate ): 1497"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1498 1499Args: 1500crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1501 1502Returns: 1503list: Link flags for the given provider 1504""" 1505 1506# This is AliasableDepInfo, we should use the alias as a crate name 1507if hasattr ( crate , "dep" ): 1508name = crate . name 1509crate_info = crate . dep 1510else : 1511name = crate . name 1512crate_info = crate 1513return [ "--extern={}={}" . format ( name , crate_info . output . path )] 1514 1515def _get_crate_dirname ( crate ): 1516"""A helper macro used by `add_crate_link_flags` for getting the directory name of the current crate's output path 1517 1518Args: 1519crate (CrateInfo): A CrateInfo provider from the current rule 1520 1521Returns: 1522str: The directory name of the the output File that will be produced. 1523""" 1524return crate . output . dirname 1525 1526def _portable_link_flags ( lib , use_pic , ambiguous_libs , for_windows = False ): 1527artifact = get_preferred_artifact ( lib , use_pic ) 1528if ambiguous_libs and artifact . path in ambiguous_libs : 1529artifact = ambiguous_libs [ artifact . path ] 1530if lib . static_library or lib . pic_static_library : 1531# To ensure appropriate linker library argument order, in the presence 1532# of both native libraries that depend on rlibs and rlibs that depend 1533# on native libraries, we use an approach where we "sandwich" the 1534# rust libraries between two similar sections of all of native 1535# libraries: 1536# n1 n2 ... r1 r2 ... n1 n2 ... 1537# A B C 1538# This way any dependency from a native library to a rust library 1539# is resolved from A to B, and any dependency from a rust library to 1540# a native one is resolved from B to C. 1541# The question of resolving dependencies from a native library from A 1542# to any rust library is addressed in a different place, where we 1543# create symlinks to the rlibs, pretending they are native libraries, 1544# and adding references to these symlinks in the native section A. 1545# We rely in the behavior of -Clink-arg to put the linker args 1546# at the end of the linker invocation constructed by rustc. 1547 1548# We skip adding `-Clink-arg=-l` for libstd and libtest from the standard library, as 1549# these two libraries are present both as an `.rlib` and a `.so` format. 1550# On linux, Rustc adds a -Bdynamic to the linker command line before the libraries specified 1551# with `-Clink-arg`, which leads to us linking against the `.so`s but not putting the 1552# corresponding value to the runtime library search paths, which results in a 1553# "cannot open shared object file: No such file or directory" error at exectuion time. 1554# We can fix this by adding a `-Clink-arg=-Bstatic` on linux, but we don't have that option for 1555# macos. The proper solution for this issue would be to remove `libtest-{hash}.so` and `libstd-{hash}.so` 1556# from the toolchain. However, it is not enough to change the toolchain's `rust_std_{...}` filegroups 1557# here: https://github.com/bazelbuild/rules_rust/blob/a9d5d894ad801002d007b858efd154e503796b9f/rust/private/repository_utils.bzl#L144 1558# because rustc manages to escape the sandbox and still finds them at linking time. 1559# We need to modify the repository rules to erase those files completely. 1560if "lib/rustlib" in artifact . path and ( 1561artifact . basename . startswith ( "libtest-" ) or artifact . basename . startswith ( "libstd-" ) or 1562artifact . basename . startswith ( "test-" ) or artifact . basename . startswith ( "std-" ) 1563): 1564return [ "-lstatic=%s" % get_lib_name ( artifact , for_windows )] 1565return [ 1566"-lstatic=%s" % get_lib_name ( artifact , for_windows ), 1567"-Clink-arg=-l%s" % ( get_lib_name ( artifact ) if not for_windows else artifact . basename ), 1568] 1569elif _is_dylib ( lib ): 1570return [ 1571"-ldylib=%s" % get_lib_name ( artifact , for_windows ), 1572] 1573 1574return [] 1575 1576def _make_link_flags_windows ( linker_input_and_use_pic_and_ambiguous_libs ): 1577linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1578ret = [] 1579for lib in linker_input . libraries : 1580if lib . alwayslink : 1581ret . extend ([ "-C" , "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact ( lib , use_pic ). path ]) 1582else : 1583ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs , for_windows = True )) 1584return ret 1585 1586def _make_link_flags_darwin ( linker_input_and_use_pic_and_ambiguous_libs ): 1587linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1588ret = [] 1589for lib in linker_input . libraries : 1590if lib . alwayslink : 1591ret . extend ([ 1592"-C" , 1593( "link-arg=-Wl,-force_load,%s" % get_preferred_artifact ( lib , use_pic ). path ), 1594]) 1595else : 1596ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1597return ret 1598 1599def _make_link_flags_default ( linker_input_and_use_pic_and_ambiguous_libs ): 1600linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1601ret = [] 1602for lib in linker_input . libraries : 1603if lib . alwayslink : 1604ret . extend ([ 1605"-C" , 1606"link-arg=-Wl,--whole-archive" , 1607"-C" , 1608( "link-arg=%s" % get_preferred_artifact ( lib , use_pic ). path ), 1609"-C" , 1610"link-arg=-Wl,--no-whole-archive" , 1611]) 1612else : 1613ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1614return ret 1615 1616def _libraries_dirnames ( linker_input_and_use_pic_and_ambiguous_libs ): 1617link_input , use_pic , _ = linker_input_and_use_pic_and_ambiguous_libs 1618 1619# De-duplicate names. 1620return depset ([ get_preferred_artifact ( lib , use_pic ). dirname for lib in link_input . libraries ]). to_list () 1621 1622def _add_native_link_flags ( args , dep_info , linkstamp_outs , ambiguous_libs , crate_type , toolchain , cc_toolchain , feature_configuration ): 1623"""Adds linker flags for all dependencies of the current target. 1624 1625Args: 1626args (Args): The Args struct for a ctx.action 1627dep_info (DepInfo): Dependency Info provider 1628linkstamp_outs (list): Linkstamp outputs of native dependencies 1629ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 1630crate_type: Crate type of the current target 1631toolchain (rust_toolchain): The current `rust_toolchain` 1632cc_toolchain (CcToolchainInfo): The current `cc_toolchain` 1633feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain 1634""" 1635if crate_type in [ "lib" , "rlib" ]: 1636return 1637 1638use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_type ) 1639 1640if toolchain . os == "windows" : 1641make_link_flags = _make_link_flags_windows 1642elif toolchain . os . startswith ( "mac" ) or toolchain . os . startswith ( "darwin" ): 1643make_link_flags = _make_link_flags_darwin 1644else : 1645make_link_flags = _make_link_flags_default 1646 1647# TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0 1648args_and_pic_and_ambiguous_libs = [( arg , use_pic , ambiguous_libs ) for arg in dep_info . transitive_noncrates . to_list ()] 1649args . add_all ( args_and_pic_and_ambiguous_libs , map_each = _libraries_dirnames , uniquify = True , format_each = "-Lnative=%s" ) 1650if ambiguous_libs : 1651# If there are ambiguous libs, the disambiguation symlinks to them are 1652# all created in the same directory. Add it to the library search path. 1653ambiguous_libs_dirname = ambiguous_libs . values ()[ 0 ]. dirname 1654args . add ( "-Lnative={}" . format ( ambiguous_libs_dirname )) 1655 1656args . add_all ( args_and_pic_and_ambiguous_libs , map_each = make_link_flags ) 1657 1658for linkstamp_out in linkstamp_outs : 1659args . add_all ([ "-C" , "link-arg=%s" % linkstamp_out . path ]) 1660 1661if crate_type in [ "dylib" , "cdylib" ]: 1662# For shared libraries we want to link C++ runtime library dynamically 1663# (for example libstdc++.so or libc++.so). 1664args . add_all ( 1665cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1666map_each = _get_dirname , 1667format_each = "-Lnative=%s" , 1668) 1669args . add_all ( 1670cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1671map_each = get_lib_name , 1672format_each = "-ldylib=%s" , 1673) 1674else : 1675# For all other crate types we want to link C++ runtime library statically 1676# (for example libstdc++.a or libc++.a). 1677args . add_all ( 1678cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1679map_each = _get_dirname , 1680format_each = "-Lnative=%s" , 1681) 1682args . add_all ( 1683cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1684map_each = get_lib_name , 1685format_each = "-lstatic=%s" , 1686) 1687 1688def _get_dirname ( file ): 1689"""A helper function for `_add_native_link_flags`. 1690 1691Args: 1692file (File): The target file 1693 1694Returns: 1695str: Directory name of `file` 1696""" 1697return file . dirname 1698 1699def _error_format_impl ( ctx ): 1700"""Implementation of the `error_format` rule 1701 1702Args: 1703ctx (ctx): The rule's context object 1704 1705Returns: 1706list: A list containing the ErrorFormatInfo provider 1707""" 1708raw = ctx . build_setting_value 1709if raw not in _error_format_values : 1710fail ( "{} expected a value in `{}` but got `{}`" . format ( 1711ctx . label , 1712_error_format_values , 1713raw , 1714)) 1715return [ ErrorFormatInfo ( error_format = raw )] 1716 1717error_format = rule ( 1718doc = ( 1719"Change the [--error-format](https://doc.rust-lang.org/rustc/command-line-arguments.html#option-error-format) " + 1720"flag from the command line with `--@rules_rust//:error_format`. See rustc documentation for valid values." 1721), 1722implementation = _error_format_impl , 1723build_setting = config . string ( flag = True ), 1724) 1725 1726def _extra_rustc_flags_impl ( ctx ): 1727return ExtraRustcFlagsInfo ( extra_rustc_flags = ctx . build_setting_value ) 1728 1729extra_rustc_flags = rule ( 1730doc = ( 1731"Add additional rustc_flags from the command line with `--@rules_rust//:extra_rustc_flags`. " + 1732"This flag should only be used for flags that need to be applied across the entire build. For options that " + 1733"apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: " + 1734"These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); " + 1735"use `--@rules_rust//:extra_exec_rustc_flags` to apply flags to the exec configuration." 1736), 1737implementation = _extra_rustc_flags_impl , 1738build_setting = config . string_list ( flag = True ), 1739) 1740 1741def _extra_rustc_flag_impl ( ctx ): 1742return ExtraRustcFlagsInfo ( extra_rustc_flags = [ f for f in ctx . build_setting_value if f != "" ]) 1743 1744extra_rustc_flag = rule ( 1745doc = ( 1746"Add additional rustc_flag from the command line with `--@rules_rust//:extra_rustc_flag`. " + 1747"Multiple uses are accumulated and appended after the extra_rustc_flags." 1748), 1749implementation = _extra_rustc_flag_impl , 1750build_setting = config . string ( flag = True , allow_multiple = True ), 1751) 1752 1753def _extra_exec_rustc_flags_impl ( ctx ): 1754return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = ctx . build_setting_value ) 1755 1756extra_exec_rustc_flags = rule ( 1757doc = ( 1758"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flags`. " + 1759"This flag should only be used for flags that need to be applied across the entire build. " + 1760"These flags only apply to the exec configuration (proc-macros, cargo_build_script, etc)." 1761), 1762implementation = _extra_exec_rustc_flags_impl , 1763build_setting = config . string_list ( flag = True ), 1764) 1765 1766def _extra_exec_rustc_flag_impl ( ctx ): 1767return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = [ f for f in ctx . build_setting_value if f != "" ]) 1768 1769extra_exec_rustc_flag = rule ( 1770doc = ( 1771"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flag`. " + 1772"Multiple uses are accumulated and appended after the extra_exec_rustc_flags." 1773), 1774implementation = _extra_exec_rustc_flag_impl , 1775build_setting = config . string ( flag = True , allow_multiple = True ), 1776)