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