fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
da75146d
0.7.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 808if toolchain . llvm_cov and ctx . configuration . coverage_enabled : 809rustc_flags . add ( "--codegen=instrument-coverage" ) 810 811# Make bin crate data deps available to tests. 812for data in getattr ( attr , "data" , []): 813if rust_common . crate_info in data : 814dep_crate_info = data [ rust_common . crate_info ] 815if dep_crate_info . type == "bin" : 816# Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists 817env_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 818env [ "CARGO_BIN_EXE_" + env_basename ] = dep_crate_info . output . short_path 819 820# Add environment variables from the Rust toolchain. 821env . update ( toolchain . env ) 822 823# Update environment with user provided variables. 824env . update ( expand_dict_value_locations ( 825ctx , 826crate_info . rustc_env , 827data_paths , 828)) 829 830# Ensure the sysroot is set for the target platform 831env [ "SYSROOT" ] = toolchain . sysroot 832 833if toolchain . _rename_first_party_crates : 834env [ "RULES_RUST_THIRD_PARTY_DIR" ] = toolchain . _third_party_dir 835 836# extra_rustc_flags apply to the target configuration, not the exec configuration. 837if hasattr ( ctx . attr , "_extra_rustc_flags" ) and not is_exec_configuration ( ctx ): 838rustc_flags . add_all ( ctx . attr . _extra_rustc_flags [ ExtraRustcFlagsInfo ]. extra_rustc_flags ) 839 840if hasattr ( ctx . attr , "_extra_exec_rustc_flags" ) and is_exec_configuration ( ctx ): 841rustc_flags . add_all ( ctx . attr . _extra_exec_rustc_flags [ ExtraExecRustcFlagsInfo ]. extra_exec_rustc_flags ) 842 843# Create a struct which keeps the arguments separate so each may be tuned or 844# replaced where necessary 845args = struct ( 846process_wrapper_flags = process_wrapper_flags , 847rustc_path = rustc_path , 848rustc_flags = rustc_flags , 849all = [ process_wrapper_flags , rustc_path , rustc_flags ], 850) 851 852return args , env 853 854def rustc_compile_action ( 855ctx , 856attr , 857toolchain , 858crate_info , 859output_hash = None , 860rust_flags = [], 861force_all_deps_direct = False ): 862"""Create and run a rustc compile action based on the current rule's attributes 863 864Args: 865ctx (ctx): The rule's context object 866attr (struct): Attributes to use for the rust compile action 867toolchain (rust_toolchain): The current `rust_toolchain` 868crate_info (CrateInfo): The CrateInfo provider for the current target. 869output_hash (str, optional): The hashed path of the crate root. Defaults to None. 870rust_flags (list, optional): Additional flags to pass to rustc. Defaults to []. 871force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 872to the commandline as opposed to -L. 873 874Returns: 875list: A list of the following providers: 876- (CrateInfo): info for the crate we just built; same as `crate_info` parameter. 877- (DepInfo): The transitive dependencies of this crate. 878- (DefaultInfo): The output file for this crate, and its runfiles. 879""" 880cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 881 882dep_info , build_info , linkstamps = collect_deps ( 883deps = crate_info . deps , 884proc_macro_deps = crate_info . proc_macro_deps , 885aliases = crate_info . aliases , 886are_linkstamps_supported = _are_linkstamps_supported ( 887feature_configuration = feature_configuration , 888has_grep_includes = hasattr ( ctx . attr , "_grep_includes" ), 889), 890) 891 892# Determine if the build is currently running with --stamp 893stamp = is_stamping_enabled ( attr ) 894 895compile_inputs , out_dir , build_env_files , build_flags_files , linkstamp_outs , ambiguous_libs = collect_inputs ( 896ctx = ctx , 897file = ctx . file , 898files = ctx . files , 899linkstamps = linkstamps , 900toolchain = toolchain , 901cc_toolchain = cc_toolchain , 902feature_configuration = feature_configuration , 903crate_info = crate_info , 904dep_info = dep_info , 905build_info = build_info , 906stamp = stamp , 907) 908 909args , env_from_args = construct_arguments ( 910ctx = ctx , 911attr = attr , 912file = ctx . file , 913toolchain = toolchain , 914tool_path = toolchain . rustc . path , 915cc_toolchain = cc_toolchain , 916feature_configuration = feature_configuration , 917crate_info = crate_info , 918dep_info = dep_info , 919linkstamp_outs = linkstamp_outs , 920ambiguous_libs = ambiguous_libs , 921output_hash = output_hash , 922rust_flags = rust_flags , 923out_dir = out_dir , 924build_env_files = build_env_files , 925build_flags_files = build_flags_files , 926force_all_deps_direct = force_all_deps_direct , 927stamp = stamp , 928) 929 930env = dict ( ctx . configuration . default_shell_env ) 931env . update ( env_from_args ) 932 933if hasattr ( attr , "version" ) and attr . version != "0.0.0" : 934formatted_version = " v{}" . format ( attr . version ) 935else : 936formatted_version = "" 937 938outputs = [ crate_info . output ] 939 940# For a cdylib that might be added as a dependency to a cc_* target on Windows, it is important to include the 941# interface library that rustc generates in the output files. 942interface_library = None 943if toolchain . os == "windows" and crate_info . type == "cdylib" : 944# Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc 945# expects (see https://github.com/rust-lang/rust/pull/29520 for more context). 946interface_library = ctx . actions . declare_file ( crate_info . output . basename + ".lib" , sibling = crate_info . output ) 947outputs . append ( interface_library ) 948 949# The action might generate extra output that we don't want to include in the `DefaultInfo` files. 950action_outputs = list ( outputs ) 951 952# Rustc generates a pdb file (on Windows) or a dsym folder (on macos) so provide it in an output group for crate 953# types that benefit from having debug information in a separate file. 954pdb_file = None 955dsym_folder = None 956if crate_info . type in ( "cdylib" , "bin" ) and not crate_info . is_test : 957if toolchain . os == "windows" : 958pdb_file = ctx . actions . declare_file ( crate_info . output . basename [: - len ( crate_info . output . extension )] + "pdb" , sibling = crate_info . output ) 959action_outputs . append ( pdb_file ) 960elif toolchain . os == "darwin" : 961dsym_folder = ctx . actions . declare_directory ( crate_info . output . basename + ".dSYM" , sibling = crate_info . output ) 962action_outputs . append ( dsym_folder ) 963 964if ctx . executable . _process_wrapper : 965# Run as normal 966ctx . actions . run ( 967executable = ctx . executable . _process_wrapper , 968inputs = compile_inputs , 969outputs = action_outputs , 970env = env , 971arguments = args . all , 972mnemonic = "Rustc" , 973progress_message = "Compiling Rust {} {}{} ({} files)" . format ( 974crate_info . type , 975ctx . label . name , 976formatted_version , 977len ( crate_info . srcs . to_list ()), 978), 979) 980else : 981# Run without process_wrapper 982if build_env_files or build_flags_files or stamp : 983fail ( "build_env_files, build_flags_files, stamp are not supported when building without process_wrapper" ) 984ctx . actions . run ( 985executable = toolchain . rustc , 986inputs = compile_inputs , 987outputs = action_outputs , 988env = env , 989arguments = [ args . rustc_flags ], 990mnemonic = "Rustc" , 991progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)" . format ( 992crate_info . type , 993ctx . label . name , 994formatted_version , 995len ( crate_info . srcs . to_list ()), 996), 997) 998 999coverage_runfiles = [] 1000if toolchain . llvm_cov and ctx . configuration . coverage_enabled and crate_info . is_test : 1001coverage_runfiles = [ toolchain . llvm_cov , toolchain . llvm_profdata ] 1002 1003runfiles = ctx . runfiles ( 1004files = getattr ( ctx . files , "data" , []) + coverage_runfiles , 1005collect_data = True , 1006) 1007 1008# TODO: Remove after some resolution to 1009# https://github.com/bazelbuild/rules_rust/issues/771 1010out_binary = getattr ( attr , "out_binary" , False ) 1011 1012providers = [ 1013DefaultInfo ( 1014# nb. This field is required for cc_library to depend on our output. 1015files = depset ( outputs ), 1016runfiles = runfiles , 1017executable = crate_info . output if crate_info . type == "bin" or crate_info . is_test or out_binary else None , 1018), 1019coverage_common . instrumented_files_info ( 1020ctx , 1021dependency_attributes = [ "deps" , "crate" ], 1022extensions = [ "rs" ], 1023source_attributes = [ "srcs" ], 1024), 1025] 1026 1027if crate_info . type in [ "staticlib" , "cdylib" ]: 1028# These rules are not supposed to be depended on by other rust targets, and 1029# as such they shouldn't provide a CrateInfo. However, one may still want to 1030# write a rust_test for them, so we provide the CrateInfo wrapped in a provider 1031# that rust_test understands. 1032providers . extend ([ rust_common . test_crate_info ( crate = crate_info ), dep_info ]) 1033else : 1034providers . extend ([ crate_info , dep_info ]) 1035 1036if toolchain . target_arch != "wasm32" : 1037providers += establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ) 1038if pdb_file : 1039providers . append ( OutputGroupInfo ( pdb_file = depset ([ pdb_file ]))) 1040if dsym_folder : 1041providers . append ( OutputGroupInfo ( dsym_folder = depset ([ dsym_folder ]))) 1042 1043return providers 1044 1045def _is_dylib ( dep ): 1046return not bool ( dep . static_library or dep . pic_static_library ) 1047 1048def _collect_nonstatic_linker_inputs ( cc_info ): 1049shared_linker_inputs = [] 1050for linker_input in cc_info . linking_context . linker_inputs . to_list (): 1051dylibs = [ 1052lib 1053for lib in linker_input . libraries 1054if _is_dylib ( lib ) 1055] 1056if dylibs : 1057shared_linker_inputs . append ( cc_common . create_linker_input ( 1058owner = linker_input . owner , 1059libraries = depset ( dylibs ), 1060)) 1061return shared_linker_inputs 1062 1063def establish_cc_info ( ctx , attr , crate_info , toolchain , cc_toolchain , feature_configuration , interface_library ): 1064"""If the produced crate is suitable yield a CcInfo to allow for interop with cc rules 1065 1066Args: 1067ctx (ctx): The rule's context object 1068attr (struct): Attributes to use in gathering CcInfo 1069crate_info (CrateInfo): The CrateInfo provider of the target crate 1070toolchain (rust_toolchain): The current `rust_toolchain` 1071cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo` 1072feature_configuration (FeatureConfiguration): Feature configuration to be queried. 1073interface_library (File): Optional interface library for cdylib crates on Windows. 1074 1075Returns: 1076list: A list containing the CcInfo provider 1077""" 1078 1079# A test will not need to produce CcInfo as nothing can depend on test targets 1080if crate_info . is_test : 1081return [] 1082 1083# Only generate CcInfo for particular crate types 1084if crate_info . type not in ( "staticlib" , "cdylib" , "rlib" , "lib" ): 1085return [] 1086 1087# TODO: Remove after some resolution to 1088# https://github.com/bazelbuild/rules_rust/issues/771 1089if getattr ( attr , "out_binary" , False ): 1090return [] 1091 1092if crate_info . type == "staticlib" : 1093library_to_link = cc_common . create_library_to_link ( 1094actions = ctx . actions , 1095feature_configuration = feature_configuration , 1096cc_toolchain = cc_toolchain , 1097static_library = crate_info . output , 1098# TODO(hlopko): handle PIC/NOPIC correctly 1099pic_static_library = crate_info . output , 1100) 1101elif crate_info . type in ( "rlib" , "lib" ): 1102# bazel hard-codes a check for endswith((".a", ".pic.a", 1103# ".lib")) in create_library_to_link, so we work around that 1104# by creating a symlink to the .rlib with a .a extension. 1105dot_a = make_static_lib_symlink ( ctx . actions , crate_info . output ) 1106 1107# TODO(hlopko): handle PIC/NOPIC correctly 1108library_to_link = cc_common . create_library_to_link ( 1109actions = ctx . actions , 1110feature_configuration = feature_configuration , 1111cc_toolchain = cc_toolchain , 1112static_library = dot_a , 1113# TODO(hlopko): handle PIC/NOPIC correctly 1114pic_static_library = dot_a , 1115) 1116elif crate_info . type == "cdylib" : 1117library_to_link = cc_common . create_library_to_link ( 1118actions = ctx . actions , 1119feature_configuration = feature_configuration , 1120cc_toolchain = cc_toolchain , 1121dynamic_library = crate_info . output , 1122interface_library = interface_library , 1123) 1124else : 1125fail ( "Unexpected case" ) 1126 1127link_input = cc_common . create_linker_input ( 1128owner = ctx . label , 1129libraries = depset ([ library_to_link ]), 1130) 1131 1132linking_context = cc_common . create_linking_context ( 1133# TODO - What to do for no_std? 1134linker_inputs = depset ([ link_input ]), 1135) 1136 1137cc_infos = [ 1138CcInfo ( linking_context = linking_context ), 1139toolchain . stdlib_linkflags , 1140] 1141 1142for dep in getattr ( attr , "deps" , []): 1143if CcInfo in dep : 1144# A Rust staticlib or shared library doesn't need to propagate linker inputs 1145# of its dependencies, except for shared libraries. 1146if crate_info . type in [ "cdylib" , "staticlib" ]: 1147shared_linker_inputs = _collect_nonstatic_linker_inputs ( dep [ CcInfo ]) 1148if shared_linker_inputs : 1149linking_context = cc_common . create_linking_context ( 1150linker_inputs = depset ( shared_linker_inputs ), 1151) 1152cc_infos . append ( CcInfo ( linking_context = linking_context )) 1153else : 1154cc_infos . append ( dep [ CcInfo ]) 1155 1156if crate_info . type in ( "rlib" , "lib" ) and toolchain . libstd_and_allocator_ccinfo : 1157# TODO: if we already have an rlib in our deps, we could skip this 1158cc_infos . append ( toolchain . libstd_and_allocator_ccinfo ) 1159 1160return [ cc_common . merge_cc_infos ( cc_infos = cc_infos )] 1161 1162def add_edition_flags ( args , crate ): 1163"""Adds the Rust edition flag to an arguments object reference 1164 1165Args: 1166args (Args): A reference to an Args object 1167crate (CrateInfo): A CrateInfo provider 1168""" 1169if crate . edition != "2015" : 1170args . add ( "--edition={}" . format ( crate . edition )) 1171 1172def _create_extra_input_args ( build_info , dep_info ): 1173"""Gather additional input arguments from transitive dependencies 1174 1175Args: 1176build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs. 1177dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs. 1178 1179Returns: 1180tuple: A tuple of the following items: 1181- (depset[File]): A list of all build info `OUT_DIR` File objects 1182- (str): The `OUT_DIR` of the current build info 1183- (File): An optional generated environment file from a `cargo_build_script` target 1184- (depset[File]): All direct and transitive build flag files from the current build info. 1185""" 1186input_files = [] 1187 1188# Arguments to the commandline line wrapper that are going to be used 1189# to create the final command line 1190out_dir = None 1191build_env_file = None 1192build_flags_files = [] 1193 1194if build_info : 1195out_dir = build_info . out_dir . path 1196build_env_file = build_info . rustc_env 1197build_flags_files . append ( build_info . flags ) 1198build_flags_files . append ( build_info . link_flags ) 1199input_files . append ( build_info . out_dir ) 1200input_files . append ( build_info . link_flags ) 1201 1202return ( 1203depset ( input_files , transitive = [ dep_info . link_search_path_files ]), 1204out_dir , 1205build_env_file , 1206depset ( build_flags_files , transitive = [ dep_info . link_search_path_files ]), 1207) 1208 1209def _compute_rpaths ( toolchain , output_dir , dep_info , use_pic ): 1210"""Determine the artifact's rpaths relative to the bazel root for runtime linking of shared libraries. 1211 1212Args: 1213toolchain (rust_toolchain): The current `rust_toolchain` 1214output_dir (str): The output directory of the current target 1215dep_info (DepInfo): The current target's dependency info 1216use_pic: If set, prefers pic_static_library over static_library. 1217 1218Returns: 1219depset: A set of relative paths from the output directory to each dependency 1220""" 1221 1222# Windows has no rpath equivalent, so always return an empty depset. 1223if toolchain . os == "windows" : 1224return depset ([]) 1225 1226dylibs = [ 1227get_preferred_artifact ( lib , use_pic ) 1228for linker_input in dep_info . transitive_noncrates . to_list () 1229for lib in linker_input . libraries 1230if _is_dylib ( lib ) 1231] 1232if not dylibs : 1233return depset ([]) 1234 1235# For darwin, dylibs compiled by Bazel will fail to be resolved at runtime 1236# without a version of Bazel that includes 1237# https://github.com/bazelbuild/bazel/pull/13427. This is known to not be 1238# included in Bazel 4.1 and below. 1239if toolchain . os != "linux" and toolchain . os != "darwin" : 1240fail ( "Runtime linking is not supported on {}, but found {}" . format ( 1241toolchain . os , 1242dep_info . transitive_noncrates , 1243)) 1244 1245# Multiple dylibs can be present in the same directory, so deduplicate them. 1246return depset ([ 1247relativize ( lib_dir , output_dir ) 1248for lib_dir in _get_dir_names ( dylibs ) 1249]) 1250 1251def _get_dir_names ( files ): 1252"""Returns a list of directory names from the given list of File objects 1253 1254Args: 1255files (list): A list of File objects 1256 1257Returns: 1258list: A list of directory names for all files 1259""" 1260dirs = {} 1261for f in files : 1262dirs [ f . dirname ] = None 1263return dirs . keys () 1264 1265def add_crate_link_flags ( args , dep_info , force_all_deps_direct = False ): 1266"""Adds link flags to an Args object reference 1267 1268Args: 1269args (Args): An arguments object reference 1270dep_info (DepInfo): The current target's dependency info 1271force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern 1272to the commandline as opposed to -L. 1273""" 1274 1275if force_all_deps_direct : 1276args . add_all ( 1277depset ( 1278transitive = [ 1279dep_info . direct_crates , 1280dep_info . transitive_crates , 1281], 1282), 1283uniquify = True , 1284map_each = _crate_to_link_flag , 1285) 1286else : 1287# nb. Direct crates are linked via --extern regardless of their crate_type 1288args . add_all ( dep_info . direct_crates , map_each = _crate_to_link_flag ) 1289args . add_all ( 1290dep_info . transitive_crates , 1291map_each = _get_crate_dirname , 1292uniquify = True , 1293format_each = "-Ldependency=%s" , 1294) 1295 1296def _crate_to_link_flag ( crate ): 1297"""A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object 1298 1299Args: 1300crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider 1301 1302Returns: 1303list: Link flags for the given provider 1304""" 1305 1306# This is AliasableDepInfo, we should use the alias as a crate name 1307if hasattr ( crate , "dep" ): 1308name = crate . name 1309crate_info = crate . dep 1310else : 1311name = crate . name 1312crate_info = crate 1313return [ "--extern={}={}" . format ( name , crate_info . output . path )] 1314 1315def _get_crate_dirname ( crate ): 1316"""A helper macro used by `add_crate_link_flags` for getting the directory name of the current crate's output path 1317 1318Args: 1319crate (CrateInfo): A CrateInfo provider from the current rule 1320 1321Returns: 1322str: The directory name of the the output File that will be produced. 1323""" 1324return crate . output . dirname 1325 1326def _portable_link_flags ( lib , use_pic , ambiguous_libs ): 1327artifact = get_preferred_artifact ( lib , use_pic ) 1328if ambiguous_libs and artifact . path in ambiguous_libs : 1329artifact = ambiguous_libs [ artifact . path ] 1330if lib . static_library or lib . pic_static_library : 1331# To ensure appropriate linker library argument order, in the presence 1332# of both native libraries that depend on rlibs and rlibs that depend 1333# on native libraries, we use an approach where we "sandwich" the 1334# rust libraries between two similar sections of all of native 1335# libraries: 1336# n1 n2 ... r1 r2 ... n1 n2 ... 1337# A B C 1338# This way any dependency from a native library to a rust library 1339# is resolved from A to B, and any dependency from a rust library to 1340# a native one is resolved from B to C. 1341# The question of resolving dependencies from a native library from A 1342# to any rust library is addressed in a different place, where we 1343# create symlinks to the rlibs, pretending they are native libraries, 1344# and adding references to these symlinks in the native section A. 1345# We rely in the behavior of -Clink-arg to put the linker args 1346# at the end of the linker invocation constructed by rustc. 1347return [ 1348"-lstatic=%s" % get_lib_name ( artifact ), 1349"-Clink-arg=-l%s" % get_lib_name ( artifact ), 1350] 1351elif _is_dylib ( lib ): 1352return [ 1353"-ldylib=%s" % get_lib_name ( artifact ), 1354] 1355 1356return [] 1357 1358def _make_link_flags_windows ( linker_input_and_use_pic_and_ambiguous_libs ): 1359linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1360ret = [] 1361for lib in linker_input . libraries : 1362if lib . alwayslink : 1363ret . extend ([ "-C" , "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact ( lib , use_pic ). path ]) 1364else : 1365ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1366return ret 1367 1368def _make_link_flags_darwin ( 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,-force_load,%s" % get_preferred_artifact ( lib , use_pic ). path ), 1376]) 1377else : 1378ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1379return ret 1380 1381def _make_link_flags_default ( linker_input_and_use_pic_and_ambiguous_libs ): 1382linker_input , use_pic , ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs 1383ret = [] 1384for lib in linker_input . libraries : 1385if lib . alwayslink : 1386ret . extend ([ 1387"-C" , 1388"link-arg=-Wl,--whole-archive" , 1389"-C" , 1390( "link-arg=%s" % get_preferred_artifact ( lib , use_pic ). path ), 1391"-C" , 1392"link-arg=-Wl,--no-whole-archive" , 1393]) 1394else : 1395ret . extend ( _portable_link_flags ( lib , use_pic , ambiguous_libs )) 1396return ret 1397 1398def _libraries_dirnames ( linker_input_and_use_pic_and_ambiguous_libs ): 1399link_input , use_pic , _ = linker_input_and_use_pic_and_ambiguous_libs 1400 1401# De-duplicate names. 1402return depset ([ get_preferred_artifact ( lib , use_pic ). dirname for lib in link_input . libraries ]). to_list () 1403 1404def _add_native_link_flags ( args , dep_info , linkstamp_outs , ambiguous_libs , crate_type , toolchain , cc_toolchain , feature_configuration ): 1405"""Adds linker flags for all dependencies of the current target. 1406 1407Args: 1408args (Args): The Args struct for a ctx.action 1409dep_info (DepInfo): Dependency Info provider 1410linkstamp_outs (list): Linkstamp outputs of native dependencies 1411ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs` 1412crate_type: Crate type of the current target 1413toolchain (rust_toolchain): The current `rust_toolchain` 1414cc_toolchain (CcToolchainInfo): The current `cc_toolchain` 1415feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain 1416""" 1417if crate_type in [ "lib" , "rlib" ]: 1418return 1419 1420use_pic = _should_use_pic ( cc_toolchain , feature_configuration , crate_type ) 1421 1422if toolchain . os == "windows" : 1423make_link_flags = _make_link_flags_windows 1424elif toolchain . os . startswith ( "mac" ) or toolchain . os . startswith ( "darwin" ): 1425make_link_flags = _make_link_flags_darwin 1426else : 1427make_link_flags = _make_link_flags_default 1428 1429# TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0 1430args_and_pic_and_ambiguous_libs = [( arg , use_pic , ambiguous_libs ) for arg in dep_info . transitive_noncrates . to_list ()] 1431args . add_all ( args_and_pic_and_ambiguous_libs , map_each = _libraries_dirnames , uniquify = True , format_each = "-Lnative=%s" ) 1432if ambiguous_libs : 1433# If there are ambiguous libs, the disambiguation symlinks to them are 1434# all created in the same directory. Add it to the library search path. 1435ambiguous_libs_dirname = ambiguous_libs . values ()[ 0 ]. dirname 1436args . add ( "-Lnative={}" . format ( ambiguous_libs_dirname )) 1437 1438args . add_all ( args_and_pic_and_ambiguous_libs , map_each = make_link_flags ) 1439 1440for linkstamp_out in linkstamp_outs : 1441args . add_all ([ "-C" , "link-arg=%s" % linkstamp_out . path ]) 1442 1443if crate_type in [ "dylib" , "cdylib" ]: 1444# For shared libraries we want to link C++ runtime library dynamically 1445# (for example libstdc++.so or libc++.so). 1446args . add_all ( 1447cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1448map_each = _get_dirname , 1449format_each = "-Lnative=%s" , 1450) 1451args . add_all ( 1452cc_toolchain . dynamic_runtime_lib ( feature_configuration = feature_configuration ), 1453map_each = get_lib_name , 1454format_each = "-ldylib=%s" , 1455) 1456else : 1457# For all other crate types we want to link C++ runtime library statically 1458# (for example libstdc++.a or libc++.a). 1459args . add_all ( 1460cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1461map_each = _get_dirname , 1462format_each = "-Lnative=%s" , 1463) 1464args . add_all ( 1465cc_toolchain . static_runtime_lib ( feature_configuration = feature_configuration ), 1466map_each = get_lib_name , 1467format_each = "-lstatic=%s" , 1468) 1469 1470def _get_dirname ( file ): 1471"""A helper function for `_add_native_link_flags`. 1472 1473Args: 1474file (File): The target file 1475 1476Returns: 1477str: Directory name of `file` 1478""" 1479return file . dirname 1480 1481def _error_format_impl ( ctx ): 1482"""Implementation of the `error_format` rule 1483 1484Args: 1485ctx (ctx): The rule's context object 1486 1487Returns: 1488list: A list containing the ErrorFormatInfo provider 1489""" 1490raw = ctx . build_setting_value 1491if raw not in _error_format_values : 1492fail ( "{} expected a value in `{}` but got `{}`" . format ( 1493ctx . label , 1494_error_format_values , 1495raw , 1496)) 1497return [ ErrorFormatInfo ( error_format = raw )] 1498 1499error_format = rule ( 1500doc = ( 1501"Change the [--error-format](https://doc.rust-lang.org/rustc/command-line-arguments.html#option-error-format) " + 1502"flag from the command line with `--@rules_rust//:error_format`. See rustc documentation for valid values." 1503), 1504implementation = _error_format_impl , 1505build_setting = config . string ( flag = True ), 1506) 1507 1508def _extra_rustc_flags_impl ( ctx ): 1509return ExtraRustcFlagsInfo ( extra_rustc_flags = ctx . build_setting_value ) 1510 1511extra_rustc_flags = rule ( 1512doc = ( 1513"Add additional rustc_flags from the command line with `--@rules_rust//:extra_rustc_flags`. " + 1514"This flag should only be used for flags that need to be applied across the entire build. For options that " + 1515"apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: " + 1516"These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); " + 1517"use `--@rules_rust//:extra_exec_rustc_flags` to apply flags to the exec configuration." 1518), 1519implementation = _extra_rustc_flags_impl , 1520build_setting = config . string_list ( flag = True ), 1521) 1522 1523def _extra_exec_rustc_flags_impl ( ctx ): 1524return ExtraExecRustcFlagsInfo ( extra_exec_rustc_flags = ctx . build_setting_value ) 1525 1526extra_exec_rustc_flags = rule ( 1527doc = ( 1528"Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flags`. " + 1529"This flag should only be used for flags that need to be applied across the entire build. " + 1530"These flags only apply to the exec configuration (proc-macros, cargo_build_script, etc)." 1531), 1532implementation = _extra_exec_rustc_flags_impl , 1533build_setting = config . string_list ( flag = True ), 1534)