fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
2bad96d9
cleanup
1# Copyright 2019 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"""Rust Bindgen rules""" 16 17load ( 18"@bazel_tools//tools/build_defs/cc:action_names.bzl" , 19"CPP_COMPILE_ACTION_NAME" , 20) 21load ( "@rules_cc//cc:defs.bzl" , "CcInfo" , "cc_library" ) 22load ( "@rules_rust//rust:defs.bzl" , "rust_library" ) 23load ( "@rules_rust//rust:rust_common.bzl" , "BuildInfo" ) 24 25# buildifier: disable=bzl-visibility 26load ( "@rules_rust//rust/private:rustc.bzl" , "get_linker_and_args" ) 27 28# buildifier: disable=bzl-visibility 29load ( "@rules_rust//rust/private:utils.bzl" , "find_cc_toolchain" , "get_lib_name_default" , "get_preferred_artifact" ) 30 31# TODO(hlopko): use the more robust logic from rustc.bzl also here, through a reasonable API. 32def _get_libs_for_static_executable ( dep ): 33"""find the libraries used for linking a static executable. 34 35Args: 36dep (Target): A cc_library target. 37 38Returns: 39depset: A depset[File] 40""" 41linker_inputs = dep [ CcInfo ]. linking_context . linker_inputs . to_list () 42return depset ([ get_preferred_artifact ( lib , use_pic = False ) for li in linker_inputs for lib in li . libraries ]) 43 44def rust_bindgen_library ( 45name , 46header , 47cc_lib , 48bindgen_flags = None , 49bindgen_features = None , 50clang_flags = None , 51wrap_static_fns = False , 52** kwargs ): 53"""Generates a rust source file for `header`, and builds a rust_library. 54 55Arguments are the same as `rust_bindgen`, and `kwargs` are passed directly to rust_library. 56 57Args: 58name (str): A unique name for this target. 59header (str): The label of the .h file to generate bindings for. 60cc_lib (str): The label of the cc_library that contains the .h file. This is used to find the transitive includes. 61bindgen_flags (list, optional): Flags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details. 62bindgen_features (list, optional): The `features` attribute for the `rust_bindgen` target. 63clang_flags (list, optional): Flags to pass directly to the clang executable. 64wrap_static_fns (bool): Whether to create a separate .c file for static fns. Requires nightly toolchain, and a header that actually needs this feature (otherwise bindgen won't generate the file and Bazel complains", 65**kwargs: Arguments to forward to the underlying `rust_library` rule. 66""" 67 68tags = kwargs . get ( "tags" ) or [] 69if "tags" in kwargs : 70kwargs . pop ( "tags" ) 71 72sub_tags = tags + ([] if "manual" in tags else [ "manual" ]) 73 74bindgen_kwargs = {} 75for shared in ( 76"target_compatible_with" , 77"exec_compatible_with" , 78): 79if shared in kwargs : 80bindgen_kwargs . update ({ shared : kwargs [ shared ]}) 81if "merge_cc_lib_objects_into_rlib" in kwargs : 82bindgen_kwargs . update ({ "merge_cc_lib_objects_into_rlib" : kwargs [ "merge_cc_lib_objects_into_rlib" ]}) 83kwargs . pop ( "merge_cc_lib_objects_into_rlib" ) 84 85rust_bindgen ( 86name = name + "__bindgen" , 87header = header , 88cc_lib = cc_lib , 89bindgen_flags = bindgen_flags or [], 90features = bindgen_features , 91clang_flags = clang_flags or [], 92tags = sub_tags , 93wrap_static_fns = wrap_static_fns , 94** bindgen_kwargs 95) 96 97tags = depset ( tags + [ "__bindgen" , "no-clippy" , "no-rustfmt" ]). to_list () 98 99deps = kwargs . get ( "deps" ) or [] 100if "deps" in kwargs : 101kwargs . pop ( "deps" ) 102 103if wrap_static_fns : 104native . filegroup ( 105name = name + "__bindgen_c_thunks" , 106srcs = [ ":" + name + "__bindgen" ], 107output_group = "bindgen_c_thunks" , 108) 109 110cc_library ( 111name = name + "__bindgen_c_thunks_library" , 112srcs = [ ":" + name + "__bindgen_c_thunks" ], 113deps = [ cc_lib ], 114) 115 116rust_library ( 117name = name , 118srcs = [ name + "__bindgen.rs" ], 119deps = deps + [ ":" + name + "__bindgen" ] + ([ ":" + name + "__bindgen_c_thunks_library" ] if wrap_static_fns else []), 120tags = tags , 121** kwargs 122) 123 124def _get_user_link_flags ( cc_lib ): 125linker_flags = [] 126 127for linker_input in cc_lib [ CcInfo ]. linking_context . linker_inputs . to_list (): 128linker_flags . extend ( linker_input . user_link_flags ) 129 130return linker_flags 131 132def _generate_cc_link_build_info ( ctx , cc_lib ): 133"""Produce the eqivilant cargo_build_script providers for use in linking the library. 134 135Args: 136ctx (ctx): The rule's context object 137cc_lib (Target): The `rust_bindgen.cc_lib` target. 138 139Returns: 140The `BuildInfo` provider. 141""" 142compile_data = [] 143 144rustc_flags = [] 145linker_search_paths = [] 146 147for linker_input in cc_lib [ CcInfo ]. linking_context . linker_inputs . to_list (): 148for lib in linker_input . libraries : 149if lib . static_library : 150rustc_flags . append ( "-lstatic={}" . format ( get_lib_name_default ( lib . static_library ))) 151linker_search_paths . append ( lib . static_library . dirname ) 152compile_data . append ( lib . static_library ) 153elif lib . pic_static_library : 154rustc_flags . append ( "-lstatic={}" . format ( get_lib_name_default ( lib . pic_static_library ))) 155linker_search_paths . append ( lib . pic_static_library . dirname ) 156compile_data . append ( lib . pic_static_library ) 157 158if not compile_data : 159fail ( "No static libraries found in {}" . format ( 160cc_lib . label , 161)) 162 163rustc_flags_file = ctx . actions . declare_file ( "{}.rustc_flags" . format ( ctx . label . name )) 164ctx . actions . write ( 165output = rustc_flags_file , 166content = "\n ". join ( rustc_flags ), 167) 168 169link_search_paths = ctx . actions . declare_file ( "{}.link_search_paths" . format ( ctx . label . name )) 170ctx . actions . write ( 171output = link_search_paths , 172content = "\n ". join ([ 173"-Lnative=${{pwd}}/{}" . format ( path ) 174for path in depset ( linker_search_paths ). to_list () 175]), 176) 177 178return BuildInfo ( 179compile_data = depset ( compile_data ), 180dep_env = None , 181flags = rustc_flags_file , 182# linker_flags is provided via CcInfo 183linker_flags = None , 184link_search_paths = link_search_paths , 185out_dir = None , 186rustc_env = None , 187) 188 189def _rust_bindgen_impl ( ctx ): 190# nb. We can't grab the cc_library`s direct headers, so a header must be provided. 191cc_lib = ctx . attr . cc_lib 192header = ctx . file . header 193cc_header_list = ctx . attr . cc_lib [ CcInfo ]. compilation_context . headers . to_list () 194if header not in cc_header_list : 195fail ( "Header {} is not in {}'s transitive headers." . format ( ctx . attr . header , cc_lib ), "header" ) 196 197toolchain = ctx . toolchains [ Label ( "//:toolchain_type" )] 198bindgen_bin = toolchain . bindgen 199clang_bin = toolchain . clang 200libclang = toolchain . libclang 201libstdcxx = toolchain . libstdcxx 202 203output = ctx . outputs . out 204 205cc_toolchain , feature_configuration = find_cc_toolchain ( ctx = ctx ) 206 207tools = depset (([ clang_bin ] if clang_bin else []), transitive = [ cc_toolchain . all_files ]) 208 209# libclang should only have 1 output file 210libclang_dir = _get_libs_for_static_executable ( libclang ). to_list ()[ 0 ]. dirname 211 212env = { 213"LIBCLANG_PATH" : libclang_dir , 214"RUST_BACKTRACE" : "1" , 215} 216if clang_bin : 217env [ "CLANG_PATH" ] = clang_bin . path 218 219args = ctx . actions . args () 220 221# Configure Bindgen Arguments 222args . add_all ( ctx . attr . bindgen_flags ) 223args . add ( header ) 224args . add ( "--output" , output ) 225 226wrap_static_fns = getattr ( ctx . attr , "wrap_static_fns" , False ) 227 228c_output = None 229if wrap_static_fns : 230if "--wrap-static-fns" in ctx . attr . bindgen_flags : 231fail ( "Do not pass `--wrap-static-fns` to `bindgen_flags, it's added automatically." + 232"The generated C file is accesible in the `bindgen_c_thunks` output group." ) 233c_output = ctx . actions . declare_file ( ctx . label . name + ".bindgen_c_thunks.c" ) 234args . add ( "--experimental" ) 235args . add ( "--wrap-static-fns" ) 236args . add ( "--wrap-static-fns-path" ) 237args . add ( c_output . path ) 238 239# Vanilla usage of bindgen produces formatted output, here we do the same if we have `rustfmt` in our toolchain. 240rustfmt_toolchain = ctx . toolchains [ Label ( "@rules_rust//rust/rustfmt:toolchain_type" )] 241if rustfmt_toolchain and toolchain . default_rustfmt : 242# Bindgen is able to find rustfmt using the RUSTFMT environment variable 243env . update ({ "RUSTFMT" : rustfmt_toolchain . rustfmt . path }) 244tools = depset ( transitive = [ tools , rustfmt_toolchain . all_files ]) 245else : 246args . add ( "--no-rustfmt-bindings" ) 247 248# Configure Clang Arguments 249args . add ( "--" ) 250 251compile_variables = cc_common . create_compile_variables ( 252cc_toolchain = cc_toolchain , 253feature_configuration = feature_configuration , 254include_directories = cc_lib [ CcInfo ]. compilation_context . includes , 255quote_include_directories = cc_lib [ CcInfo ]. compilation_context . quote_includes , 256system_include_directories = depset ( 257transitive = [ cc_lib [ CcInfo ]. compilation_context . system_includes ], 258direct = cc_toolchain . built_in_include_directories , 259), 260user_compile_flags = ctx . attr . clang_flags , 261) 262compile_flags = cc_common . get_memory_inefficient_command_line ( 263feature_configuration = feature_configuration , 264action_name = CPP_COMPILE_ACTION_NAME , 265variables = compile_variables , 266) 267 268# Bindgen forcibly uses clang. 269# It's possible that the selected cc_toolchain isn't clang, and may specify flags which clang doesn't recognise. 270# Ideally we could depend on a more specific toolchain, requesting one which is specifically clang via some constraint. 271# Unfortunately, we can't currently rely on this, so instead we filter only to flags we know clang supports. 272# We can add extra flags here as needed. 273flags_known_to_clang = ( 274"-I" , 275"-iquote" , 276"-isystem" , 277"--sysroot" , 278"--gcc-toolchain" , 279"--target" , 280"-W" , 281"--system-header-prefix" , 282"--no-system-header-prefix" , 283"-Xclang" , 284"-D" , 285"-no-canonical-prefixes" , 286"-nostd" , 287) 288open_arg = False 289for arg in compile_flags : 290if open_arg : 291args . add ( arg ) 292open_arg = False 293 continue 294 295# The cc_toolchain merged these flags into its returned flags - don't strip these out. 296if arg in ctx . attr . clang_flags : 297args . add ( arg ) 298 continue 299 300if not arg . startswith ( flags_known_to_clang ): 301 continue 302 303args . add ( arg ) 304 305if arg in flags_known_to_clang : 306open_arg = True 307 continue 308 309_ , _ , linker_env = get_linker_and_args ( ctx , "bin" , cc_toolchain , feature_configuration , None ) 310env . update ( ** linker_env ) 311 312# Set the dynamic linker search path so that clang uses the libstdcxx from the toolchain. 313# DYLD_LIBRARY_PATH is LD_LIBRARY_PATH on macOS. 314if libstdcxx : 315env [ "LD_LIBRARY_PATH" ] = ":" . join ([ f . dirname for f in _get_libs_for_static_executable ( libstdcxx ). to_list ()]) 316env [ "DYLD_LIBRARY_PATH" ] = env [ "LD_LIBRARY_PATH" ] 317 318ctx . actions . run ( 319executable = bindgen_bin , 320inputs = depset ( 321[ header ], 322transitive = [ 323cc_lib [ CcInfo ]. compilation_context . headers , 324_get_libs_for_static_executable ( libclang ), 325] + ([ 326_get_libs_for_static_executable ( libstdcxx ), 327] if libstdcxx else []), 328), 329outputs = [ output ] + ([ c_output ] if wrap_static_fns else []), 330mnemonic = "RustBindgen" , 331progress_message = "Generating bindings for {}.." . format ( header . path ), 332env = env , 333arguments = [ args ], 334tools = tools , 335# ctx.actions.run now require (through a buildifier check) that we 336# specify this 337toolchain = None , 338) 339 340if ctx . attr . merge_cc_lib_objects_into_rlib : 341providers = [ 342_generate_cc_link_build_info ( ctx , cc_lib ), 343# As in https://github.com/bazelbuild/rules_rust/pull/2361, we want 344# to link cc_lib to the direct parent (rlib) using `-lstatic=<cc_lib>` 345# rustc flag. Hence, we do not need to provide the whole CcInfo of 346# cc_lib because it will cause the downstream binary to link the cc_lib 347# again. The CcInfo here only contains the custom link flags (i.e. 348# linkopts attribute) specified by users in cc_lib. 349CcInfo ( 350linking_context = cc_common . create_linking_context ( 351linker_inputs = depset ([ cc_common . create_linker_input ( 352owner = ctx . label , 353user_link_flags = _get_user_link_flags ( cc_lib ), 354)]), 355), 356), 357] 358else : 359providers = [ cc_lib [ CcInfo ]] 360 361return providers + [ 362OutputGroupInfo ( 363bindgen_bindings = depset ([ output ]), 364bindgen_c_thunks = depset (([ c_output ] if wrap_static_fns else [])), 365), 366] 367 368rust_bindgen = rule ( 369doc = "Generates a rust source file from a cc_library and a header." , 370implementation = _rust_bindgen_impl , 371attrs = { 372"bindgen_flags" : attr . string_list ( 373doc = "Flags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details." , 374), 375"cc_lib" : attr . label ( 376doc = "The cc_library that contains the `.h` file. This is used to find the transitive includes." , 377providers = [ CcInfo ], 378mandatory = True , 379), 380"clang_flags" : attr . string_list ( 381doc = "Flags to pass directly to the clang executable." , 382), 383"header" : attr . label ( 384doc = "The `.h` file to generate bindings for." , 385allow_single_file = True , 386mandatory = True , 387), 388"merge_cc_lib_objects_into_rlib" : attr . bool ( 389doc = ( "When True, objects from `cc_lib` will be copied into the `rlib` archive produced by " + 390"the rust_library that depends on this `rust_bindgen` rule (using `BuildInfo` provider)" ), 391default = True , 392), 393"wrap_static_fns" : attr . bool ( 394doc = "Whether to create a separate .c file for static fns. Requires nightly toolchain, and a header that actually needs this feature (otherwise bindgen won't generate the file and Bazel complains)." , 395default = False , 396), 397"_cc_toolchain" : attr . label ( 398default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 399), 400"_process_wrapper" : attr . label ( 401default = Label ( "@rules_rust//util/process_wrapper" ), 402executable = True , 403allow_single_file = True , 404cfg = "exec" , 405), 406}, 407outputs = { "out" : "%{name}.rs" }, 408fragments = [ "cpp" ], 409toolchains = [ 410config_common . toolchain_type ( "//:toolchain_type" ), 411config_common . toolchain_type ( "@rules_rust//rust:toolchain_type" ), 412config_common . toolchain_type ( "@rules_rust//rust/rustfmt:toolchain_type" , mandatory = False ), 413config_common . toolchain_type ( "@bazel_tools//tools/cpp:toolchain_type" ), 414], 415) 416 417def _rust_bindgen_toolchain_impl ( ctx ): 418return platform_common . ToolchainInfo ( 419bindgen = ctx . executable . bindgen , 420clang = ctx . executable . clang , 421libclang = ctx . attr . libclang , 422libstdcxx = ctx . attr . libstdcxx , 423default_rustfmt = ctx . attr . default_rustfmt , 424) 425 426rust_bindgen_toolchain = rule ( 427_rust_bindgen_toolchain_impl , 428doc = """\ 429The tools required for the `rust_bindgen` rule. 430 431This rule depends on the [`bindgen`](https://crates.io/crates/bindgen) binary crate, and it 432in turn depends on both a clang binary and the clang library. To obtain these dependencies, 433`rust_bindgen_dependencies` imports bindgen and its dependencies. 434 435```python 436load("@rules_rust_bindgen//:defs.bzl", "rust_bindgen_toolchain") 437 438rust_bindgen_toolchain( 439name = "bindgen_toolchain_impl", 440bindgen = "//my/rust:bindgen", 441clang = "//my/clang:clang", 442libclang = "//my/clang:libclang.so", 443libstdcxx = "//my/cpp:libstdc++", 444) 445 446toolchain( 447name = "bindgen_toolchain", 448toolchain = "bindgen_toolchain_impl", 449toolchain_type = "@rules_rust_bindgen//:toolchain_type", 450) 451``` 452 453This toolchain will then need to be registered in the current `WORKSPACE`. 454For additional information, see the [Bazel toolchains documentation](https://docs.bazel.build/versions/master/toolchains.html). 455""" , 456attrs = { 457"bindgen" : attr . label ( 458doc = "The label of a `bindgen` executable." , 459executable = True , 460cfg = "exec" , 461), 462"clang" : attr . label ( 463doc = "The label of a `clang` executable." , 464executable = True , 465cfg = "exec" , 466allow_files = True , 467), 468"default_rustfmt" : attr . bool ( 469doc = "If set, `rust_bindgen` targets will always format generated sources with `rustfmt`." , 470mandatory = False , 471default = True , 472), 473"libclang" : attr . label ( 474doc = "A cc_library that provides bindgen's runtime dependency on libclang." , 475cfg = "exec" , 476providers = [ CcInfo ], 477allow_files = True , 478), 479"libstdcxx" : attr . label ( 480doc = "A cc_library that satisfies libclang's libstdc++ dependency. This is used to make the execution of clang hermetic. If None, system libraries will be used instead." , 481cfg = "exec" , 482providers = [ CcInfo ], 483mandatory = False , 484allow_files = True , 485), 486}, 487)