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