fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

Erik GillingUse correct dynamic link args fro proc-macro crates (#1803)a5853fd3

rust-analyzer
11.2 KiB306 linesraw
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("//rust:defs.bzl", "rust_library")
18
19# buildifier: disable=bzl-visibility
20load("//rust/private:rustc.bzl", "get_linker_and_args")
21
22# buildifier: disable=bzl-visibility
23load("//rust/private:utils.bzl", "find_cc_toolchain", "get_preferred_artifact")
24
25# TODO(hlopko): use the more robust logic from rustc.bzl also here, through a reasonable API.
26def _get_libs_for_static_executable(dep):
27    """find the libraries used for linking a static executable.
28
29    Args:
30        dep (Target): A cc_library target.
31
32    Returns:
33        depset: A depset[File]
34    """
35    linker_inputs = dep[CcInfo].linking_context.linker_inputs.to_list()
36    return depset([get_preferred_artifact(lib, use_pic = False) for li in linker_inputs for lib in li.libraries])
37
38def rust_bindgen_library(
39        name,
40        header,
41        cc_lib,
42        bindgen_flags = None,
43        clang_flags = None,
44        rustfmt = True,
45        **kwargs):
46    """Generates a rust source file for `header`, and builds a rust_library.
47
48    Arguments are the same as `rust_bindgen`, and `kwargs` are passed directly to rust_library.
49
50    Args:
51        name (str): A unique name for this target.
52        header (str): The label of the .h file to generate bindings for.
53        cc_lib (str): The label of the cc_library that contains the .h file. This is used to find the transitive includes.
54        bindgen_flags (list, optional): Flags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.
55        clang_flags (list, optional): Flags to pass directly to the clang executable.
56        rustfmt (bool, optional): Enable or disable running rustfmt on the generated file.
57        **kwargs: Arguments to forward to the underlying `rust_library` rule.
58    """
59
60    tags = kwargs.get("tags") or []
61    if "tags" in kwargs:
62        kwargs.pop("tags")
63
64    deps = kwargs.get("deps") or []
65    if "deps" in kwargs:
66        kwargs.pop("deps")
67
68    rust_bindgen(
69        name = name + "__bindgen",
70        header = header,
71        cc_lib = cc_lib,
72        bindgen_flags = bindgen_flags or [],
73        clang_flags = clang_flags or [],
74        rustfmt = rustfmt,
75        tags = tags,
76    )
77
78    rust_library(
79        name = name,
80        srcs = [name + "__bindgen.rs"],
81        tags = tags + ["__bindgen", "noclippy"],
82        deps = deps + [cc_lib],
83        **kwargs
84    )
85
86def _rust_bindgen_impl(ctx):
87    toolchain = ctx.toolchains[Label("//bindgen:toolchain_type")]
88    rustfmt_toolchain = ctx.toolchains[Label("//rust/rustfmt:toolchain_type")]
89
90    # nb. We can't grab the cc_library`s direct headers, so a header must be provided.
91    cc_lib = ctx.attr.cc_lib
92    header = ctx.file.header
93    cc_header_list = ctx.attr.cc_lib[CcInfo].compilation_context.headers.to_list()
94    if header not in cc_header_list:
95        fail("Header {} is not in {}'s transitive headers.".format(ctx.attr.header, cc_lib), "header")
96
97    toolchain = ctx.toolchains[Label("//bindgen:toolchain_type")]
98    bindgen_bin = toolchain.bindgen
99    rustfmt_bin = rustfmt_toolchain.rustfmt
100    clang_bin = toolchain.clang
101    libclang = toolchain.libclang
102    libstdcxx = toolchain.libstdcxx
103
104    # rustfmt is not where bindgen expects to find it, so we format manually
105    bindgen_args = ["--no-rustfmt-bindings"] + ctx.attr.bindgen_flags
106    clang_args = ctx.attr.clang_flags
107
108    output = ctx.outputs.out
109
110    # libclang should only have 1 output file
111    libclang_dir = _get_libs_for_static_executable(libclang).to_list()[0].dirname
112    include_directories = cc_lib[CcInfo].compilation_context.includes.to_list()
113    quote_include_directories = cc_lib[CcInfo].compilation_context.quote_includes.to_list()
114    system_include_directories = cc_lib[CcInfo].compilation_context.system_includes.to_list()
115
116    # Vanilla usage of bindgen produces formatted output, here we do the same if we have `rustfmt` in our toolchain.
117    run_rustfmt = toolchain.default_rustfmt or ctx.attr.rustfmt
118    if run_rustfmt:
119        unformatted_output = ctx.actions.declare_file(output.basename + ".unformatted")
120    else:
121        unformatted_output = output
122
123    args = ctx.actions.args()
124    args.add_all(bindgen_args)
125    args.add(header.path)
126    args.add("--output", unformatted_output)
127    args.add("--")
128    args.add_all(include_directories, before_each = "-I")
129    args.add_all(quote_include_directories, before_each = "-iquote")
130    args.add_all(system_include_directories, before_each = "-isystem")
131    args.add_all(clang_args)
132
133    env = {
134        "CLANG_PATH": clang_bin.path,
135        "LIBCLANG_PATH": libclang_dir,
136        "RUST_BACKTRACE": "1",
137    }
138    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
139    _, _, linker_env = get_linker_and_args(ctx, ctx.attr, "bin", cc_toolchain, feature_configuration, None)
140    env.update(**linker_env)
141
142    # Set the dynamic linker search path so that clang uses the libstdcxx from the toolchain.
143    # DYLD_LIBRARY_PATH is LD_LIBRARY_PATH on macOS.
144    if libstdcxx:
145        env["LD_LIBRARY_PATH"] = ":".join([f.dirname for f in _get_libs_for_static_executable(libstdcxx).to_list()])
146        env["DYLD_LIBRARY_PATH"] = env["LD_LIBRARY_PATH"]
147
148    ctx.actions.run(
149        executable = bindgen_bin,
150        inputs = depset(
151            [header],
152            transitive = [
153                cc_lib[CcInfo].compilation_context.headers,
154                _get_libs_for_static_executable(libclang),
155            ] + ([
156                _get_libs_for_static_executable(libstdcxx),
157            ] if libstdcxx else []),
158        ),
159        outputs = [unformatted_output],
160        mnemonic = "RustBindgen",
161        progress_message = "Generating bindings for {}..".format(header.path),
162        env = env,
163        arguments = [args],
164        tools = [clang_bin],
165    )
166
167    if run_rustfmt:
168        rustfmt_args = ctx.actions.args()
169        rustfmt_args.add("--stdout-file", output)
170        rustfmt_args.add("--")
171        rustfmt_args.add(rustfmt_bin)
172        rustfmt_args.add("--emit", "stdout")
173        rustfmt_args.add("--quiet")
174        rustfmt_args.add(unformatted_output)
175
176        ctx.actions.run(
177            executable = ctx.executable._process_wrapper,
178            inputs = [unformatted_output],
179            outputs = [output],
180            arguments = [rustfmt_args],
181            tools = [rustfmt_toolchain.all_files],
182            mnemonic = "RustfmtBindgen",
183        )
184
185rust_bindgen = rule(
186    doc = "Generates a rust source file from a cc_library and a header.",
187    implementation = _rust_bindgen_impl,
188    attrs = {
189        "bindgen_flags": attr.string_list(
190            doc = "Flags to pass directly to the bindgen executable. See https://rust-lang.github.io/rust-bindgen/ for details.",
191        ),
192        "cc_lib": attr.label(
193            doc = "The cc_library that contains the `.h` file. This is used to find the transitive includes.",
194            providers = [CcInfo],
195        ),
196        "clang_flags": attr.string_list(
197            doc = "Flags to pass directly to the clang executable.",
198        ),
199        "header": attr.label(
200            doc = "The `.h` file to generate bindings for.",
201            allow_single_file = True,
202        ),
203        "rustfmt": attr.bool(
204            doc = "Enable or disable running rustfmt on the generated file.",
205            default = True,
206        ),
207        "_cc_toolchain": attr.label(
208            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
209        ),
210        "_process_wrapper": attr.label(
211            default = Label("//util/process_wrapper"),
212            executable = True,
213            allow_single_file = True,
214            cfg = "exec",
215        ),
216    },
217    outputs = {"out": "%{name}.rs"},
218    fragments = ["cpp"],
219    toolchains = [
220        str(Label("//bindgen:toolchain_type")),
221        str(Label("//rust:toolchain_type")),
222        str(Label("//rust/rustfmt:toolchain_type")),
223        "@bazel_tools//tools/cpp:toolchain_type",
224    ],
225    incompatible_use_toolchain_transition = True,
226)
227
228def _rust_bindgen_toolchain_impl(ctx):
229    if ctx.attr.rustfmt:
230        # buildifier: disable=print
231        print("The `rustfmt` attribute is deprecated. Please remove it on {} and register a `rustfmt_toolchain` instead.".format(
232            ctx.label,
233        ))
234
235    return platform_common.ToolchainInfo(
236        bindgen = ctx.executable.bindgen,
237        clang = ctx.executable.clang,
238        libclang = ctx.attr.libclang,
239        libstdcxx = ctx.attr.libstdcxx,
240        default_rustfmt = ctx.attr.default_rustfmt,
241    )
242
243rust_bindgen_toolchain = rule(
244    _rust_bindgen_toolchain_impl,
245    doc = """\
246The tools required for the `rust_bindgen` rule.
247
248This rule depends on the [`bindgen`](https://crates.io/crates/bindgen) binary crate, and it 
249in turn depends on both a clang binary and the clang library. To obtain these dependencies,
250`rust_bindgen_dependencies` imports bindgen and its dependencies.
251
252```python
253load("@rules_rust//bindgen:bindgen.bzl", "rust_bindgen_toolchain")
254
255rust_bindgen_toolchain(
256    name = "bindgen_toolchain_impl",
257    bindgen = "//my/rust:bindgen",
258    clang = "//my/clang:clang",
259    libclang = "//my/clang:libclang.so",
260    libstdcxx = "//my/cpp:libstdc++",
261)
262
263toolchain(
264    name = "bindgen_toolchain",
265    toolchain = "bindgen_toolchain_impl",
266    toolchain_type = "@rules_rust//bindgen:toolchain_type",
267)
268```
269
270This toolchain will then need to be registered in the current `WORKSPACE`.
271For additional information, see the [Bazel toolchains documentation](https://docs.bazel.build/versions/master/toolchains.html).
272""",
273    attrs = {
274        "bindgen": attr.label(
275            doc = "The label of a `bindgen` executable.",
276            executable = True,
277            cfg = "exec",
278        ),
279        "clang": attr.label(
280            doc = "The label of a `clang` executable.",
281            executable = True,
282            cfg = "exec",
283        ),
284        "default_rustfmt": attr.bool(
285            doc = "If set, `rust_bindgen` targets will always format generated sources with `rustfmt`.",
286            mandatory = False,
287        ),
288        "libclang": attr.label(
289            doc = "A cc_library that provides bindgen's runtime dependency on libclang.",
290            cfg = "exec",
291            providers = [CcInfo],
292        ),
293        "libstdcxx": attr.label(
294            doc = "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.",
295            cfg = "exec",
296            providers = [CcInfo],
297            mandatory = False,
298        ),
299        "rustfmt": attr.label(
300            doc = "**Deprecated**: Instead, register a `rustfmt_toolchain` and refer to the `rust_bindgen_toolchain.default_rustfmt` and `rust_bindgen.rustfmt` attributes.",
301            executable = True,
302            cfg = "exec",
303            mandatory = False,
304        ),
305    },
306)