fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
0e2409ef
patching
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 ( "@bazel_skylib//rules:common_settings.bzl" , "BuildSettingInfo" ) 18load ( 19"@bazel_tools//tools/build_defs/cc:action_names.bzl" , 20"CPP_LINK_DYNAMIC_LIBRARY_ACTION_NAME" , 21"CPP_LINK_EXECUTABLE_ACTION_NAME" , 22"CPP_LINK_NODEPS_DYNAMIC_LIBRARY_ACTION_NAME" , 23"CPP_LINK_STATIC_LIBRARY_ACTION_NAME" , 24) 25load ( "//rust/private:common.bzl" , "rust_common" ) 26load ( "//rust/private:providers.bzl" , "RustcOutputDiagnosticsInfo" , _BuildInfo = "BuildInfo" ) 27load ( "//rust/private:stamp.bzl" , "is_stamping_enabled" ) 28load ( 29"//rust/private:utils.bzl" , 30"abs" , 31"expand_dict_value_locations" , 32"expand_list_element_locations" , 33"find_cc_toolchain" , 34"get_lib_name_default" , 35"get_lib_name_for_windows" , 36"get_preferred_artifact" , 37"is_exec_configuration" , 38"make_static_lib_symlink" , 39"relativize" , 40) 41load ( ":utils.bzl" , "is_std_dylib" ) 42 43# This feature is disabled unless one of the dependencies is a cc_library. 44# Authors of C++ toolchains can place linker flags that should only be applied 45# when linking with C objects in a feature with this name, or require this 46# feature from other features which needs to be disabled together. 47RUST_LINK_CC_FEATURE = "rules_rust_link_cc" 48 49BuildInfo = _BuildInfo 50 51AliasableDepInfo = provider ( 52doc = "A provider mapping an alias name to a Crate's information." , 53fields = { 54"dep" : "CrateInfo" , 55"name" : "str" , 56}, 57) 58 59_error_format_values = [ "human" , "json" , "short" ] 60 61ErrorFormatInfo = provider ( 62doc = "Set the --error-format flag for all rustc invocations" , 63fields = { "error_format" : "(string) [" + ", " . join ( _error_format_values ) + "]" }, 64) 65 66ExtraRustcFlagsInfo = provider ( 67doc = "Pass each value as an additional flag to non-exec rustc invocations" , 68fields = { "extra_rustc_flags" : "List[string] Extra flags to pass to rustc in non-exec configuration" }, 69) 70 71ExtraExecRustcFlagsInfo = provider ( 72doc = "Pass each value as an additional flag to exec rustc invocations" , 73fields = { "extra_exec_rustc_flags" : "List[string] Extra flags to pass to rustc in exec configuration" }, 74) 75 76PerCrateRustcFlagsInfo = provider ( 77doc = "Pass each value as an additional flag to non-exec rustc invocations for crates matching the provided filter" , 78fields = { "per_crate_rustc_flags" : "List[string] Extra flags to pass to rustc in non-exec configuration" }, 79) 80 81IsProcMacroDepInfo = provider ( 82doc = "Records if this is a transitive dependency of a proc-macro." , 83fields = { "is_proc_macro_dep" : "Boolean" }, 84) 85 86def _is_proc_macro_dep_impl ( ctx ): 87return IsProcMacroDepInfo ( is_proc_macro_dep = ctx . build_setting_value ) 88 89is_proc_macro_dep = rule ( 90doc = "Records if this is a transitive dependency of a proc-macro." , 91implementation = _is_proc_macro_dep_impl , 92build_setting = config . bool ( flag = True ), 93) 94 95IsProcMacroDepEnabledInfo = provider ( 96doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro." , 97fields = { "enabled" : "Boolean" }, 98) 99 100def _is_proc_macro_dep_enabled_impl ( ctx ): 101return IsProcMacroDepEnabledInfo ( enabled = ctx . build_setting_value ) 102 103is_proc_macro_dep_enabled = rule ( 104doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro." , 105implementation = _is_proc_macro_dep_enabled_impl , 106build_setting = config . bool ( flag = True ), 107) 108 109def _get_rustc_env ( attr , toolchain , crate_name ): 110"""Gathers rustc environment variables 111 112Args: 113attr (struct): The current target's attributes 114toolchain (rust_toolchain): The current target's rust toolchain context 115crate_name (str): The name of the crate to be compiled 116 117Returns: 118dict: Rustc environment variables 119""" 120version = attr . version if hasattr ( attr , "version" ) else "0.0.0" 121major , minor , patch = version . split ( "." , 2 ) 122if "-" in patch : 123patch , pre = patch . split ( "-" , 1 ) 124else : 125pre = "" 126 127result = { 128"CARGO_CFG_TARGET_ARCH" : "" if toolchain . target_arch == None else toolchain . target_arch , 129"CARGO_CFG_TARGET_OS" : "" if toolchain . target_os == None else toolchain . target_os , 130"CARGO_CRATE_NAME" : crate_name , 131"CARGO_PKG_AUTHORS" : "" , 132"CARGO_PKG_DESCRIPTION" : "" , 133"CARGO_PKG_HOMEPAGE" : "" , 134"CARGO_PKG_NAME" : attr . name , 135"CARGO_PKG_VERSION" : version , 136"CARGO_PKG_VERSION_MAJOR" : major , 137"CARGO_PKG_VERSION_MINOR" : minor , 138"CARGO_PKG_VERSION_PATCH" : patch , 139"CARGO_PKG_VERSION_PRE" : pre , 140} 141if hasattr ( attr , "_is_proc_macro_dep_enabled" ) and attr . _is_proc_macro_dep_enabled [ IsProcMacroDepEnabledInfo ]. enabled : 142is_proc_macro_dep = "0" 143if hasattr ( attr , "_is_proc_macro_dep" ) and attr . _is_proc_macro_dep [ IsProcMacroDepInfo ]. is_proc_macro_dep : 144is_proc_macro_dep = "1" 145result [ "BAZEL_RULES_RUST_IS_PROC_MACRO_DEP" ] = is_proc_macro_dep 146return result 147 148def get_compilation_mode_opts ( ctx , toolchain ): 149"""Gathers rustc flags for the current compilation mode (opt/debug) 150 151Args: 152ctx (ctx): The current rule's context object 153toolchain (rust_toolchain): The current rule's `rust_toolchain` 154 155Returns: 156struct: See `_rust_toolchain_impl` for more details 157""" 158comp_mode = ctx . var [ "COMPILATION_MODE" ] 159if not comp_mode in toolchain . compilation_mode_opts : 160fail ( "Unrecognized compilation mode {} for toolchain." . format ( comp_mode )) 161 162return toolchain . compilation_mode_opts [ comp_mode ] 163 164def _are_linkstamps_supported ( feature_configuration , has_grep_includes ): 165# Are linkstamps supported by the C++ toolchain? 166return ( cc_common . is_enabled ( feature_configuration = feature_configuration , feature_name = "linkstamps" ) and 167# Is Bazel recent enough to support Starlark linkstamps? 168hasattr ( cc_common , "register_linkstamp_compile_action" ) and 169# The current rule doesn't define _grep_includes attribute; this 170# attribute is required for compiling linkstamps. 171has_grep_includes ) 172 173def _should_use_pic ( cc_toolchain , feature_configuration , crate_type , compilation_mode ): 174"""Whether or not [PIC][pic] should be enabled 175 176[pic]: https://en.wikipedia.org/wiki/Position-independent_code 177 178Args: 179cc_toolchain (CcToolchainInfo): The current `cc_toolchain`. 180feature_configuration (FeatureConfiguration): Feature configuration to be queried. 181crate_type (str): A Rust target's crate type. 182compilation_mode: The compilation mode. 183 184Returns: 185bool: Whether or not [PIC][pic] should be enabled. 186""" 187 188# We use the same logic to select between `pic` and `nopic` outputs as the C++ rules: 189# - For shared libraries - we use `pic`. This covers `dylib`, `cdylib` and `proc-macro` crate types. 190# - In `fastbuild` and `dbg` mode we use `pic` by default. 191# - In `opt` mode we use `nopic` outputs to build binaries. 192if crate_type in ( "cdylib" , "dylib" , "proc-macro" ): 193return cc_toolchain . needs_pic_for_dynamic_libraries ( feature_configuration = feature_configuration ) 194elif compilation_mode in ( "fastbuild" , "dbg" ): 195return True 196return False 197 198def _is_proc_macro ( crate_info ): 199return "proc-macro" in ( crate_info . type , crate_info . wrapped_crate_type ) 200 201def collect_deps ( 202deps , 203proc_macro_deps , 204aliases ): 205"""Walks through dependencies and collects the transitive dependencies. 206 207Args: 208deps (list): The deps from ctx.attr.deps. 209proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps. 210aliases (dict): A dict mapping aliased targets to their actual Crate information. 211 212Returns: 213tuple: Returns a tuple of: 214DepInfo, 215BuildInfo, 216linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries when applicable. 217 218""" 219direct_crates = [] 220transitive_crates = [] 221transitive_data = [] 222transitive_proc_macro_data = [] 223transitive_noncrates = [] 224transitive_build_infos = [] 225transitive_link_search_paths = [] 226build_info = None 227linkstamps = [] 228transitive_crate_outputs = [] 229transitive_metadata_outputs = [] 230 231crate_deps = [] 232for dep in depset ( transitive = [ deps , proc_macro_deps ]). to_list (): 233crate_group = None 234 235if type ( dep ) == "Target" and rust_common . crate_group_info in dep : 236crate_group = dep [ rust_common . crate_group_info ] 237elif type ( dep ) == "struct" and hasattr ( dep , "crate_group_info" ) and dep . crate_group_info != None : 238crate_group = dep . crate_group_info 239else : 240crate_deps . append ( dep ) 241 242if crate_group : 243for dep_variant_info in crate_group . dep_variant_infos . to_list (): 244crate_deps . append ( struct ( 245crate_info = dep_variant_info . crate_info , 246dep_info = dep_variant_info . dep_info , 247cc_info = dep_variant_info . cc_info , 248)) 249 250aliases = { k . label : v for k , v in aliases . items ()} 251for dep in crate_deps : 252( crate_info , dep_info ) = _get_crate_and_dep_info ( dep ) 253cc_info = _get_cc_info ( dep ) 254dep_build_info = _get_build_info ( dep ) 255 256if cc_info : 257linkstamps . append ( cc_info . linking_context . linkstamps ()) 258 259if crate_info : 260# This dependency is a rust_library 261 262# When crate_info.owner is set, we use it. When the dep type is Target we get the 263# label from dep.label 264owner = getattr ( crate_info , "owner" , dep . label if type ( dep ) == "Target" else None ) 265 266direct_crates . append ( AliasableDepInfo ( 267name = aliases . get ( owner , crate_info . name ), 268dep = crate_info , 269)) 270 271transitive_crates . append ( 272depset ( 273[ crate_info ], 274transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_crates ], 275), 276) 277 278if _is_proc_macro ( crate_info ): 279# This crate's data and its non-macro dependencies' data are proc macro data. 280transitive_proc_macro_data . append ( crate_info . data ) 281transitive_proc_macro_data . append ( dep_info . transitive_data ) 282else : 283# This crate's proc macro dependencies' data are proc macro data. 284transitive_proc_macro_data . append ( dep_info . transitive_proc_macro_data ) 285 286# Track transitive non-macro data in case a proc macro depends on this crate. 287transitive_data . append ( crate_info . data ) 288transitive_data . append ( dep_info . transitive_data ) 289 290# If this dependency produces metadata, add it to the metadata outputs. 291# If it doesn't (for example a custom library that exports crate_info), 292# we depend on crate_info.output. 293depend_on = crate_info . metadata 294if not crate_info . metadata : 295depend_on = crate_info . output 296 297# If this dependency is a proc_macro, it still can be used for lib crates 298# that produce metadata. 299# In that case, we don't depend on its metadata dependencies. 300transitive_metadata_outputs . append ( 301depset ( 302[ depend_on ], 303transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_metadata_outputs ], 304), 305) 306 307transitive_crate_outputs . append ( 308depset ( 309[ crate_info . output ], 310transitive = [] if _is_proc_macro ( crate_info ) else [ dep_info . transitive_crate_outputs ], 311), 312) 313 314if "proc-macro" not in [ crate_info . type , crate_info . wrapped_crate_type ]: 315transitive_noncrates . append ( dep_info . transitive_noncrates ) 316transitive_link_search_paths . append ( dep_info . link_search_path_files ) 317 318transitive_build_infos . append ( dep_info . transitive_build_infos ) 319elif cc_info or dep_build_info : 320if cc_info : 321# This dependency is a cc_library 322transitive_noncrates . append ( cc_info . linking_context . linker_inputs ) 323 324if dep_build_info : 325if build_info : 326fail ( "Several deps are providing build information, " + 327"only one is allowed in the dependencies" ) 328build_info = dep_build_info 329transitive_build_infos . append ( depset ([ build_info ])) 330if build_info . link_search_paths : 331transitive_link_search_paths . append ( depset ([ build_info . link_search_paths ])) 332else : 333fail ( "rust targets can only depend on rust_library, rust_*_library or cc_library " + 334"targets." ) 335 336transitive_crates_depset = depset ( transitive = transitive_crates ) 337transitive_data_depset = depset ( transitive = transitive_data ) 338transitive_proc_macro_data_depset = depset ( transitive = transitive_proc_macro_data ) 339 340return ( 341rust_common . dep_info ( 342direct_crates = depset ( direct_crates ), 343transitive_crates = transitive_crates_depset , 344transitive_data = transitive_data_depset , 345transitive_proc_macro_data = transitive_proc_macro_data_depset , 346transitive_noncrates = depset ( 347transitive = transitive_noncrates , 348order = "topological" , #dylib link flag ordering matters . 349), 350transitive_crate_outputs = depset ( transitive = transitive_crate_outputs ), 351transitive_metadata_outputs = depset ( transitive = transitive_metadata_outputs ), 352transitive_build_infos = depset ( transitive = transitive_build_infos ), 353link_search_path_files = depset ( transitive = transitive_link_search_paths ), 354dep_env = build_info . dep_env if build_info else None , 355), 356build_info , 357depset ( transitive = linkstamps ), 358) 359 360def _collect_libs_from_linker_inputs ( linker_inputs , use_pic ): 361# TODO: We could let the user choose how to link, instead of always preferring to link static libraries. 362return [ 363get_preferred_artifact ( lib , use_pic ) 364for li in linker_inputs 365for lib in li . libraries 366] 367 368def _get_crate_and_dep_info ( dep ): 369if type ( dep ) == "Target" and rust_common . crate_info in dep : 370return ( dep [ rust_common . crate_info ], dep [ rust_common . dep_info ]) 371elif type ( dep ) == "struct" and hasattr ( dep , "crate_info" ): 372return ( dep . crate_info , dep . dep_info ) 373return ( None , None ) 374 375def _get_cc_info ( dep ): 376if type ( dep ) == "Target" and CcInfo in dep : 377return dep [ CcInfo ] 378elif type ( dep ) == "struct" and hasattr ( dep , "cc_info" ): 379return dep . cc_info 380return None 381 382def _get_build_info ( dep ): 383if type ( dep ) == "Target" and BuildInfo in dep : 384return dep [ BuildInfo ] 385elif type ( dep ) == "struct" and hasattr ( dep , "build_info" ): 386return dep . build_info 387return None 388 389def get_cc_user_link_flags ( ctx ): 390"""Get the current target's linkopt flags 391 392Args: 393ctx (ctx): The current rule's context object 394 395Returns: 396depset: The flags passed to Bazel by --linkopt option. 397""" 398return ctx . fragments . cpp . linkopts 399 400def get_linker_and_args ( ctx , attr , crate_type , cc_toolchain , feature_configuration , rpaths , add_flags_for_binary = False ): 401"""Gathers cc_common linker information 402 403Args: 404ctx (ctx): The current target's context object 405attr (struct): Attributes to use in gathering linker args 406crate_type (str): The target crate's type (i.e. "bin", "proc-macro", etc.). 407cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables. 408feature_configuration (FeatureConfiguration): Feature configuration to be queried. 409rpaths (depset): Depset of directories where loader will look for libraries at runtime. 410add_flags_for_binary (bool, optional): Whether to add "bin" link flags to the command regardless of `crate_type`. 411 412 413Returns: 414tuple: A tuple of the following items: 415- (str): The tool path for given action. 416- (sequence): A flattened command line flags for given action. 417- (dict): Environment variables to be set for given action. 418""" 419user_link_flags = get_cc_user_link_flags ( ctx ) 420 421if crate_type in ( "bin" ) or add_flags_for_binary : 422is_linking_dynamic_library = False 423action_name = CPP_LINK_EXECUTABLE_ACTION_NAME 424elif crate_type in ( "dylib" ): 425is_linking_dynamic_library = True 426action_name = CPP_LINK_NODEPS_DYNAMIC_LIBRARY_ACTION_NAME 427elif crate_type in ( "staticlib" ): 428is_linking_dynamic_library = False 429action_name = CPP_LINK_STATIC_LIBRARY_ACTION_NAME 430elif crate_type in ( "cdylib" , "proc-macro" ): 431# Proc macros get compiled as shared libraries to be loaded by the compiler. 432is_linking_dynamic_library = True 433action_name = CPP_LINK_DYNAMIC_LIBRARY_ACTION_NAME 434elif crate_type in ( "lib" , "rlib" ): 435fail ( "Invalid `crate_type` for linking action: {}" . format ( crate_type )) 436else : 437fail ( "Unknown `crate_type`: {}" . format ( crate_type )) 438 439# Add linkopts from dependencies. This includes linkopts from transitive 440# dependencies since they get merged up. 441for dep in getattr ( attr , "deps" , []): 442if CcInfo in dep and dep [ CcInfo ]. linking_context : 443for linker_input in dep [ CcInfo ]. linking_context . linker_inputs . to_list (): 444for flag in linker_input . user_link_flags : 445user_link_flags . append ( flag ) 446link_variables = cc_common . create_link_variables ( 447feature_configuration = feature_configuration , 448cc_toolchain = cc_toolchain , 449is_linking_dynamic_library = is_linking_dynamic_library , 450runtime_library_search_directories = rpaths , 451user_link_flags = user_link_flags , 452) 453link_args = cc_common . get_memory_inefficient_command_line ( 454feature_configuration = feature_configuration , 455action_name = action_name , 456variables = link_variables , 457) 458link_env = cc_common . get_environment_variables ( 459feature_configuration = feature_configuration , 460action_name = action_name , 461variables = link_variables , 462) 463ld = cc_common . get_tool_for_action ( 464feature_configuration = feature_configuration , 465action_name = action_name , 466) 467 468return ld , link_args , link_env 469 470def _process_build_scripts ( 471build_info , 472dep_info , 473compile_inputs , 474include_link_flags = True ): 475"""Gathers the outputs from a target's `cargo_build_script` action. 476 477Args: 478build_info (BuildInfo): The target Build's dependency info. 479dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 480compile_inputs (depset): A set of all files that will participate in the build. 481include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library. 482 483Returns: 484tuple: A tuple: A tuple of the following items: 485- (depset[File]): A list of all build info `OUT_DIR` File objects 486- (str): The `OUT_DIR` of the current build info 487- (File): An optional path to a generated environment file from a `cargo_build_script` target 488- (depset[File]): All direct and transitive build flags from the current build info. 489""" 490extra_inputs , out_dir , build_env_file , build_flags_files = _create_extra_input_args ( build_info , dep_info , include_link_flags = include_link_flags ) 491compile_inputs = depset ( transitive = [ extra_inputs , compile_inputs ]) 492return compile_inputs , out_dir , build_env_file , build_flags_files 493 494def _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , lib ): 495"""Constructs a disambiguating symlink for a library dependency. 496 497Args: 498actions (Actions): The rule's context actions object. 499toolchain: The Rust toolchain object. 500crate_info (CrateInfo): The target crate's info. 501lib (File): The library to symlink to. 502 503Returns: 504(File): The disambiguating symlink for the library. 505""" 506# FIXME: Once the relative order part of the native-link-modifiers rustc 507# feature is stable, we should be able to eliminate the need to construct 508# symlinks by passing the full paths to the libraries. 509# https://github.com/rust-lang/rust/issues/81490. 510 511# Take the absolute value of hash() since it could be negative. 512path_hash = abs ( hash ( lib . path )) 513lib_name = get_lib_name_for_windows ( lib ) if toolchain . target_os . startswith ( "windows" ) else get_lib_name_default ( lib ) 514 515if toolchain . target_os . startswith ( "windows" ): 516prefix = "" 517extension = ".lib" 518elif lib_name . endswith ( ".pic" ): 519# Strip the .pic suffix 520lib_name = lib_name [: - 4 ] 521prefix = "lib" 522extension = ".pic.a" 523else : 524prefix = "lib" 525extension = ".a" 526 527# Ensure the symlink follows the lib<name>.a pattern on Unix-like platforms 528# or <name>.lib on Windows. 529# Add a hash of the original library path to disambiguate libraries with the same basename. 530symlink_name = "{}{}-{}{}" . format ( prefix , lib_name , path_hash , extension ) 531 532# Add the symlink to a target crate-specific _ambiguous_libs/ subfolder, 533# to avoid possible collisions with sibling crates that may depend on the 534# same ambiguous libraries. 535symlink = actions . declare_file ( "_ambiguous_libs/" + crate_info . output . basename + "/" + symlink_name ) 536actions . symlink ( 537output = symlink , 538target_file = lib , 539progress_message = "Creating symlink to ambiguous lib: {}" . format ( lib . path ), 540) 541return symlink 542 543def _disambiguate_libs ( actions , toolchain , crate_info , dep_info , use_pic ): 544"""Constructs disambiguating symlinks for ambiguous library dependencies. 545 546The symlinks are all created in a _ambiguous_libs/ subfolder specific to 547the target crate to avoid possible collisions with sibling crates that may 548depend on the same ambiguous libraries. 549 550Args: 551actions (Actions): The rule's context actions object. 552toolchain: The Rust toolchain object. 553crate_info (CrateInfo): The target crate's info. 554dep_info: (DepInfo): The target crate's dependency info. 555use_pic: (boolean): Whether the build should use PIC. 556 557Returns: 558dict[String, File]: A mapping from ambiguous library paths to their 559disambiguating symlink. 560""" 561# FIXME: Once the relative order part of the native-link-modifiers rustc 562# feature is stable, we should be able to eliminate the need to construct 563# symlinks by passing the full paths to the libraries. 564# https://github.com/rust-lang/rust/issues/81490. 565 566# A dictionary from file paths of ambiguous libraries to the corresponding 567# symlink. 568ambiguous_libs = {} 569 570# A dictionary maintaining a mapping from preferred library name to the 571# last visited artifact with that name. 572visited_libs = {} 573for link_input in dep_info . transitive_noncrates . to_list (): 574for lib in link_input . libraries : 575# FIXME: Dynamic libs are not disambiguated right now, there are 576# cases where those have a non-standard name with version (e.g., 577# //test/unit/versioned_libs). We hope that the link modifiers 578# stabilization will come before we need to make this work. 579if _is_dylib ( lib ): 580 continue 581artifact = get_preferred_artifact ( lib , use_pic ) 582name = get_lib_name_for_windows ( artifact ) if toolchain . target_os . startswith ( "windows" ) else get_lib_name_default ( artifact ) 583 584# On Linux-like platforms, normally library base names start with 585# `lib`, following the pattern `lib[name].(a|lo)` and we pass 586# -lstatic=name. 587# On Windows, the base name looks like `name.lib` and we pass 588# -lstatic=name. 589# FIXME: Under the native-link-modifiers unstable rustc feature, 590# we could use -lstatic:+verbatim instead. 591needs_symlink_to_standardize_name = ( 592toolchain . target_os . startswith (( "linux" , "mac" , "darwin" )) and 593artifact . basename . endswith ( ".a" ) and not artifact . basename . startswith ( "lib" ) 594) or ( 595toolchain . target_os . startswith ( "windows" ) and not artifact . basename . endswith ( ".lib" ) 596) 597 598# Detect cases where we need to disambiguate library dependencies 599# by constructing symlinks. 600if ( 601needs_symlink_to_standardize_name or 602# We have multiple libraries with the same name. 603( name in visited_libs and visited_libs [ name ]. path != artifact . path ) 604): 605# Disambiguate the previously visited library (if we just detected 606# that it is ambiguous) and the current library. 607if name in visited_libs : 608old_path = visited_libs [ name ]. path 609if old_path not in ambiguous_libs : 610ambiguous_libs [ old_path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , visited_libs [ name ]) 611ambiguous_libs [ artifact . path ] = _symlink_for_ambiguous_lib ( actions , toolchain , crate_info , artifact ) 612 613visited_libs [ name ] = artifact 614return ambiguous_libs 615 616def _depend_on_metadata ( crate_info , force_depend_on_objects ): 617"""Determines if we can depend on metadata for this crate. 618 619By default (when pipelining is disabled or when the crate type needs to link against 620objects) we depend on the set of object files (.rlib). 621When pipelining is enabled and the crate type supports depending on metadata, 622we depend on metadata files only (.rmeta). 623In some rare cases, even if both of those conditions are true, we still want to 624depend on objects. This is what force_depend_on_objects is. 625 626Args: 627crate_info (CrateInfo): The Crate to determine this for. 628force_depend_on_objects (bool): if set we will not depend on metadata. 629 630Returns: 631Whether we can depend on metadata for this crate. 632""" 633if force_depend_on_objects : 634return False 635 636return crate_info . type in ( "rlib" , "lib" ) 637 638def collect_inputs ( 639ctx , 640file , 641files , 642linkstamps , 643toolchain , 644cc_toolchain , 645feature_configuration , 646crate_info , 647dep_info , 648build_info , 649stamp = False , 650force_depend_on_objects = False , 651experimental_use_cc_common_link = False , 652include_link_flags = True ): 653"""Gather's the inputs and required input information for a rustc action 654 655Args: 656ctx (ctx): The rule's context object. 657file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 658files (list): A list of all inputs (`ctx.files`). 659linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries. 660toolchain (rust_toolchain): The current `rust_toolchain`. 661cc_toolchain (CcToolchainInfo): The current `cc_toolchain`. 662feature_configuration (FeatureConfiguration): Feature configuration to be queried. 663crate_info (CrateInfo): The Crate information of the crate to process build scripts for. 664dep_info (DepInfo): The target Crate's dependency information. 665build_info (BuildInfo): The target Crate's build settings. 666stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 667https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 668force_depend_on_objects (bool, optional): Forces dependencies of this rule to be objects rather than 669metadata, even for libraries. This is used in rustdoc tests. 670experimental_use_cc_common_link (bool, optional): Whether rules_rust uses cc_common.link to link 671rust binaries. 672include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library. 673 674Returns: 675tuple: A tuple: A tuple of the following items: 676- (list): A list of all build info `OUT_DIR` File objects 677- (str): The `OUT_DIR` of the current build info 678- (File): An optional path to a generated environment file from a `cargo_build_script` target 679- (depset[File]): All direct and transitive build flag files from the current build info 680- (list[File]): Linkstamp outputs 681- (dict[String, File]): Ambiguous libs, see `_disambiguate_libs`. 682""" 683linker_script = getattr ( file , "linker_script" ) if hasattr ( file , "linker_script" ) else None 684 685# TODO: As of writing this comment Bazel used Java CcToolchainInfo. 686# However there is ongoing work to rewrite provider in Starlark. 687# rules_rust is not coupled with Bazel release. Remove conditional and change to 688# _linker_files once Starlark CcToolchainInfo is visible to Bazel. 689# https://github.com/bazelbuild/rules_rust/issues/2425 690if hasattr ( cc_toolchain , "_linker_files" ): 691linker_depset = cc_toolchain . _linker_files 692else : 693linker_depset = cc_toolchain . linker_files () 694compilation_mode = ctx . var [ "COMPILATION_MODE" ] 695 696use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type , compilation_mode ) 697 698# Pass linker inputs only for linking-like actions, not for example where 699# the output is rlib. This avoids quadratic behavior where transitive noncrates are 700# flattened on each transitive rust_library dependency. 701additional_transitive_inputs = [] 702ambiguous_libs = {} 703if crate_info . type not in ( "lib" , "rlib" ): 704linker_inputs = dep_info . transitive_noncrates . to_list () 705ambiguous_libs = _disambiguate_libs ( ctx . actions , toolchain , crate_info , dep_info , use_pic ) 706additional_transitive_inputs = _collect_libs_from_linker_inputs ( linker_inputs , use_pic ) + [ 707additional_input 708for linker_input in linker_inputs 709for additional_input in linker_input . additional_inputs 710] + ambiguous_libs . values () 711 712# Compute linkstamps. Use the inputs of the binary as inputs to the 713# linkstamp action to ensure linkstamps are rebuilt whenever binary inputs 714# change. 715linkstamp_outs = [] 716 717transitive_crate_outputs = dep_info . transitive_crate_outputs 718if _depend_on_metadata ( crate_info , force_depend_on_objects ): 719transitive_crate_outputs = dep_info . transitive_metadata_outputs 720 721build_info_inputs = [] 722if build_info : 723if build_info . rustc_env : 724build_info_inputs . append ( build_info . rustc_env ) 725if build_info . flags : 726build_info_inputs . append ( build_info . flags ) 727 728nolinkstamp_compile_inputs = depset ( 729getattr ( files , "data" , []) + 730build_info_inputs + 731([ toolchain . target_json ] if toolchain . target_json else []) + 732([] if linker_script == None else [ linker_script ]), 733transitive = [ 734linker_depset , 735crate_info . srcs , 736transitive_crate_outputs , 737depset ( additional_transitive_inputs ), 738crate_info . compile_data , 739dep_info . transitive_proc_macro_data , 740toolchain . all_files , 741], 742) 743 744# Register linkstamps when linking with rustc (when linking with 745# cc_common.link linkstamps are handled by cc_common.link itself). 746if not experimental_use_cc_common_link and crate_info . type in ( "bin" , "cdylib" ): 747# There is no other way to register an action for each member of a depset than 748# flattening the depset as of 2021-10-12. Luckily, usually there is only one linkstamp 749# in a build, and we only flatten the list on binary targets that perform transitive linking, 750# so it's extremely unlikely that this call to `to_list()` will ever be a performance 751# problem. 752for linkstamp in linkstamps . to_list (): 753# The linkstamp output path is based on the binary crate 754# name and the input linkstamp path. This is to disambiguate 755# the linkstamp outputs produced by multiple binary crates 756# that depend on the same linkstamp. We use the same pattern 757# for the output name as the one used by native cc rules. 758out_name = "_objs/" + crate_info . output . basename + "/" + linkstamp . file (). path [: - len ( linkstamp . file (). extension )] + "o" 759linkstamp_out = ctx . actions . declare_file ( out_name ) 760linkstamp_outs . append ( linkstamp_out ) 761cc_common . register_linkstamp_compile_action ( 762actions = ctx . actions , 763cc_toolchain = cc_toolchain , 764feature_configuration = feature_configuration , 765source_file = linkstamp . file (), 766output_file = linkstamp_out , 767compilation_inputs = linkstamp . hdrs (), 768inputs_for_validation = nolinkstamp_compile_inputs , 769label_replacement = str ( ctx . label ), 770output_replacement = crate_info . output . path , 771) 772 773# If stamping is enabled include the volatile and stable status info file 774stamp_info = [ ctx . version_file , ctx . info_file ] if stamp else [] 775 776compile_inputs = depset ( 777linkstamp_outs + stamp_info , 778transitive = [ 779nolinkstamp_compile_inputs , 780], 781) 782 783# For backwards compatibility, we also check the value of the `rustc_env_files` attribute when 784# `crate_info.rustc_env_files` is not populated. 785build_env_files = crate_info . rustc_env_files if crate_info . rustc_env_files else getattr ( files , "rustc_env_files" , []) 786compile_inputs , out_dir , build_env_file , build_flags_files = _process_build_scripts ( build_info , dep_info , compile_inputs , include_link_flags = include_link_flags ) 787if build_env_file : 788build_env_files = [ f for f in build_env_files ] + [ build_env_file ] 789compile_inputs = depset ( build_env_files , transitive = [ compile_inputs ]) 790return compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs 791 792def construct_arguments ( 793ctx , 794attr , 795file , 796toolchain , 797tool_path , 798cc_toolchain , 799feature_configuration , 800crate_info , 801dep_info , 802linkstamp_outs , 803ambiguous_libs , 804output_hash , 805rust_flags , 806out_dir , 807build_env_files , 808build_flags_files , 809emit = [ "dep-info" , "link" ], 810force_all_deps_direct = False , 811add_flags_for_binary = False , 812include_link_flags = True , 813stamp = False , 814remap_path_prefix = "" , 815use_json_output = False , 816build_metadata = False , 817force_depend_on_objects = False , 818skip_expanding_rustc_env = False ): 819"""Builds an Args object containing common rustc flags 820 821Args: 822ctx (ctx): The rule's context object 823attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context. 824file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`. 825toolchain (rust_toolchain): The current target's `rust_toolchain` 826tool_path (str): Path to rustc 827cc_toolchain (CcToolchain): The CcToolchain for the current target. 828feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features. 829crate_info (CrateInfo): The CrateInfo provider of the target crate 830dep_info (DepInfo): The DepInfo provider of the target crate 831linkstamp_outs (list): Linkstamp outputs of native dependencies 832ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 833output_hash (str): The hashed path of the crate root 834rust_flags (list): Additional flags to pass to rustc 835out_dir (str): The path to the output directory for the target Crate. 836build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions. 837build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags 838emit (list): Values for the --emit flag to rustc. 839force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 840to the commandline as opposed to -L. 841add_flags_for_binary (bool, optional): Whether to add "bin" link flags to the command regardless of `emit` and `crate_type`. 842include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library. 843stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see 844https://docs.bazel.build/versions/main/user-manual.html#flag--stamp 845remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to None, no prefix will be set. 846use_json_output (bool): Have rustc emit json and process_wrapper parse json messages to output rendered output. 847build_metadata (bool): Generate CLI arguments for building *only* .rmeta files. This requires use_json_output. 848force_depend_on_objects (bool): Force using `.rlib` object files instead of metadata (`.rmeta`) files even if they are available. 849skip_expanding_rustc_env (bool): Whether to skip expanding CrateInfo.rustc_env_attr 850 851Returns: 852tuple: A tuple of the following items 853- (struct): A struct of arguments used to run the `Rustc` action 854- process_wrapper_flags (Args): Arguments for the process wrapper 855- rustc_path (Args): Arguments for invoking rustc via the process wrapper 856- rustc_flags (Args): Rust flags for the Rust compiler 857- all (list): A list of all `Args` objects in the order listed above. 858This is to be passed to the `arguments` parameter of actions 859- (dict): Common rustc environment variables 860""" 861if build_metadata and not use_json_output : 862fail ( "build_metadata requires parse_json_output" ) 863 864output_dir = getattr ( crate_info . output , "dirname" , None ) 865linker_script = getattr ( file , "linker_script" , None ) 866 867env = _get_rustc_env ( attr , toolchain , crate_info . name ) 868 869# Wrapper args first 870process_wrapper_flags = ctx . actions . args () 871 872for build_env_file in build_env_files : 873process_wrapper_flags . add ( "--env-file" , build_env_file ) 874 875process_wrapper_flags . add_all ( build_flags_files , before_each = "--arg-file" ) 876 877# Certain rust build processes expect to find files from the environment 878# variable `$CARGO_MANIFEST_DIR`. Examples of this include pest, tera, 879# asakuma. 880# 881# The compiler and by extension proc-macros see the current working 882# directory as the Bazel exec root. This is what `$CARGO_MANIFEST_DIR` 883# would default to but is often the wrong value (e.g. if the source is in a 884# sub-package or if we are building something in an external repository). 885# Hence, we need to set `CARGO_MANIFEST_DIR` explicitly. 886# 887# Since we cannot get the `exec_root` from starlark, we cheat a little and 888# use `${pwd}` which resolves the `exec_root` at action execution time. 889process_wrapper_flags . add ( "--subst" , "pwd=${pwd}" ) 890 891# If stamping is enabled, enable the functionality in the process wrapper 892if stamp : 893process_wrapper_flags . add ( "--volatile-status-file" , ctx . version_file ) 894process_wrapper_flags . add ( "--stable-status-file" , ctx . info_file ) 895 896# Both ctx.label.workspace_root and ctx.label.package are relative paths 897# and either can be empty strings. Avoid trailing/double slashes in the path. 898components = "${{pwd}}/{}/{}" . format ( ctx . label . workspace_root , ctx . label . package ). split ( "/" ) 899env [ "CARGO_MANIFEST_DIR" ] = "/" . join ([ c for c in components if c ]) 900 901if out_dir != None : 902env [ "OUT_DIR" ] = "${pwd}/" + out_dir 903 904# Arguments for launching rustc from the process wrapper 905rustc_path = ctx . actions . args () 906rustc_path . add ( "--" ) 907rustc_path . add ( tool_path ) 908 909# Rustc arguments 910rustc_flags = ctx . actions . args () 911rustc_flags . set_param_file_format ( "multiline" ) 912rustc_flags . use_param_file ( "@%s" , use_always = False ) 913rustc_flags . add ( crate_info . root ) 914rustc_flags . add ( crate_info . name , format = "--crate-name=%s" ) 915rustc_flags . add ( crate_info . type , format = "--crate-type=%s" ) 916 917error_format = "human" 918if hasattr ( attr , "_error_format" ): 919error_format = attr . _error_format [ ErrorFormatInfo ]. error_format 920 921if use_json_output : 922# If --error-format was set to json, we just pass the output through 923# Otherwise process_wrapper uses the "rendered" field. 924process_wrapper_flags . add ( "--rustc-output-format" , "json" if error_format == "json" else "rendered" ) 925 926# Configure rustc json output by adding artifact notifications. 927# These will always be filtered out by process_wrapper and will be use to terminate 928# rustc when appropriate. 929json = [ "artifacts" ] 930if error_format == "short" : 931json . append ( "diagnostic-short" ) 932elif error_format == "human" and toolchain . target_os != "windows" : 933# If the os is not windows, we can get colorized output. 934json . append ( "diagnostic-rendered-ansi" ) 935 936rustc_flags . add_joined ( json , format_joined = "--json=%s" , join_with = "," ) 937 938error_format = "json" 939 940if build_metadata : 941# Configure process_wrapper to terminate rustc when metadata are emitted 942process_wrapper_flags . add ( "--rustc-quit-on-rmeta" , "true" ) 943if crate_info . rustc_rmeta_output : 944process_wrapper_flags . add ( "--output-file" , crate_info . rustc_rmeta_output . path ) 945elif crate_info . rustc_output : 946process_wrapper_flags . add ( "--output-file" , crate_info . rustc_output . path ) 947 948rustc_flags . add ( error_format , format = "--error-format=%s" ) 949 950# Mangle symbols to disambiguate crates with the same name. This could 951# happen only for non-final artifacts where we compute an output_hash, 952# e.g., rust_library. 953# 954# For "final" artifacts and ones intended for distribution outside of 955# Bazel, such as rust_binary, rust_static_library and rust_shared_library, 956# where output_hash is None we don't need to add these flags. 957if output_hash : 958rustc_flags . add ( output_hash , format = "--codegen=metadata=-%s" ) 959rustc_flags . add ( output_hash , format = "--codegen=extra-filename=-%s" ) 960 961if output_dir : 962rustc_flags . add ( output_dir , format = "--out-dir=%s" ) 963 964compilation_mode = get_compilation_mode_opts ( ctx , toolchain ) 965rustc_flags . add ( compilation_mode . opt_level , format = "--codegen=opt-level=%s" ) 966rustc_flags . add ( compilation_mode . debug_info , format = "--codegen=debuginfo=%s" ) 967rustc_flags . add ( compilation_mode . strip_level , format = "--codegen=strip=%s" ) 968 969# For determinism to help with build distribution and such 970if remap_path_prefix != None : 971rustc_flags . add ( "--remap-path-prefix=${{pwd}}={}" . format ( remap_path_prefix )) 972 973emit_without_paths = [] 974for kind in emit : 975if kind == "link" and crate_info . type == "bin" and crate_info . output != None : 976rustc_flags . add ( crate_info . output , format = "--emit=link=%s" ) 977else : 978emit_without_paths . append ( kind ) 979 980if emit_without_paths : 981rustc_flags . add_joined ( emit_without_paths , format_joined = "--emit=%s" , join_with = "," ) 982if error_format != "json" : 983# Color is not compatible with json output. 984rustc_flags . add ( "--color=always" ) 985rustc_flags . add ( toolchain . target_flag_value , format = "--target=%s" ) 986if hasattr ( attr , "crate_features" ): 987rustc_flags . add_all ( getattr ( attr , "crate_features" ), before_each = "--cfg" , format_each = 'feature="%s"' ) 988if linker_script : 989rustc_flags . add ( linker_script , format = "--codegen=link-arg=-T%s" ) 990 991# Tell Rustc where to find the standard library (or libcore) 992rustc_flags . add_all ( toolchain . rust_std_paths , before_each = "-L" , format_each = "%s" ) 993rustc_flags . add_all ( rust_flags ) 994 995# Gather data path from crate_info since it is inherited from real crate for rust_doc and rust_test 996# Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681 997data_paths = depset ( direct = getattr ( attr , "data" , []), transitive = [ crate_info . compile_data_targets ]). to_list () 998 999rustc_flags . add_all ( 1000expand_list_element_locations ( 1001ctx , 1002getattr ( attr , "rustc_flags" , []), 1003data_paths , 1004), 1005) 1006add_edition_flags ( rustc_flags , crate_info ) 1007 1008# Link! 1009if ( "link" in emit and crate_info . type not in [ "rlib" , "lib" ]) or add_flags_for_binary : 1010# Rust's built-in linker can handle linking wasm files. We don't want to attempt to use the cc 1011# linker since it won't understand. 1012compilation_mode = ctx . var [ "COMPILATION_MODE" ] 1013if toolchain . target_arch != "wasm32" : 1014if output_dir : 1015use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_info . type , compilation_mode ) 1016rpaths = _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ) 1017else : 1018rpaths = depset () 1019 1020ld , link_args , link_env = get_linker_and_args ( ctx , attr , crate_info . type , cc_toolchain , feature_configuration , rpaths , add_flags_for_binary = add_flags_for_binary ) 1021 1022env . update ( link_env ) 1023rustc_flags . add ( ld , format = "--codegen=linker=%s" ) 1024 1025# Split link args into individual "--codegen=link-arg=" flags to handle nested spaces. 1026# Additional context: https://github.com/rust-lang/rust/pull/36574 1027rustc_flags . add_all ( link_args , format_each = "--codegen=link-arg=%s" ) 1028 1029_add_native_link_flags ( rustc_flags , dep_info , linkstamp_outs , ambiguous_libs , crate_info . type , toolchain , cc_toolchain , feature_configuration , compilation_mode , include_link_flags = include_link_flags ) 1030 1031use_metadata = _depend_on_metadata ( crate_info , force_depend_on_objects ) 1032 1033# These always need to be added, even if not linking this crate. 1034add_crate_link_flags ( rustc_flags , dep_info , force_all_deps_direct , use_metadata ) 1035 1036needs_extern_proc_macro_flag = _is_proc_macro ( crate_info ) and crate_info . edition != "2015" 1037if needs_extern_proc_macro_flag : 1038rustc_flags . add ( "--extern" ) 1039rustc_flags . add ( "proc_macro" ) 1040 1041if toolchain . llvm_cov and ctx . configuration . coverage_enabled : 1042# https://doc.rust-lang.org/rustc/instrument-coverage.html 1043rustc_flags . add ( "--codegen=instrument-coverage" ) 1044 1045if toolchain . _experimental_link_std_dylib : 1046rustc_flags . add ( "--codegen=prefer-dynamic" ) 1047 1048# Make bin crate data deps available to tests. 1049for data in getattr ( attr , "data" , []): 1050if rust_common . crate_info in data : 1051dep_crate_info = data [ rust_common . crate_info ] 1052if dep_crate_info . type == "bin" : 1053# Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists 1054env_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 1055env [ "CARGO_BIN_EXE_" + env_basename ] = dep_crate_info . output . short_path 1056 1057# Add environment variables from the Rust toolchain. 1058env . update ( toolchain . env ) 1059 1060# Update environment with user provided variables. 1061if skip_expanding_rustc_env : 1062env . update ( crate_info . rustc_env ) 1063else : 1064env . update ( expand_dict_value_locations ( 1065ctx , 1066crate_info . rustc_env , 1067data_paths , 1068)) 1069 1070# Ensure the sysroot is set for the target platform 1071if toolchain . _experimental_toolchain_generated_sysroot : 1072rustc_flags . add ( toolchain . sysroot , format = "--sysroot=%s" ) 1073 1074if toolchain . _rename_first_party_crates : 1075env [ "RULES_RUST_THIRD_PARTY_DIR" ] = toolchain . _third_party_dir 1076 1077if crate_info . type in toolchain . extra_rustc_flags_for_crate_types . keys (): 1078rustc_flags . add_all ( toolchain . extra_rustc_flags_for_crate_types [ crate_info . type ]) 1079 1080if is_exec_configuration ( ctx ): 1081rustc_flags . add_all ( toolchain . extra_exec_rustc_flags ) 1082else : 1083rustc_flags . add_all ( toolchain . extra_rustc_flags ) 1084 1085# extra_rustc_flags apply to the target configuration, not the exec configuration. 1086if hasattr ( ctx . attr , "_extra_rustc_flags" ) and not is_exec_configuration ( ctx ): 1087rustc_flags . add_all ( ctx . attr . _extra_rustc_flags [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 1088 1089if hasattr ( ctx . attr , "_extra_rustc_flag" ) and not is_exec_configuration ( ctx ): 1090rustc_flags . add_all ( ctx . attr . _extra_rustc_flag [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 1091 1092if hasattr ( ctx . attr , "_per_crate_rustc_flag" ) and not is_exec_configuration ( ctx ): 1093per_crate_rustc_flags = ctx . attr . _per_crate_rustc_flag [ PerCrateRustcFlagsInfo ]. per_crate_rustc_flags 1094_add_per_crate_rustc_flags ( ctx , rustc_flags , crate_info , per_crate_rustc_flags ) 1095 1096if hasattr ( ctx . attr , "_extra_exec_rustc_flags" ) and is_exec_configuration ( ctx ): 1097rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flags [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 1098 1099if hasattr ( ctx . attr , "_extra_exec_rustc_flag" ) and is_exec_configuration ( ctx ): 1100rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flag [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 1101 1102if _is_no_std ( ctx , toolchain , crate_info ): 1103rustc_flags . add ( '--cfg=feature="no_std"' ) 1104 1105# Needed for bzlmod-aware runfiles resolution. 1106env [ "REPOSITORY_NAME" ] = ctx . label . workspace_name 1107 1108# Create a struct which keeps the arguments separate so each may be tuned or 1109# replaced where necessary 1110args = struct ( 1111process_wrapper_flags = process_wrapper_flags , 1112rustc_path = rustc_path , 1113rustc_flags = rustc_flags , 1114all = [ process_wrapper_flags , rustc_path , rustc_flags ], 1115) 1116 1117return args , env 1118 1119def rustc_compile_action ( 1120ctx , 1121attr , 1122toolchain , 1123rust_flags = [], 1124output_hash = None , 1125force_all_deps_direct = False , 1126crate_info_dict = None , 1127skip_expanding_rustc_env = False , 1128include_coverage = True ): 1129"""Create and run a rustc compile action based on the current rule's attributes 1130 1131Args: 1132ctx (ctx): The rule's context object 1133attr (struct): Attributes to use for the rust compile action 1134toolchain (rust_toolchain): The current `rust_toolchain` 1135output_hash (str, optional): The hashed path of the crate root. Defaults to None. 1136rust_flags (list, optional): Additional flags to pass to rustc. Defaults to []. 1137force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 1138to the commandline as opposed to -L. 1139crate_info_dict: A mutable dict used to create CrateInfo provider 1140skip_expanding_rustc_env (bool, optional): Whether to expand CrateInfo.rustc_env 1141include_coverage (bool, optional): Whether to generate coverage information or not. 1142 1143Returns: 1144list: A list of the following providers: 1145- (CrateInfo): info for the crate we just built; same as `crate_info` parameter. 1146- (DepInfo): The transitive dependencies of this crate. 1147- (DefaultInfo): The output file for this crate, and its runfiles. 1148""" 1149crate_info = rust_common . create_crate_info ( ** crate_info_dict ) 1150 1151build_metadata = crate_info_dict . get ( "metadata" , None ) 1152rustc_output = crate_info_dict . get ( "rustc_output" , None ) 1153rustc_rmeta_output = crate_info_dict . get ( "rustc_rmeta_output" , None ) 1154 1155# Determine whether to use cc_common.link: 1156# * either if experimental_use_cc_common_link is 1, 1157# * or if experimental_use_cc_common_link is -1 and 1158# the toolchain experimental_use_cc_common_link is true. 1159experimental_use_cc_common_link = False 1160if hasattr ( ctx . attr , "experimental_use_cc_common_link" ): 1161if ctx . attr . experimental_use_cc_common_link == 0 : 1162experimental_use_cc_common_link = False 1163elif ctx . attr . experimental_use_cc_common_link == 1 : 1164experimental_use_cc_common_link = True 1165elif ctx . attr . experimental_use_cc_common_link == - 1 : 1166experimental_use_cc_common_link = toolchain . _experimental_use_cc_common_link 1167 1168dep_info , build_info , linkstamps = collect_deps ( 1169deps = crate_info_dict [ "deps" ], 1170proc_macro_deps = crate_info_dict [ "proc_macro_deps" ], 1171aliases = crate_info_dict [ "aliases" ], 1172) 1173extra_disabled_features = [ RUST_LINK_CC_FEATURE ] 1174if crate_info . type in [ "bin" , "cdylib" ] and dep_info . transitive_noncrates . to_list (): 1175# One or more of the transitive deps is a cc_library / cc_import 1176extra_disabled_features = [] 1177cc_toolchain , feature_configuration = find_cc_toolchain ( ctx , extra_disabled_features ) 1178if not _are_linkstamps_supported ( 1179feature_configuration = feature_configuration , 1180has_grep_includes = hasattr ( ctx . attr , "_use_grep_includes" ), 1181): 1182linkstamps = depset ([]) 1183 1184# Determine if the build is currently running with --stamp 1185stamp = is_stamping_enabled ( attr ) 1186 1187compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 1188ctx = ctx , 1189file = ctx . file , 1190files = ctx . files , 1191linkstamps = linkstamps , 1192toolchain = toolchain , 1193cc_toolchain = cc_toolchain , 1194feature_configuration = feature_configuration , 1195crate_info = crate_info , 1196dep_info = dep_info , 1197build_info = build_info , 1198stamp = stamp , 1199experimental_use_cc_common_link = experimental_use_cc_common_link , 1200) 1201 1202# The types of rustc outputs to emit. 1203# If we build metadata, we need to keep the command line of the two invocations 1204# (rlib and rmeta) as similar as possible, otherwise rustc rejects the rmeta as 1205# a candidate. 1206# Because of that we need to add emit=metadata to both the rlib and rmeta invocation. 1207# 1208# When cc_common linking is enabled, emit a `.o` file, which is later 1209# passed to the cc_common.link action. 1210emit = [ "dep-info" , "link" ] 1211if build_metadata : 1212emit . append ( "metadata" ) 1213if experimental_use_cc_common_link : 1214emit = [ "obj" ] 1215 1216args , env_from_args = construct_arguments ( 1217ctx = ctx , 1218attr = attr , 1219file = ctx . file , 1220toolchain = toolchain , 1221tool_path = toolchain . rustc . path , 1222cc_toolchain = cc_toolchain , 1223emit = emit , 1224feature_configuration = feature_configuration , 1225crate_info = crate_info , 1226dep_info = dep_info , 1227linkstamp_outs = linkstamp_outs , 1228ambiguous_libs = ambiguous_libs , 1229output_hash = output_hash , 1230rust_flags = rust_flags , 1231out_dir = out_dir , 1232build_env_files = build_env_files , 1233build_flags_files = build_flags_files , 1234force_all_deps_direct = force_all_deps_direct , 1235stamp = stamp , 1236use_json_output = bool ( build_metadata ) or bool ( rustc_output ) or bool ( rustc_rmeta_output ), 1237skip_expanding_rustc_env = skip_expanding_rustc_env , 1238) 1239 1240args_metadata = None 1241if build_metadata : 1242args_metadata , _ = construct_arguments ( 1243ctx = ctx , 1244attr = attr , 1245file = ctx . file , 1246toolchain = toolchain , 1247tool_path = toolchain . rustc . path , 1248cc_toolchain = cc_toolchain , 1249emit = emit , 1250feature_configuration = feature_configuration , 1251crate_info = crate_info , 1252dep_info = dep_info , 1253linkstamp_outs = linkstamp_outs , 1254ambiguous_libs = ambiguous_libs , 1255output_hash = output_hash , 1256rust_flags = rust_flags , 1257out_dir = out_dir , 1258build_env_files = build_env_files , 1259build_flags_files = build_flags_files , 1260force_all_deps_direct = force_all_deps_direct , 1261stamp = stamp , 1262use_json_output = True , 1263build_metadata = True , 1264) 1265 1266env = dict ( ctx . configuration . default_shell_env ) 1267 1268# this is the final list of env vars 1269env . update ( env_from_args ) 1270 1271if hasattr ( attr , "version" ) and attr . version != "0.0.0" : 1272formatted_version = " v{}" . format ( attr . version ) 1273else : 1274formatted_version = "" 1275 1276# Declares the outputs of the rustc compile action. 1277# By default this is the binary output; if cc_common.link is used, this is 1278# the main `.o` file (`output_o` below). 1279outputs = [ crate_info . output ] 1280 1281# The `.o` output file, only used for linking via cc_common.link. 1282output_o = None 1283if experimental_use_cc_common_link : 1284obj_ext = ".o" 1285output_o = ctx . actions . declare_file ( crate_info . name + obj_ext , sibling = crate_info . output ) 1286outputs = [ output_o ] 1287 1288# For a cdylib that might be added as a dependency to a cc_* target on Windows, it is important to include the 1289# interface library that rustc generates in the output files. 1290interface_library = None 1291if toolchain . target_os == "windows" and crate_info . type == "cdylib" : 1292# Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc 1293# expects (see https://github.com/rust-lang/rust/pull/29520 for more context). 1294interface_library = ctx . actions . declare_file ( crate_info . output . basename + ".lib" , sibling = crate_info . output ) 1295outputs . append ( interface_library ) 1296 1297# The action might generate extra output that we don't want to include in the `DefaultInfo` files. 1298action_outputs = list ( outputs ) 1299if rustc_output : 1300action_outputs . append ( rustc_output ) 1301 1302# Get the compilation mode for the current target. 1303compilation_mode = get_compilation_mode_opts ( ctx , toolchain ) 1304 1305# Rustc generates a pdb file (on Windows) or a dsym folder (on macos) so provide it in an output group for crate 1306# types that benefit from having debug information in a separate file. 1307pdb_file = None 1308dsym_folder = None 1309if crate_info . type in ( "cdylib" , "bin" ): 1310if toolchain . target_os == "windows" and compilation_mode . strip_level == "none" : 1311pdb_file = ctx . actions . declare_file ( crate_info . output . basename [: - len ( crate_info . output . extension )] + "pdb" , sibling = crate_info . output ) 1312action_outputs . append ( pdb_file ) 1313elif toolchain . target_os == "darwin" : 1314dsym_folder = ctx . actions . declare_directory ( crate_info . output . basename + ".dSYM" , sibling = crate_info . output ) 1315action_outputs . append ( dsym_folder ) 1316 1317if ctx . executable . _process_wrapper : 1318# Run as normal 1319ctx . actions . run ( 1320executable = ctx . executable . _process_wrapper , 1321inputs = compile_inputs , 1322outputs = action_outputs , 1323env = env , 1324arguments = args . all , 1325mnemonic = "Rustc" , 1326progress_message = "Compiling Rust {} {}{} ({} files)" . format ( 1327crate_info . type , 1328ctx . label . name , 1329formatted_version , 1330len ( crate_info . srcs . to_list ()), 1331), 1332toolchain = "@rules_rust//rust:toolchain_type" , 1333) 1334if args_metadata : 1335ctx . actions . run ( 1336executable = ctx . executable . _process_wrapper , 1337inputs = compile_inputs , 1338outputs = [ build_metadata ] + [ x for x in [ rustc_rmeta_output ] if x ], 1339env = env , 1340arguments = args_metadata . all , 1341mnemonic = "RustcMetadata" , 1342progress_message = "Compiling Rust metadata {} {}{} ({} files)" . format ( 1343crate_info . type , 1344ctx . label . name , 1345formatted_version , 1346len ( crate_info . srcs . to_list ()), 1347), 1348toolchain = "@rules_rust//rust:toolchain_type" , 1349) 1350elif hasattr ( ctx . executable , "_bootstrap_process_wrapper" ): 1351# Run without process_wrapper 1352if build_env_files or build_flags_files or stamp or build_metadata : 1353fail ( "build_env_files, build_flags_files, stamp, build_metadata are not supported when building without process_wrapper" ) 1354ctx . actions . run ( 1355executable = ctx . executable . _bootstrap_process_wrapper , 1356inputs = compile_inputs , 1357outputs = action_outputs , 1358env = env , 1359arguments = [ args . rustc_path , args . rustc_flags ], 1360mnemonic = "Rustc" , 1361progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)" . format ( 1362crate_info . type , 1363ctx . label . name , 1364formatted_version , 1365len ( crate_info . srcs . to_list ()), 1366), 1367toolchain = "@rules_rust//rust:toolchain_type" , 1368) 1369else : 1370fail ( "No process wrapper was defined for {}" . format ( ctx . label )) 1371 1372if experimental_use_cc_common_link : 1373# Wrap the main `.o` file into a compilation output suitable for 1374# cc_common.link. The main `.o` file is useful in both PIC and non-PIC 1375# modes. 1376compilation_outputs = cc_common . create_compilation_outputs ( 1377objects = depset ([ output_o ]), 1378pic_objects = depset ([ output_o ]), 1379) 1380 1381malloc_library = ctx . attr . _custom_malloc or ctx . attr . malloc 1382 1383# Collect the linking contexts of the standard library and dependencies. 1384linking_contexts = [ 1385malloc_library [ CcInfo ]. linking_context , 1386_get_std_and_alloc_info ( ctx , toolchain , crate_info ). linking_context , 1387toolchain . stdlib_linkflags . linking_context , 1388] 1389 1390for dep in crate_info . deps . to_list (): 1391if dep . cc_info : 1392linking_contexts . append ( dep . cc_info . linking_context ) 1393 1394# In the cc_common.link action we need to pass the name of the final 1395# binary (output) relative to the package of this target. 1396# We compute it by stripping the path to the package directory, 1397# which is a prefix of the path of `crate_info.output`. 1398 1399# The path to the package dir, including a trailing "/". 1400package_dir = ctx . bin_dir . path + "/" 1401 1402# For external repositories, workspace root is not part of the output 1403# path when sibling repository layout is used (the repository name is 1404# part of the bin_dir). This scenario happens when the workspace root 1405# starts with "../" 1406if ctx . label . workspace_root and not ctx . label . workspace_root . startswith ( "../" ): 1407package_dir = package_dir + ctx . label . workspace_root + "/" 1408if ctx . label . package : 1409package_dir = package_dir + ctx . label . package + "/" 1410 1411if not crate_info . output . path . startswith ( package_dir ): 1412fail ( "The package dir path" , package_dir , "should be a prefix of the crate_info.output.path" , crate_info . output . path ) 1413 1414output_relative_to_package = crate_info . output . path [ len ( package_dir ):] 1415 1416# Compile actions that produce shared libraries create output of the form "libfoo.so" for linux and macos; 1417# cc_common.link expects us to pass "foo" to the name parameter. We cannot simply use crate_info.name because 1418# the name of the crate does not always match the name of output file, e.g a crate named foo-bar will produce 1419# a (lib)foo_bar output file. 1420if crate_info . type == "cdylib" : 1421output_lib = crate_info . output . basename 1422if toolchain . target_os != "windows" : 1423# Strip the leading "lib" prefix 1424output_lib = output_lib [ 3 :] 1425 1426# Strip the file extension 1427output_lib = output_lib [: - ( 1 + len ( crate_info . output . extension ))] 1428 1429# Remove the basename (which contains the undesired 'lib' prefix and the file extension) 1430output_relative_to_package = output_relative_to_package [: - len ( crate_info . output . basename )] 1431 1432# Append the name of the library 1433output_relative_to_package = output_relative_to_package + output_lib 1434 1435cc_common . link ( 1436actions = ctx . actions , 1437feature_configuration = feature_configuration , 1438cc_toolchain = cc_toolchain , 1439linking_contexts = linking_contexts , 1440compilation_outputs = compilation_outputs , 1441name = output_relative_to_package , 1442stamp = ctx . attr . stamp , 1443output_type = "executable" if crate_info . type == "bin" else "dynamic_library" , 1444) 1445 1446outputs = [ crate_info . output ] 1447 1448coverage_runfiles = [] 1449if toolchain . llvm_cov and ctx . configuration . coverage_enabled and crate_info . is_test : 1450coverage_runfiles = [ toolchain . llvm_cov , toolchain . llvm_profdata ] 1451 1452experimental_use_coverage_metadata_files = toolchain . _experimental_use_coverage_metadata_files 1453 1454dynamic_libraries = [ 1455library_to_link . dynamic_library 1456for dep in getattr ( ctx . attr , "deps" , []) 1457if CcInfo in dep 1458for linker_input in dep [ CcInfo ]. linking_context . linker_inputs . to_list () 1459for library_to_link in linker_input . libraries 1460if _is_dylib ( library_to_link ) 1461] 1462runfiles = ctx . runfiles ( 1463files = getattr ( ctx . files , "data" , []) + 1464([] if experimental_use_coverage_metadata_files else coverage_runfiles ) + 1465dynamic_libraries , 1466collect_data = True , 1467) 1468if getattr ( ctx . attr , "crate" , None ): 1469runfiles = runfiles . merge ( ctx . attr . crate [ DefaultInfo ]. default_runfiles ) 1470runfiles = runfiles . merge ( ctx . attr . crate [ DefaultInfo ]. data_runfiles ) 1471 1472# TODO: Remove after some resolution to 1473# https://github.com/bazelbuild/rules_rust/issues/771 1474out_binary = getattr ( attr , "out_binary" , False ) 1475 1476executable = crate_info . output if crate_info . type == "bin" or crate_info . is_test or out_binary else None 1477 1478instrumented_files_kwargs = { 1479"dependency_attributes" : [ "deps" , "crate" ], 1480"extensions" : [ "rs" ], 1481"source_attributes" : [ "srcs" ], 1482} 1483 1484if experimental_use_coverage_metadata_files : 1485instrumented_files_kwargs . update ({ 1486"metadata_files" : coverage_runfiles + [ executable ] if executable else [], 1487}) 1488 1489providers = [ 1490DefaultInfo ( 1491# nb. This field is required for cc_library to depend on our output. 1492files = depset ( outputs ), 1493runfiles = runfiles , 1494executable = executable , 1495), 1496] 1497 1498# When invoked by aspects (and when running `bazel coverage`), the 1499# baseline_coverage.dat created here will conflict with the baseline_coverage.dat of the 1500# underlying target, which is a build failure. So we add an option to disable it so that this 1501# function can be invoked from aspects for rules that have its own InstrumentedFilesInfo. 1502if include_coverage : 1503providers . append ( 1504coverage_common . instrumented_files_info ( 1505ctx , 1506** instrumented_files_kwargs 1507), 1508) 1509 1510if crate_info_dict != None : 1511crate_info_dict . update ({ 1512"rustc_env" : env , 1513}) 1514crate_info = rust_common . create_crate_info ( ** crate_info_dict ) 1515 1516if crate_info . type in [ "staticlib" , "cdylib" ]: 1517# These rules are not supposed to be depended on by other rust targets, and 1518# as such they shouldn't provide a CrateInfo. However, one may still want to 1519# write a rust_test for them, so we provide the CrateInfo wrapped in a provider 1520# that rust_test understands. 1521providers . extend ([ rust_common . test_crate_info ( crate = crate_info ), dep_info ]) 1522else : 1523providers . extend ([ crate_info , dep_info ]) 1524 1525providers += establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ) 1526 1527output_group_info = {} 1528 1529if pdb_file : 1530output_group_info [ "pdb_file" ] = depset ([ pdb_file ]) 1531if dsym_folder : 1532output_group_info [ "dsym_folder" ] = depset ([ dsym_folder ]) 1533if build_metadata : 1534output_group_info [ "build_metadata" ] = depset ([ build_metadata ]) 1535if build_metadata : 1536output_group_info [ "build_metadata" ] = depset ([ build_metadata ]) 1537if rustc_rmeta_output : 1538output_group_info [ "rustc_rmeta_output" ] = depset ([ rustc_rmeta_output ]) 1539if rustc_output : 1540output_group_info [ "rustc_output" ] = depset ([ rustc_output ]) 1541 1542if output_group_info : 1543providers . append ( OutputGroupInfo ( ** output_group_info )) 1544 1545return providers 1546 1547def _is_no_std ( ctx , toolchain , crate_info ): 1548if is_exec_configuration ( ctx ) or crate_info . is_test : 1549return False 1550if toolchain . _no_std == "off" : 1551return False 1552return True 1553 1554def _get_std_and_alloc_info ( ctx , toolchain , crate_info ): 1555if is_exec_configuration ( ctx ): 1556return toolchain . libstd_and_allocator_ccinfo 1557if toolchain . _experimental_use_global_allocator : 1558if _is_no_std ( ctx , toolchain , crate_info ): 1559return toolchain . nostd_and_global_allocator_cc_info 1560else : 1561return toolchain . libstd_and_global_allocator_ccinfo 1562else : 1563return toolchain . libstd_and_allocator_ccinfo 1564 1565def _is_dylib ( dep ): 1566return not bool ( dep . static_library or dep . pic_static_library ) 1567 1568def _collect_nonstatic_linker_inputs ( cc_info ): 1569shared_linker_inputs = [] 1570for linker_input in cc_info . linking_context . linker_inputs . to_list (): 1571dylibs = [ 1572lib 1573for lib in linker_input . libraries 1574if _is_dylib ( lib ) 1575] 1576if dylibs : 1577shared_linker_inputs . append ( cc_common . create_linker_input ( 1578owner = linker_input . owner , 1579libraries = depset ( dylibs ), 1580)) 1581return shared_linker_inputs 1582 1583def establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ): 1584"""If the produced crate is suitable yield a CcInfo to allow for interop with cc rules 1585 1586Args: 1587ctx (ctx): The rule's context object 1588attr (struct): Attributes to use in gathering CcInfo 1589crate_info (CrateInfo): The CrateInfo provider of the target crate 1590toolchain (rust_toolchain): The current `rust_toolchain` 1591cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo` 1592feature_configuration (FeatureConfiguration): Feature configuration to be queried. 1593interface_library (File): Optional interface library for cdylib crates on Windows. 1594 1595Returns: 1596list: A list containing the CcInfo provider 1597""" 1598 1599# A test will not need to produce CcInfo as nothing can depend on test targets 1600if crate_info . is_test : 1601return [] 1602 1603# Only generate CcInfo for particular crate types 1604if crate_info . type not in ( "staticlib" , "cdylib" , "rlib" , "lib" ): 1605return [] 1606 1607# TODO: Remove after some resolution to 1608# https://github.com/bazelbuild/rules_rust/issues/771 1609if getattr ( attr , "out_binary" , False ): 1610return [] 1611 1612if crate_info . type == "staticlib" : 1613library_to_link = cc_common . create_library_to_link ( 1614actions = ctx . actions , 1615feature_configuration = feature_configuration , 1616cc_toolchain = cc_toolchain , 1617static_library = crate_info . output , 1618# TODO(hlopko): handle PIC/NOPIC correctly 1619pic_static_library = crate_info . output , 1620alwayslink = getattr ( attr , "alwayslink" , False ), 1621) 1622elif crate_info . type in ( "rlib" , "lib" ): 1623# bazel hard-codes a check for endswith((".a", ".pic.a", 1624# ".lib")) in create_library_to_link, so we work around that 1625# by creating a symlink to the .rlib with a .a extension. 1626dot_a = make_static_lib_symlink ( ctx . label . package , ctx . actions , crate_info . output ) 1627 1628# TODO(hlopko): handle PIC/NOPIC correctly 1629library_to_link = cc_common . create_library_to_link ( 1630actions = ctx . actions , 1631feature_configuration = feature_configuration , 1632cc_toolchain = cc_toolchain , 1633static_library = dot_a , 1634# TODO(hlopko): handle PIC/NOPIC correctly 1635pic_static_library = dot_a , 1636alwayslink = getattr ( attr , "alwayslink" , False ), 1637) 1638elif crate_info . type == "cdylib" : 1639library_to_link = cc_common . create_library_to_link ( 1640actions = ctx . actions , 1641feature_configuration = feature_configuration , 1642cc_toolchain = cc_toolchain , 1643dynamic_library = crate_info . output , 1644interface_library = interface_library , 1645) 1646else : 1647fail ( "Unexpected case" ) 1648 1649link_input = cc_common . create_linker_input ( 1650owner = ctx . label , 1651libraries = depset ([ library_to_link ]), 1652) 1653 1654linking_context = cc_common . create_linking_context ( 1655# TODO - What to do for no_std? 1656linker_inputs = depset ([ link_input ]), 1657) 1658 1659cc_infos = [ 1660CcInfo ( linking_context = linking_context ), 1661toolchain . stdlib_linkflags , 1662] 1663 1664# Flattening is okay since crate_info.deps only records direct deps. 1665for dep in crate_info . deps . to_list (): 1666if dep . cc_info : 1667# A Rust staticlib or shared library doesn't need to propagate linker inputs 1668# of its dependencies, except for shared libraries. 1669if crate_info . type in [ "cdylib" , "staticlib" ]: 1670shared_linker_inputs = _collect_nonstatic_linker_inputs ( dep . cc_info ) 1671if shared_linker_inputs : 1672linking_context = cc_common . create_linking_context ( 1673linker_inputs = depset ( shared_linker_inputs ), 1674) 1675cc_infos . append ( CcInfo ( linking_context = linking_context )) 1676else : 1677cc_infos . append ( dep . cc_info ) 1678 1679if crate_info . type in ( "rlib" , "lib" ): 1680libstd_and_allocator_cc_info = _get_std_and_alloc_info ( ctx , toolchain , crate_info ) 1681if libstd_and_allocator_cc_info : 1682# TODO: if we already have an rlib in our deps, we could skip this 1683cc_infos . append ( libstd_and_allocator_cc_info ) 1684 1685return [ cc_common . merge_cc_infos ( cc_infos = cc_infos )] 1686 1687def add_edition_flags ( args , crate ): 1688"""Adds the Rust edition flag to an arguments object reference 1689 1690Args: 1691args (Args): A reference to an Args object 1692crate (CrateInfo): A CrateInfo provider 1693""" 1694if crate . edition != "2015" : 1695args . add ( crate . edition , format = "--edition=%s" ) 1696 1697def _create_extra_input_args ( build_info , dep_info , include_link_flags = True ): 1698"""Gather additional input arguments from transitive dependencies 1699 1700Args: 1701build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs. 1702dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 1703include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library. 1704 1705Returns: 1706tuple: A tuple of the following items: 1707- (depset[File]): A list of all build info `OUT_DIR` File objects 1708- (str): The `OUT_DIR` of the current build info 1709- (File): An optional generated environment file from a `cargo_build_script` target 1710- (depset[File]): All direct and transitive build flag files from the current build info to be passed to rustc. 1711""" 1712input_files = [] 1713input_depsets = [] 1714 1715# Arguments to the commandline line wrapper that are going to be used 1716# to create the final command line 1717out_dir = None 1718build_env_file = None 1719build_flags_files = [] 1720 1721if build_info : 1722if build_info . out_dir : 1723out_dir = build_info . out_dir . path 1724input_files . append ( build_info . out_dir ) 1725build_env_file = build_info . rustc_env 1726if build_info . flags : 1727build_flags_files . append ( build_info . flags ) 1728if build_info . linker_flags and include_link_flags : 1729build_flags_files . append ( build_info . linker_flags ) 1730input_files . append ( build_info . linker_flags ) 1731 1732input_depsets . append ( build_info . compile_data ) 1733 1734return ( 1735depset ( input_files , transitive = [ dep_info . link_search_path_files ] + input_depsets ), 1736out_dir , 1737build_env_file , 1738depset ( build_flags_files , transitive = [ dep_info . link_search_path_files ]), 1739) 1740 1741def _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ): 1742"""Determine the artifact's rpaths relative to the bazel root for runtime linking of shared libraries. 1743 1744Args: 1745toolchain (rust_toolchain): The current `rust_toolchain` 1746output_dir (str): The output directory of the current target 1747dep_info (DepInfo): The current target's dependency info 1748use_pic: If set, prefers pic_static_library over static_library. 1749 1750Returns: 1751depset: A set of relative paths from the output directory to each dependency 1752""" 1753 1754# Windows has no rpath equivalent, so always return an empty depset. 1755# Fuchsia assembles shared libraries during packaging. 1756if toolchain . target_os == "windows" or toolchain . target_os == "fuchsia" : 1757return depset ([]) 1758 1759dylibs = [ 1760get_preferred_artifact ( lib , use_pic ) 1761for linker_input in dep_info . transitive_noncrates . to_list () 1762for lib in linker_input . libraries 1763if _is_dylib ( lib ) 1764] 1765 1766# Include std dylib if dylib linkage is enabled 1767if toolchain . _experimental_link_std_dylib : 1768# TODO: Make toolchain.rust_std to only include libstd.so 1769# When dylib linkage is enabled, toolchain.rust_std should only need to 1770# include libstd.so. Hence, no filtering needed. 1771for file in toolchain . rust_std . to_list (): 1772if is_std_dylib ( file ): 1773dylibs . append ( file ) 1774 1775if not dylibs : 1776return depset ([]) 1777 1778# For darwin, dylibs compiled by Bazel will fail to be resolved at runtime 1779# without a version of Bazel that includes 1780# https://github.com/bazelbuild/bazel/pull/13427. This is known to not be 1781# included in Bazel 4.1 and below. 1782if toolchain . target_os not in [ "linux" , "darwin" , "android" ]: 1783fail ( "Runtime linking is not supported on {}, but found {}" . format ( 1784toolchain . target_os , 1785dep_info . transitive_noncrates , 1786)) 1787 1788# Multiple dylibs can be present in the same directory, so deduplicate them. 1789return depset ([ 1790relativize ( lib_dir , output_dir ) 1791for lib_dir in _get_dir_names ( dylibs ) 1792]) 1793 1794def _get_dir_names ( files ): 1795"""Returns a list of directory names from the given list of File objects 1796 1797Args: 1798files (list): A list of File objects 1799 1800Returns: 1801list: A list of directory names for all files 1802""" 1803dirs = {} 1804for f in files : 1805dirs [ f . dirname ] = None 1806return dirs . keys () 1807 1808def add_crate_link_flags ( args , dep_info , force_all_deps_direct = False , use_metadata = False ): 1809"""Adds link flags to an Args object reference 1810 1811Args: 1812args (Args): An arguments object reference 1813dep_info (DepInfo): The current target's dependency info 1814force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 1815to the commandline as opposed to -L. 1816use_metadata (bool, optional): Build command line arugments using metadata for crates that provide it. 1817""" 1818 1819direct_crates = depset ( 1820transitive = [ 1821dep_info . direct_crates , 1822dep_info . transitive_crates , 1823], 1824) if force_all_deps_direct else dep_info . direct_crates 1825 1826crate_to_link_flags = _crate_to_link_flag_metadata if use_metadata else _crate_to_link_flag 1827args . add_all ( direct_crates , uniquify = True , map_each = crate_to_link_flags ) 1828 1829args . add_all ( 1830dep_info . transitive_crates , 1831map_each = _get_crate_dirname , 1832uniquify = True , 1833format_each = "-Ldependency=%s" , 1834) 1835 1836def _crate_to_link_flag_metadata ( crate ): 1837"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1838 1839Args: 1840crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1841 1842Returns: 1843list: Link flags for the given provider 1844""" 1845 1846# This is AliasableDepInfo, we should use the alias as a crate name 1847if hasattr ( crate , "dep" ): 1848name = crate . name 1849crate_info = crate . dep 1850else : 1851name = crate . name 1852crate_info = crate 1853 1854lib_or_meta = crate_info . metadata 1855if not crate_info . metadata : 1856lib_or_meta = crate_info . output 1857return [ "--extern={}={}" . format ( name , lib_or_meta . path )] 1858 1859def _crate_to_link_flag ( crate ): 1860"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1861 1862Args: 1863crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1864 1865Returns: 1866list: Link flags for the given provider 1867""" 1868 1869# This is AliasableDepInfo, we should use the alias as a crate name 1870if hasattr ( crate , "dep" ): 1871name = crate . name 1872crate_info = crate . dep 1873else : 1874name = crate . name 1875crate_info = crate 1876return [ "--extern={}={}" . format ( name , crate_info . output . path )] 1877 1878def _get_crate_dirname ( crate ): 1879"""A helper macro used by `add_crate_link_flags` for getting the directory name of the current crate's output path 1880 1881Args: 1882crate (CrateInfo): A CrateInfo provider from the current rule 1883 1884Returns: 1885str: The directory name of the the output File that will be produced. 1886""" 1887return crate . output . dirname 1888 1889def _portable_link_flags ( lib , use_pic , ambiguous_libs , get_lib_name , for_windows = False , for_darwin = False , flavor_msvc = False ): 1890artifact = get_preferred_artifact ( lib , use_pic ) 1891if ambiguous_libs and artifact . path in ambiguous_libs : 1892artifact = ambiguous_libs [ artifact . path ] 1893if lib . static_library or lib . pic_static_library : 1894# To ensure appropriate linker library argument order, in the presence 1895# of both native libraries that depend on rlibs and rlibs that depend 1896# on native libraries, we use an approach where we "sandwich" the 1897# rust libraries between two similar sections of all of native 1898# libraries: 1899# n1 n2 ... r1 r2 ... n1 n2 ... 1900# A B C 1901# This way any dependency from a native library to a rust library 1902# is resolved from A to B, and any dependency from a rust library to 1903# a native one is resolved from B to C. 1904# The question of resolving dependencies from a native library from A 1905# to any rust library is addressed in a different place, where we 1906# create symlinks to the rlibs, pretending they are native libraries, 1907# and adding references to these symlinks in the native section A. 1908# We rely in the behavior of -Clink-arg to put the linker args 1909# at the end of the linker invocation constructed by rustc. 1910 1911# We skip adding `-Clink-arg=-l` for libstd and libtest from the standard library, as 1912# these two libraries are present both as an `.rlib` and a `.so` format. 1913# On linux, Rustc adds a -Bdynamic to the linker command line before the libraries specified 1914# with `-Clink-arg`, which leads to us linking against the `.so`s but not putting the 1915# corresponding value to the runtime library search paths, which results in a 1916# "cannot open shared object file: No such file or directory" error at exectuion time. 1917# We can fix this by adding a `-Clink-arg=-Bstatic` on linux, but we don't have that option for 1918# macos. The proper solution for this issue would be to remove `libtest-{hash}.so` and `libstd-{hash}.so` 1919# from the toolchain. However, it is not enough to change the toolchain's `rust_std_{...}` filegroups 1920# here: https://github.com/bazelbuild/rules_rust/blob/a9d5d894ad801002d007b858efd154e503796b9f/rust/private/repository_utils.bzl#L144 1921# because rustc manages to escape the sandbox and still finds them at linking time. 1922# We need to modify the repository rules to erase those files completely. 1923if "lib/rustlib" in artifact . path and ( 1924artifact . basename . startswith ( "libtest-" ) or artifact . basename . startswith ( "libstd-" ) or 1925artifact . basename . startswith ( "test-" ) or artifact . basename . startswith ( "std-" ) 1926): 1927return [] if for_darwin else [ "-lstatic=%s" % get_lib_name ( artifact )] 1928 1929if for_windows : 1930if flavor_msvc : 1931return [ 1932"-lstatic=%s" % get_lib_name ( artifact ), 1933"-Clink-arg={}" . format ( artifact . basename ), 1934] 1935else : 1936return [ 1937"-lstatic=%s" % get_lib_name ( artifact ), 1938"-Clink-arg=-l{}" . format ( artifact . basename ), 1939] 1940else : 1941return [ 1942"-lstatic=%s" % get_lib_name ( artifact ), 1943"-Clink-arg=-l{}" . format ( get_lib_name ( artifact )), 1944] 1945elif _is_dylib ( lib ): 1946return [ 1947"-ldylib=%s" % get_lib_name ( artifact ), 1948] 1949 1950return [] 1951 1952def _make_link_flags_windows ( make_link_flags_args , flavor_msvc ): 1953linker_input , use_pic , ambiguous_libs , include_link_flags = make_link_flags_args 1954ret = [] 1955for lib in linker_input . libraries : 1956if lib . alwayslink : 1957if flavor_msvc : 1958ret . extend ([ "-C" , "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact ( lib , use_pic ). path ]) 1959else : 1960ret . extend ([ 1961"-C" , 1962"link-arg=-Wl,--whole-archive" , 1963"-C" , 1964( "link-arg=%s" % get_preferred_artifact ( lib , use_pic ). path ), 1965"-C" , 1966"link-arg=-Wl,--no-whole-archive" , 1967]) 1968elif include_link_flags : 1969ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs , get_lib_name_for_windows , for_windows = True , flavor_msvc = flavor_msvc )) 1970return ret 1971 1972def _make_link_flags_windows_msvc ( make_link_flags_args ): 1973return _make_link_flags_windows ( make_link_flags_args , flavor_msvc = True ) 1974 1975def _make_link_flags_windows_gnu ( make_link_flags_args ): 1976return _make_link_flags_windows ( make_link_flags_args , flavor_msvc = False ) 1977 1978def _make_link_flags_darwin ( make_link_flags_args ): 1979linker_input , use_pic , ambiguous_libs , include_link_flags = make_link_flags_args 1980ret = [] 1981for lib in linker_input . libraries : 1982if lib . alwayslink : 1983ret . extend ([ 1984"-C" , 1985( "link-arg=-Wl,-force_load,%s" % get_preferred_artifact ( lib , use_pic ). path ), 1986]) 1987elif include_link_flags : 1988ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs , get_lib_name_default , for_darwin = True )) 1989return ret 1990 1991def _make_link_flags_default ( make_link_flags_args ): 1992linker_input , use_pic , ambiguous_libs , include_link_flags = make_link_flags_args 1993ret = [] 1994for lib in linker_input . libraries : 1995if lib . alwayslink : 1996ret . extend ([ 1997"-C" , 1998"link-arg=-Wl,--whole-archive" , 1999"-C" , 2000( "link-arg=%s" % get_preferred_artifact ( lib , use_pic ). path ), 2001"-C" , 2002"link-arg=-Wl,--no-whole-archive" , 2003]) 2004elif include_link_flags : 2005ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs , get_lib_name_default )) 2006return ret 2007 2008def _libraries_dirnames ( make_link_flags_args ): 2009link_input , use_pic , _ , _ = make_link_flags_args 2010 2011# De-duplicate names. 2012return depset ([ get_preferred_artifact ( lib , use_pic ). dirname for lib in link_input . libraries ]). to_list () 2013 2014def _add_native_link_flags ( args , dep_info , linkstamp_outs , ambiguous_libs , crate_type , toolchain , cc_toolchain , feature_configuration , compilation_mode , include_link_flags = True ): 2015"""Adds linker flags for all dependencies of the current target. 2016 2017Args: 2018args (Args): The Args struct for a ctx.action 2019dep_info (DepInfo): Dependency Info provider 2020linkstamp_outs (list): Linkstamp outputs of native dependencies 2021ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 2022crate_type: Crate type of the current target 2023toolchain (rust_toolchain): The current `rust_toolchain` 2024cc_toolchain (CcToolchainInfo): The current `cc_toolchain` 2025feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain 2026compilation_mode (bool): The compilation mode for this build. 2027include_link_flags (bool, optional): Whether to include flags like `-l` that instruct the linker to search for a library. 2028""" 2029if crate_type in [ "lib" , "rlib" ]: 2030return 2031 2032use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_type , compilation_mode ) 2033 2034if toolchain . target_os == "windows" : 2035make_link_flags = _make_link_flags_windows_msvc if toolchain . target_triple . abi == "msvc" else _make_link_flags_windows_gnu 2036get_lib_name = get_lib_name_for_windows 2037elif toolchain . target_os . startswith (( "mac" , "darwin" , "ios" )): 2038make_link_flags = _make_link_flags_darwin 2039get_lib_name = get_lib_name_default 2040else : 2041make_link_flags = _make_link_flags_default 2042get_lib_name = get_lib_name_default 2043 2044# TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0 2045make_link_flags_args = [( arg , use_pic , ambiguous_libs , include_link_flags ) for arg in dep_info . transitive_noncrates . to_list ()] 2046args . add_all ( make_link_flags_args , map_each = _libraries_dirnames , uniquify = True , format_each = "-Lnative=%s" ) 2047if ambiguous_libs : 2048# If there are ambiguous libs, the disambiguation symlinks to them are 2049# all created in the same directory. Add it to the library search path. 2050ambiguous_libs_dirname = ambiguous_libs . values ()[ 0 ]. dirname 2051args . add ( ambiguous_libs_dirname , format = "-Lnative=%s" ) 2052 2053args . add_all ( make_link_flags_args , map_each = make_link_flags ) 2054 2055args . add_all ( linkstamp_outs , before_each = "-C" , format_each = "link-args=%s" ) 2056 2057if crate_type in [ "dylib" , "cdylib" ]: 2058# For shared libraries we want to link C++ runtime library dynamically 2059# (for example libstdc++.so or libc++.so). 2060args . add_all ( 2061cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 2062map_each = _get_dirname , 2063format_each = "-Lnative=%s" , 2064) 2065if include_link_flags : 2066args . add_all ( 2067cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 2068map_each = get_lib_name , 2069format_each = "-ldylib=%s" , 2070) 2071else : 2072# For all other crate types we want to link C++ runtime library statically 2073# (for example libstdc++.a or libc++.a). 2074args . add_all ( 2075cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 2076map_each = _get_dirname , 2077format_each = "-Lnative=%s" , 2078) 2079if include_link_flags : 2080args . add_all ( 2081cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 2082map_each = get_lib_name , 2083format_each = "-lstatic=%s" , 2084) 2085 2086def _get_dirname ( file ): 2087"""A helper function for `_add_native_link_flags`. 2088 2089Args: 2090file (File): The target file 2091 2092Returns: 2093str: Directory name of `file` 2094""" 2095return file . dirname 2096 2097def _add_per_crate_rustc_flags ( ctx , args , crate_info , per_crate_rustc_flags ): 2098"""Adds matching per-crate rustc flags to an arguments object reference 2099 2100Args: 2101ctx (ctx): The source rule's context object 2102args (Args): A reference to an Args object 2103crate_info (CrateInfo): A CrateInfo provider 2104per_crate_rustc_flags (list): A list of per_crate_rustc_flag values 2105""" 2106for per_crate_rustc_flag in per_crate_rustc_flags : 2107at_index = per_crate_rustc_flag . find ( "@" ) 2108if at_index == - 1 : 2109fail ( "per_crate_rustc_flag '{}' does not follow the expected format: prefix_filter@flag" . format ( per_crate_rustc_flag )) 2110 2111prefix_filter = per_crate_rustc_flag [: at_index ] 2112flag = per_crate_rustc_flag [ at_index + 1 :] 2113if not flag : 2114fail ( "per_crate_rustc_flag '{}' does not follow the expected format: prefix_filter@flag" . format ( per_crate_rustc_flag )) 2115 2116label_string = str ( ctx . label ) 2117label = label_string [ 1 :] if label_string . startswith ( "@//" ) else label_string 2118execution_path = crate_info . root . path 2119 2120if label . startswith ( prefix_filter ) or execution_path . startswith ( prefix_filter ): 2121args . add ( flag ) 2122 2123def _error_format_impl ( ctx ): 2124"""Implementation of the `error_format` rule 2125 2126Args: 2127ctx (ctx): The rule's context object 2128 2129Returns: 2130list: A list containing the ErrorFormatInfo provider 2131""" 2132raw = ctx . build_setting_value 2133if raw not in _error_format_values : 2134fail ( "{} expected a value in `{}` but got `{}`" . format ( 2135ctx . label , 2136_error_format_values , 2137raw , 2138)) 2139return [ ErrorFormatInfo ( error_format = raw )] 2140 2141error_format = rule ( 2142doc = ( 2143"Change the [--error-format](https://doc.rust-lang.org/rustc/command-line-arguments.html#option-error-format) " + 2144"flag from the command line with `--@rules_rust//:error_format`. See rustc documentation for valid values." 2145), 2146implementation = _error_format_impl , 2147build_setting = config . string ( flag = True ), 2148) 2149 2150def _rustc_output_diagnostics_impl ( ctx ): 2151"""Implementation of the `rustc_output_diagnostics` rule 2152 2153Args: 2154ctx (ctx): The rule's context object 2155 2156Returns: 2157list: A list containing the RustcOutputDiagnosticsInfo provider 2158""" 2159return [ RustcOutputDiagnosticsInfo ( 2160rustc_output_diagnostics = ctx . build_setting_value , 2161)] 2162 2163rustc_output_diagnostics = rule ( 2164doc = ( 2165"Setting this flag from the command line with `--@rules_rust//:rustc_output_diagnostics` " + 2166"makes rules_rust save rustc json output(suitable for consumption by rust-analyzer) in a file. " + 2167"These are accessible via the " + 2168"`rustc_rmeta_output`(for pipelined compilation) and `rustc_output` output groups. " + 2169"You can find these using `bazel cquery`" 2170), 2171implementation = _rustc_output_diagnostics_impl , 2172build_setting = config . bool ( flag = True ), 2173) 2174 2175def _extra_rustc_flags_impl ( ctx ): 2176return ExtraRustcFlagsInfo ( extra_rustc_flags = ctx . build_setting_value ) 2177 2178extra_rustc_flags = rule ( 2179doc = ( 2180"Add additional rustc_flags from the command line with `--@rules_rust//:extra_rustc_flags`. " + 2181"This flag should only be used for flags that need to be applied across the entire build. For options that " + 2182"apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: " + 2183"These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); " + 2184"use `--@rules_rust//:extra_exec_rustc_flags` to apply flags to the exec configuration." 2185), 2186implementation = _extra_rustc_flags_impl , 2187build_setting = config . string_list ( flag = True ), 2188) 2189 2190def _extra_rustc_flag_impl ( ctx ): 2191return ExtraRustcFlagsInfo ( extra_rustc_flags = [ f for f in ctx . build_setting_value if f != "" ]) 2192 2193extra_rustc_flag = rule ( 2194doc = ( 2195"Add additional rustc_flag from the command line with `--@rules_rust//:extra_rustc_flag`. " + 2196"Multiple uses are accumulated and appended after the extra_rustc_flags." 2197), 2198implementation = _extra_rustc_flag_impl , 2199build_setting = config . string ( flag = True , allow_multiple = True ), 2200) 2201 2202def _extra_exec_rustc_flags_impl ( ctx ): 2203return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = ctx . build_setting_value ) 2204 2205extra_exec_rustc_flags = rule ( 2206doc = ( 2207"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flags`. " + 2208"This flag should only be used for flags that need to be applied across the entire build. " + 2209"These flags only apply to the exec configuration (proc-macros, cargo_build_script, etc)." 2210), 2211implementation = _extra_exec_rustc_flags_impl , 2212build_setting = config . string_list ( flag = True ), 2213) 2214 2215def _extra_exec_rustc_flag_impl ( ctx ): 2216return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = [ f for f in ctx . build_setting_value if f != "" ]) 2217 2218extra_exec_rustc_flag = rule ( 2219doc = ( 2220"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flag`. " + 2221"Multiple uses are accumulated and appended after the extra_exec_rustc_flags." 2222), 2223implementation = _extra_exec_rustc_flag_impl , 2224build_setting = config . string ( flag = True , allow_multiple = True ), 2225) 2226 2227def _per_crate_rustc_flag_impl ( ctx ): 2228return PerCrateRustcFlagsInfo ( per_crate_rustc_flags = [ f for f in ctx . build_setting_value if f != "" ]) 2229 2230per_crate_rustc_flag = rule ( 2231doc = ( 2232"Add additional rustc_flag to matching crates from the command line with `--@rules_rust//:experimental_per_crate_rustc_flag`. " + 2233"The expected flag format is prefix_filter@flag, where any crate with a label or execution path starting with the prefix filter will be built with the given flag." + 2234"The label matching uses the canonical form of the label (i.e //package:label_name)." + 2235"The execution path is the relative path to your workspace directory including the base name (including extension) of the crate root." + 2236"This flag is only applied to the exec configuration (proc-macros, cargo_build_script, etc)." + 2237"Multiple uses are accumulated." 2238), 2239implementation = _per_crate_rustc_flag_impl , 2240build_setting = config . string ( flag = True , allow_multiple = True ), 2241) 2242 2243def _no_std_impl ( ctx ): 2244value = str ( ctx . attr . _no_std [ BuildSettingInfo ]. value ) 2245if is_exec_configuration ( ctx ): 2246return [ config_common . FeatureFlagInfo ( value = "off" )] 2247return [ config_common . FeatureFlagInfo ( value = value )] 2248 2249no_std = rule ( 2250doc = ( 2251"No std; we need this so that we can distinguish between host and exec" 2252), 2253attrs = { 2254"_no_std" : attr . label ( default = "//:no_std" ), 2255}, 2256implementation = _no_std_impl , 2257)