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