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