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