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