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