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