fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
e3a77c4d
patching
1"""Rules for Cargo build scripts (`build.rs` files)""" 2 3load ( "@bazel_skylib//lib:paths.bzl" , "paths" ) 4load ( "@bazel_skylib//rules:common_settings.bzl" , "BuildSettingInfo" ) 5load ( "@bazel_tools//tools/cpp:toolchain_utils.bzl" , "find_cpp_toolchain" ) 6load ( "@rules_cc//cc:action_names.bzl" , "ACTION_NAMES" ) 7load ( "//rust:defs.bzl" , "rust_common" ) 8load ( "//rust:rust_common.bzl" , "BuildInfo" , "DepInfo" ) 9 10# buildifier: disable=bzl-visibility 11load ( 12"//rust/private:rustc.bzl" , 13"get_compilation_mode_opts" , 14"get_linker_and_args" , 15) 16 17# buildifier: disable=bzl-visibility 18load ( 19"//rust/private:utils.bzl" , 20"dedent" , 21"expand_dict_value_locations" , 22"find_cc_toolchain" , 23"find_toolchain" , 24_name_to_crate_name = "name_to_crate_name" , 25) 26 27# Reexport for cargo_build_script_wrapper.bzl 28name_to_crate_name = _name_to_crate_name 29 30def get_cc_compile_args_and_env ( cc_toolchain , feature_configuration ): 31"""Gather cc environment variables from the given `cc_toolchain` 32 33Args: 34cc_toolchain (cc_toolchain): The current rule's `cc_toolchain`. 35feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features. 36 37Returns: 38tuple: A tuple of the following items: 39- (sequence): A flattened C command line flags for given action. 40- (sequence): A flattened CXX command line flags for given action. 41- (dict): C environment variables to be set for given action. 42""" 43compile_variables = cc_common . create_compile_variables ( 44feature_configuration = feature_configuration , 45cc_toolchain = cc_toolchain , 46) 47cc_c_args = cc_common . get_memory_inefficient_command_line ( 48feature_configuration = feature_configuration , 49action_name = ACTION_NAMES . c_compile , 50variables = compile_variables , 51) 52cc_cxx_args = cc_common . get_memory_inefficient_command_line ( 53feature_configuration = feature_configuration , 54action_name = ACTION_NAMES . cpp_compile , 55variables = compile_variables , 56) 57cc_env = cc_common . get_environment_variables ( 58feature_configuration = feature_configuration , 59action_name = ACTION_NAMES . c_compile , 60variables = compile_variables , 61) 62return cc_c_args , cc_cxx_args , cc_env 63 64def _pwd_flags_sysroot ( args ): 65"""Prefix execroot-relative paths of known arguments with ${pwd}. 66 67Args: 68args (list): List of tool arguments. 69 70Returns: 71list: The modified argument list. 72""" 73res = [] 74for arg in args : 75s , opt , path = arg . partition ( "--sysroot=" ) 76if s == "" and not paths . is_absolute ( path ): 77res . append ( "{}${{pwd}}/{}" . format ( opt , path )) 78else : 79res . append ( arg ) 80return res 81 82def _pwd_flags_isystem ( args ): 83"""Prefix execroot-relative paths of known arguments with ${pwd}. 84 85Args: 86args (list): List of tool arguments. 87 88Returns: 89list: The modified argument list. 90""" 91res = [] 92fix_next_arg = False 93for arg in args : 94if fix_next_arg and not paths . is_absolute ( arg ): 95res . append ( "${{pwd}}/{}" . format ( arg )) 96else : 97res . append ( arg ) 98 99fix_next_arg = arg == "-isystem" 100 101return res 102 103def _pwd_flags ( args ): 104return _pwd_flags_isystem ( _pwd_flags_sysroot ( args )) 105 106def _feature_enabled ( ctx , feature_name , default = False ): 107"""Check if a feature is enabled. 108 109If the feature is explicitly enabled or disabled, return accordingly. 110 111In the case where the feature is not explicitly enabled or disabled, return the default value. 112 113Args: 114ctx: The context object. 115feature_name: The name of the feature. 116default: The default value to return if the feature is not explicitly enabled or disabled. 117 118Returns: 119Boolean defining whether the feature is enabled. 120""" 121if feature_name in ctx . disabled_features : 122return False 123 124if feature_name in ctx . features : 125return True 126 127return default 128 129def _cargo_build_script_impl ( ctx ): 130"""The implementation for the `cargo_build_script` rule. 131 132Args: 133ctx (ctx): The rules context object 134 135Returns: 136list: A list containing a BuildInfo provider 137""" 138script = ctx . executable . script 139toolchain = find_toolchain ( ctx ) 140out_dir = ctx . actions . declare_directory ( ctx . label . name + ".out_dir" ) 141env_out = ctx . actions . declare_file ( ctx . label . name + ".env" ) 142dep_env_out = ctx . actions . declare_file ( ctx . label . name + ".depenv" ) 143flags_out = ctx . actions . declare_file ( ctx . label . name + ".flags" ) 144link_flags = ctx . actions . declare_file ( ctx . label . name + ".linkflags" ) 145link_search_paths = ctx . actions . declare_file ( ctx . label . name + ".linksearchpaths" ) #rustc - link - search , propagated from transitive dependencies 146manifest_dir = "%s.runfiles/%s/%s" % ( script . path , ctx . label . workspace_name or ctx . workspace_name , ctx . label . package ) 147compilation_mode_opt_level = get_compilation_mode_opts ( ctx , toolchain ). opt_level 148 149streams = struct ( 150stdout = ctx . actions . declare_file ( ctx . label . name + ".stdout.log" ), 151stderr = ctx . actions . declare_file ( ctx . label . name + ".stderr.log" ), 152) 153 154pkg_name = ctx . attr . pkg_name 155if pkg_name == "" : 156pkg_name = name_to_pkg_name ( ctx . label . name ) 157 158toolchain_tools = [ toolchain . all_files ] 159 160cc_toolchain = find_cpp_toolchain ( ctx ) 161 162# Start with the default shell env, which contains any --action_env 163# settings passed in on the command line. 164env = dict ( ctx . configuration . default_shell_env ) 165 166env . update ({ 167"CARGO_CRATE_NAME" : name_to_crate_name ( pkg_name ), 168"CARGO_MANIFEST_DIR" : manifest_dir , 169"CARGO_PKG_NAME" : pkg_name , 170"HOST" : toolchain . exec_triple . str , 171"NUM_JOBS" : "1" , 172"OPT_LEVEL" : compilation_mode_opt_level , 173"RUSTC" : toolchain . rustc . path , 174"TARGET" : toolchain . target_flag_value , 175# OUT_DIR is set by the runner itself, rather than on the action. 176}) 177 178# This isn't exactly right, but Bazel doesn't have exact views of "debug" and "release", so... 179env . update ({ 180"DEBUG" : { "dbg" : "true" , "fastbuild" : "true" , "opt" : "false" }. get ( ctx . var [ "COMPILATION_MODE" ], "true" ), 181"PROFILE" : { "dbg" : "debug" , "fastbuild" : "debug" , "opt" : "release" }. get ( ctx . var [ "COMPILATION_MODE" ], "unknown" ), 182}) 183 184if ctx . attr . version : 185version = ctx . attr . version . split ( "+" )[ 0 ]. split ( "." ) 186patch = version [ 2 ]. split ( "-" ) if len ( version ) > 2 else [ "" ] 187env [ "CARGO_PKG_VERSION_MAJOR" ] = version [ 0 ] 188env [ "CARGO_PKG_VERSION_MINOR" ] = version [ 1 ] if len ( version ) > 1 else "" 189env [ "CARGO_PKG_VERSION_PATCH" ] = patch [ 0 ] 190env [ "CARGO_PKG_VERSION_PRE" ] = patch [ 1 ] if len ( patch ) > 1 else "" 191env [ "CARGO_PKG_VERSION" ] = ctx . attr . version 192 193# Pull in env vars which may be required for the cc_toolchain to work (e.g. on OSX, the SDK version). 194# We hope that the linker env is sufficient for the whole cc_toolchain. 195cc_toolchain , feature_configuration = find_cc_toolchain ( ctx ) 196linker , link_args , linker_env = get_linker_and_args ( ctx , ctx . attr , "bin" , cc_toolchain , feature_configuration , None ) 197env . update ( ** linker_env ) 198env [ "LD" ] = linker 199env [ "LDFLAGS" ] = " " . join ( _pwd_flags ( link_args )) 200 201# MSVC requires INCLUDE to be set 202cc_c_args , cc_cxx_args , cc_env = get_cc_compile_args_and_env ( cc_toolchain , feature_configuration ) 203include = cc_env . get ( "INCLUDE" ) 204if include : 205env [ "INCLUDE" ] = include 206 207if cc_toolchain : 208toolchain_tools . append ( cc_toolchain . all_files ) 209 210env [ "CC" ] = cc_common . get_tool_for_action ( 211feature_configuration = feature_configuration , 212action_name = ACTION_NAMES . c_compile , 213) 214env [ "CXX" ] = cc_common . get_tool_for_action ( 215feature_configuration = feature_configuration , 216action_name = ACTION_NAMES . cpp_compile , 217) 218env [ "AR" ] = cc_common . get_tool_for_action ( 219feature_configuration = feature_configuration , 220action_name = ACTION_NAMES . cpp_link_static_library , 221) 222 223# Populate CFLAGS and CXXFLAGS that cc-rs relies on when building from source, in particular 224# to determine the deployment target when building for apple platforms (`macosx-version-min` 225# for example, itself derived from the `macos_minimum_os` Bazel argument). 226env [ "CFLAGS" ] = " " . join ( _pwd_flags ( cc_c_args )) 227env [ "CXXFLAGS" ] = " " . join ( _pwd_flags ( cc_cxx_args )) 228 229# Inform build scripts of rustc flags 230# https://github.com/rust-lang/cargo/issues/9600 231env [ "CARGO_ENCODED_RUSTFLAGS" ] = "\\x1f ". join ([ 232# Allow build scripts to locate the generated sysroot 233"--sysroot=${{pwd}}/{}" . format ( toolchain . sysroot ), 234] + ctx . attr . rustc_flags ) 235 236for f in ctx . attr . crate_features : 237env [ "CARGO_FEATURE_" + f . upper (). replace ( "-" , "_" )] = "1" 238 239links = ctx . attr . links or "" 240if links : 241env [ "CARGO_MANIFEST_LINKS" ] = links 242 243# Add environment variables from the Rust toolchain. 244env . update ( toolchain . env ) 245 246# Gather data from the `toolchains` attribute. 247for target in ctx . attr . toolchains : 248if DefaultInfo in target : 249toolchain_tools . extend ([ 250target [ DefaultInfo ]. files , 251target [ DefaultInfo ]. default_runfiles . files , 252]) 253if platform_common . ToolchainInfo in target : 254all_files = getattr ( target [ platform_common . ToolchainInfo ], "all_files" , depset ([])) 255if type ( all_files ) == "list" : 256all_files = depset ( all_files ) 257toolchain_tools . append ( all_files ) 258if platform_common . TemplateVariableInfo in target : 259variables = getattr ( target [ platform_common . TemplateVariableInfo ], "variables" , depset ([])) 260env . update ( variables ) 261 262_merge_env_dict ( env , expand_dict_value_locations ( 263ctx , 264ctx . attr . build_script_env , 265getattr ( ctx . attr , "data" , []) + 266getattr ( ctx . attr , "compile_data" , []) + 267getattr ( ctx . attr , "tools" , []), 268)) 269 270tools = depset ( 271direct = [ 272script , 273ctx . executable . _cargo_build_script_runner , 274] + ctx . files . data + ctx . files . tools + ([ toolchain . target_json ] if toolchain . target_json else []), 275transitive = toolchain_tools , 276) 277 278# dep_env_file contains additional environment variables coming from 279# direct dependency sys-crates' build scripts. These need to be made 280# available to the current crate build script. 281# See https://doc.rust-lang.org/cargo/reference/build-scripts.html#-sys-packages 282# for details. 283args = ctx . actions . args () 284args . add ( script ) 285args . add ( links ) 286args . add ( out_dir . path ) 287args . add ( env_out ) 288args . add ( flags_out ) 289args . add ( link_flags ) 290args . add ( link_search_paths ) 291args . add ( dep_env_out ) 292args . add ( streams . stdout ) 293args . add ( streams . stderr ) 294args . add ( ctx . attr . rundir ) 295 296build_script_inputs = [] 297for dep in ctx . attr . link_deps : 298if rust_common . dep_info in dep and dep [ rust_common . dep_info ]. dep_env : 299dep_env_file = dep [ rust_common . dep_info ]. dep_env 300args . add ( dep_env_file . path ) 301build_script_inputs . append ( dep_env_file ) 302for dep_build_info in dep [ rust_common . dep_info ]. transitive_build_infos . to_list (): 303build_script_inputs . append ( dep_build_info . out_dir ) 304 305for dep in ctx . attr . deps : 306for dep_build_info in dep [ rust_common . dep_info ]. transitive_build_infos . to_list (): 307build_script_inputs . append ( dep_build_info . out_dir ) 308 309experimental_symlink_execroot = ctx . attr . _experimental_symlink_execroot [ BuildSettingInfo ]. value or \ 310_feature_enabled ( ctx , "symlink-exec-root" ) 311 312if experimental_symlink_execroot : 313env [ "RULES_RUST_SYMLINK_EXEC_ROOT" ] = "1" 314 315ctx . actions . run ( 316executable = ctx . executable . _cargo_build_script_runner , 317arguments = [ args ], 318outputs = [ out_dir , env_out , flags_out , link_flags , link_search_paths , dep_env_out , streams . stdout , streams . stderr ], 319tools = tools , 320inputs = build_script_inputs , 321mnemonic = "CargoBuildScriptRun" , 322progress_message = "Running Cargo build script {}" . format ( pkg_name ), 323env = env , 324toolchain = None , 325# Set use_default_shell_env so that $PATH is set, as tools like cmake may want to probe $PATH for helper tools. 326use_default_shell_env = True , 327) 328 329return [ 330# Although this isn't used anywhere, without this, `bazel build`'ing 331# the cargo_build_script label won't actually run the build script 332# since bazel is lazy. 333DefaultInfo ( files = depset ([ out_dir ])), 334BuildInfo ( 335out_dir = out_dir , 336rustc_env = env_out , 337dep_env = dep_env_out , 338flags = flags_out , 339linker_flags = link_flags , 340link_search_paths = link_search_paths , 341compile_data = depset ([]), 342), 343OutputGroupInfo ( 344streams = depset ([ streams . stdout , streams . stderr ]), 345out_dir = depset ([ out_dir ]), 346), 347] 348 349cargo_build_script = rule ( 350doc = ( 351"A rule for running a crate's `build.rs` files to generate build information " + 352"which is then used to determine how to compile said crate." 353), 354implementation = _cargo_build_script_impl , 355attrs = { 356"build_script_env" : attr . string_dict ( 357doc = "Environment variables for build scripts." , 358), 359"crate_features" : attr . string_list ( 360doc = "The list of rust features that the build script should consider activated." , 361), 362"data" : attr . label_list ( 363doc = "Data required by the build script." , 364allow_files = True , 365), 366"deps" : attr . label_list ( 367doc = "The Rust build-dependencies of the crate" , 368providers = [ rust_common . dep_info ], 369cfg = "exec" , 370), 371"link_deps" : attr . label_list ( 372doc = dedent ( """\ 373The subset of the Rust (normal) dependencies of the crate that 374have the links attribute and therefore provide environment 375variables to this build script. 376""" ), 377providers = [ rust_common . dep_info ], 378), 379"links" : attr . string ( 380doc = "The name of the native library this crate links against." , 381), 382"pkg_name" : attr . string ( 383doc = "The name of package being compiled, if not derived from `name`." , 384), 385"rundir" : attr . string ( 386default = "" , 387doc = dedent ( """\ 388A directory to cd to before the cargo_build_script is run. This should be a path relative to the exec root. 389 390The default behaviour (and the behaviour if rundir is set to the empty string) is to change to the relative path corresponding to the cargo manifest directory, which replicates the normal behaviour of cargo so it is easy to write compatible build scripts. 391 392If set to `.`, the cargo build script will run in the exec root. 393""" ), 394), 395"rustc_flags" : attr . string_list ( 396doc = dedent ( """\ 397List of compiler flags passed to `rustc`. 398 399These strings are subject to Make variable expansion for predefined 400source/output path variables like `$location`, `$execpath`, and 401`$rootpath`. This expansion is useful if you wish to pass a generated 402file of arguments to rustc: `@$(location //package:target)`. 403""" ), 404), 405# The source of truth will be the `cargo_build_script` macro until stardoc 406# implements documentation inheritence. See https://github.com/bazelbuild/stardoc/issues/27 407"script" : attr . label ( 408doc = "The binary script to run, generally a `rust_binary` target." , 409executable = True , 410allow_files = True , 411mandatory = True , 412cfg = "exec" , 413), 414"tools" : attr . label_list ( 415doc = "Tools required by the build script." , 416allow_files = True , 417cfg = "exec" , 418), 419"version" : attr . string ( 420doc = "The semantic version (semver) of the crate" , 421), 422"_cargo_build_script_runner" : attr . label ( 423executable = True , 424allow_files = True , 425default = Label ( "//cargo/cargo_build_script_runner:cargo_build_script_runner" ), 426cfg = "exec" , 427), 428"_cc_toolchain" : attr . label ( 429default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 430), 431"_experimental_symlink_execroot" : attr . label ( 432default = Label ( "//cargo/settings:experimental_symlink_execroot" ), 433), 434}, 435fragments = [ "cpp" ], 436toolchains = [ 437str ( Label ( "//rust:toolchain_type" )), 438"@bazel_tools//tools/cpp:toolchain_type" , 439], 440) 441 442def _merge_env_dict ( prefix_dict , suffix_dict ): 443"""Merges suffix_dict into prefix_dict, appending rather than replacing certain env vars.""" 444for key in [ "CFLAGS" , "CXXFLAGS" , "LDFLAGS" ]: 445if key in prefix_dict and key in suffix_dict and prefix_dict [ key ]: 446prefix_dict [ key ] += " " + suffix_dict . pop ( key ) 447prefix_dict . update ( suffix_dict ) 448 449def name_to_pkg_name ( name ): 450"""Sanitize the name of cargo_build_script targets. 451 452Args: 453name (str): The name value pass to the `cargo_build_script` wrapper. 454 455Returns: 456str: A cleaned up name for a build script target. 457""" 458if name . endswith ( "_bs" ): 459return name [: - len ( "_bs" )] 460return name 461 462def _cargo_dep_env_implementation ( ctx ): 463empty_file = ctx . actions . declare_file ( ctx . label . name + ".empty_file" ) 464empty_dir = ctx . actions . declare_directory ( ctx . label . name + ".empty_dir" ) 465ctx . actions . write ( 466output = empty_file , 467content = "" , 468) 469ctx . actions . run ( 470outputs = [ empty_dir ], 471executable = "true" , 472) 473 474build_infos = [] 475out_dir = ctx . file . out_dir 476if out_dir : 477if not out_dir . is_directory : 478fail ( "out_dir must be a directory artifact" ) 479 480# BuildInfos in this list are collected up for all transitive cargo_build_script 481# dependencies. This is important for any flags set in `dep_env` which reference this 482# `out_dir`. 483# 484# TLDR: This BuildInfo propagates up build script dependencies. 485build_infos . append ( BuildInfo ( 486dep_env = empty_file , 487flags = empty_file , 488linker_flags = empty_file , 489link_search_paths = empty_file , 490out_dir = out_dir , 491rustc_env = empty_file , 492compile_data = depset ([]), 493)) 494return [ 495DefaultInfo ( files = depset ( ctx . files . src )), 496# Parts of this BuildInfo is used when building all transitive dependencies 497# (cargo_build_script and otherwise), alongside the DepInfo. This is how other rules 498# identify this one as a valid dependency, but we don't otherwise have a use for it. 499# 500# TLDR: This BuildInfo propagates up normal (non build script) depenencies. 501# 502# In the future, we could consider setting rustc_env here, and also propagating dep_dir 503# so files in it can be referenced there. 504BuildInfo ( 505dep_env = empty_file , 506flags = empty_file , 507linker_flags = empty_file , 508link_search_paths = empty_file , 509out_dir = None , 510rustc_env = empty_file , 511compile_data = depset ([]), 512), 513# Information here is used directly by dependencies, and it is an error to have more than 514# one dependency which sets this. This is the main way to specify information from build 515# scripts, which is what we're looking to do. 516DepInfo ( 517dep_env = ctx . file . src , 518direct_crates = depset (), 519link_search_path_files = depset (), 520transitive_build_infos = depset ( direct = build_infos ), 521transitive_crate_outputs = depset (), 522transitive_crates = depset (), 523transitive_noncrates = depset (), 524), 525] 526 527cargo_dep_env = rule ( 528implementation = _cargo_dep_env_implementation , 529doc = ( 530"A rule for generating variables for dependent `cargo_build_script`s " + 531"without a build script. This is useful for using Bazel rules instead " + 532"of a build script, while also generating configuration information " + 533"for build scripts which depend on this crate." 534), 535attrs = { 536"out_dir" : attr . label ( 537doc = dedent ( """\ 538Folder containing additional inputs when building all direct dependencies. 539 540This has the same effect as a `cargo_build_script` which prints 541puts files into `$OUT_DIR`, but without requiring a build script. 542""" ), 543allow_single_file = True , 544mandatory = False , 545), 546"src" : attr . label ( 547doc = dedent ( """\ 548 File containing additional environment variables to set for build scripts of direct dependencies. 549 550 This has the same effect as a `cargo_build_script` which prints 551 `cargo:VAR=VALUE` lines, but without requiring a build script. 552 553 This files should contain a single variable per line, of format 554 `NAME=value`, and newlines may be included in a value by ending a 555 line with a trailing back-slash (`\\\\`). 556 """), 557 allow_single_file = True, 558 mandatory = True, 559 ), 560 }, 561)