fork/rules_rust

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

Roberto Bampirules_rust: enable pipelined compilation. (#1275)867fc37c

0.9.0
11.5 KiB332 linesraw
1# Copyright 2018 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"""Rules for generating documentation with `rustdoc` for Bazel built crates"""
16
17load("//rust/private:common.bzl", "rust_common")
18load("//rust/private:rustc.bzl", "collect_deps", "collect_inputs", "construct_arguments")
19load("//rust/private:utils.bzl", "dedent", "find_cc_toolchain", "find_toolchain")
20
21def _strip_crate_info_output(crate_info):
22    """Set the CrateInfo.output to None for a given CrateInfo provider.
23
24    Args:
25        crate_info (CrateInfo): A provider
26
27    Returns:
28        CrateInfo: A modified CrateInfo provider
29    """
30    return rust_common.create_crate_info(
31        name = crate_info.name,
32        type = crate_info.type,
33        root = crate_info.root,
34        srcs = crate_info.srcs,
35        deps = crate_info.deps,
36        proc_macro_deps = crate_info.proc_macro_deps,
37        aliases = crate_info.aliases,
38        # This crate info should have no output
39        output = None,
40        metadata = None,
41        edition = crate_info.edition,
42        rustc_env = crate_info.rustc_env,
43        is_test = crate_info.is_test,
44        compile_data = crate_info.compile_data,
45    )
46
47def rustdoc_compile_action(
48        ctx,
49        toolchain,
50        crate_info,
51        output = None,
52        rustdoc_flags = [],
53        is_test = False):
54    """Create a struct of information needed for a `rustdoc` compile action based on crate passed to the rustdoc rule.
55
56    Args:
57        ctx (ctx): The rule's context object.
58        toolchain (rust_toolchain): The currently configured `rust_toolchain`.
59        crate_info (CrateInfo): The provider of the crate passed to a rustdoc rule.
60        output (File, optional): An optional output a `rustdoc` action is intended to produce.
61        rustdoc_flags (list, optional): A list of `rustdoc` specific flags.
62        is_test (bool, optional): If True, the action will be configured for `rust_doc_test` targets
63
64    Returns:
65        struct: A struct of some `ctx.actions.run` arguments.
66    """
67
68    # If an output was provided, ensure it's used in rustdoc arguments
69    if output:
70        rustdoc_flags = [
71            "--output",
72            output.path,
73        ] + rustdoc_flags
74
75    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
76
77    dep_info, build_info, linkstamps = collect_deps(
78        deps = crate_info.deps,
79        proc_macro_deps = crate_info.proc_macro_deps,
80        aliases = crate_info.aliases,
81    )
82
83    compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
84        ctx = ctx,
85        file = ctx.file,
86        files = ctx.files,
87        linkstamps = linkstamps,
88        toolchain = toolchain,
89        cc_toolchain = cc_toolchain,
90        feature_configuration = feature_configuration,
91        crate_info = crate_info,
92        dep_info = dep_info,
93        build_info = build_info,
94        # If this is a rustdoc test, we need to depend on rlibs rather than .rmeta.
95        force_depend_on_objects = is_test,
96    )
97
98    # Since this crate is not actually producing the output described by the
99    # given CrateInfo, this attribute needs to be stripped to allow the rest
100    # of the rustc functionality in `construct_arguments` to avoid generating
101    # arguments expecting to do so.
102    rustdoc_crate_info = _strip_crate_info_output(crate_info)
103
104    args, env = construct_arguments(
105        ctx = ctx,
106        attr = ctx.attr,
107        file = ctx.file,
108        toolchain = toolchain,
109        tool_path = toolchain.rust_doc.short_path if is_test else toolchain.rust_doc.path,
110        cc_toolchain = cc_toolchain,
111        feature_configuration = feature_configuration,
112        crate_info = rustdoc_crate_info,
113        dep_info = dep_info,
114        linkstamp_outs = linkstamp_outs,
115        ambiguous_libs = ambiguous_libs,
116        output_hash = None,
117        rust_flags = rustdoc_flags,
118        out_dir = out_dir,
119        build_env_files = build_env_files,
120        build_flags_files = build_flags_files,
121        emit = [],
122        remap_path_prefix = None,
123        force_link = True,
124        force_depend_on_objects = is_test,
125    )
126
127    # Because rustdoc tests compile tests outside of the sandbox, the sysroot
128    # must be updated to the `short_path` equivilant as it will now be
129    # a part of runfiles.
130    if is_test:
131        if "SYSROOT" in env:
132            env.update({"SYSROOT": "${{pwd}}/{}".format(toolchain.sysroot_short_path)})
133
134        # `rustdoc` does not support the SYSROOT environment variable. To account
135        # for this, the flag must be explicitly passed to the `rustdoc` binary.
136        args.rustc_flags.add("--sysroot=${{pwd}}/{}".format(toolchain.sysroot_short_path))
137
138    return struct(
139        executable = ctx.executable._process_wrapper,
140        inputs = depset([crate_info.output], transitive = [compile_inputs]),
141        env = env,
142        arguments = args.all,
143        tools = [toolchain.rust_doc],
144    )
145
146def _zip_action(ctx, input_dir, output_zip, crate_label):
147    """Creates an archive of the generated documentation from `rustdoc`
148
149    Args:
150        ctx (ctx): The `rust_doc` rule's context object
151        input_dir (File): A directory containing the outputs from rustdoc
152        output_zip (File): The location of the output archive containing generated documentation
153        crate_label (Label): The label of the crate docs are being generated for.
154    """
155    args = ctx.actions.args()
156    args.add(ctx.executable._zipper)
157    args.add(output_zip)
158    args.add(ctx.bin_dir.path)
159    args.add_all([input_dir], expand_directories = True)
160    ctx.actions.run(
161        executable = ctx.executable._dir_zipper,
162        inputs = [input_dir],
163        outputs = [output_zip],
164        arguments = [args],
165        mnemonic = "RustdocZip",
166        progress_message = "Creating RustdocZip for {}".format(crate_label),
167        tools = [ctx.executable._zipper],
168    )
169
170def _rust_doc_impl(ctx):
171    """The implementation of the `rust_doc` rule
172
173    Args:
174        ctx (ctx): The rule's context object
175    """
176
177    crate = ctx.attr.crate
178    crate_info = crate[rust_common.crate_info]
179
180    output_dir = ctx.actions.declare_directory("{}.rustdoc".format(ctx.label.name))
181
182    # Add the current crate as an extern for the compile action
183    rustdoc_flags = [
184        "--extern",
185        "{}={}".format(crate_info.name, crate_info.output.path),
186    ]
187
188    action = rustdoc_compile_action(
189        ctx = ctx,
190        toolchain = find_toolchain(ctx),
191        crate_info = crate_info,
192        output = output_dir,
193        rustdoc_flags = rustdoc_flags,
194    )
195
196    ctx.actions.run(
197        mnemonic = "Rustdoc",
198        progress_message = "Generating Rustdoc for {}".format(crate.label),
199        outputs = [output_dir],
200        executable = action.executable,
201        inputs = action.inputs,
202        env = action.env,
203        arguments = action.arguments,
204        tools = action.tools,
205    )
206
207    # This rule does nothing without a single-file output, though the directory should've sufficed.
208    _zip_action(ctx, output_dir, ctx.outputs.rust_doc_zip, crate.label)
209
210    return [
211        DefaultInfo(
212            files = depset([ctx.outputs.rust_doc_zip]),
213        ),
214        OutputGroupInfo(
215            rustdoc_dir = depset([output_dir]),
216            rustdoc_zip = depset([ctx.outputs.rust_doc_zip]),
217        ),
218    ]
219
220rust_doc = rule(
221    doc = dedent("""\
222    Generates code documentation.
223
224    Example:
225    Suppose you have the following directory structure for a Rust library crate:
226
227    ```
228    [workspace]/
229        WORKSPACE
230        hello_lib/
231            BUILD
232            src/
233                lib.rs
234    ```
235
236    To build [`rustdoc`][rustdoc] documentation for the `hello_lib` crate, define \
237    a `rust_doc` rule that depends on the the `hello_lib` `rust_library` target:
238
239    [rustdoc]: https://doc.rust-lang.org/book/documentation.html
240
241    ```python
242    package(default_visibility = ["//visibility:public"])
243
244    load("@rules_rust//rust:defs.bzl", "rust_library", "rust_doc")
245
246    rust_library(
247        name = "hello_lib",
248        srcs = ["src/lib.rs"],
249    )
250
251    rust_doc(
252        name = "hello_lib_doc",
253        crate = ":hello_lib",
254    )
255    ```
256
257    Running `bazel build //hello_lib:hello_lib_doc` will build a zip file containing \
258    the documentation for the `hello_lib` library crate generated by `rustdoc`.
259    """),
260    implementation = _rust_doc_impl,
261    attrs = {
262        "crate": attr.label(
263            doc = (
264                "The label of the target to generate code documentation for.\n" +
265                "\n" +
266                "`rust_doc` can generate HTML code documentation for the source files of " +
267                "`rust_library` or `rust_binary` targets."
268            ),
269            providers = [rust_common.crate_info],
270            mandatory = True,
271        ),
272        "html_after_content": attr.label(
273            doc = "File to add in `<body>`, after content.",
274            allow_single_file = [".html", ".md"],
275        ),
276        "html_before_content": attr.label(
277            doc = "File to add in `<body>`, before content.",
278            allow_single_file = [".html", ".md"],
279        ),
280        "html_in_header": attr.label(
281            doc = "File to add to `<head>`.",
282            allow_single_file = [".html", ".md"],
283        ),
284        "markdown_css": attr.label_list(
285            doc = "CSS files to include via `<link>` in a rendered Markdown file.",
286            allow_files = [".css"],
287        ),
288        "rustc_flags": attr.string_list(
289            doc = dedent("""\
290                List of compiler flags passed to `rustc`.
291
292                These strings are subject to Make variable expansion for predefined
293                source/output path variables like `$location`, `$execpath`, and
294                `$rootpath`. This expansion is useful if you wish to pass a generated
295                file of arguments to rustc: `@$(location //package:target)`.
296            """),
297        ),
298        "_cc_toolchain": attr.label(
299            doc = "In order to use find_cpp_toolchain, you must define the '_cc_toolchain' attribute on your rule or aspect.",
300            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
301        ),
302        "_dir_zipper": attr.label(
303            doc = "A tool that orchestrates the creation of zip archives for rustdoc outputs.",
304            default = Label("//util/dir_zipper"),
305            cfg = "exec",
306            executable = True,
307        ),
308        "_process_wrapper": attr.label(
309            doc = "A process wrapper for running rustdoc on all platforms",
310            default = Label("@rules_rust//util/process_wrapper"),
311            executable = True,
312            allow_single_file = True,
313            cfg = "exec",
314        ),
315        "_zipper": attr.label(
316            doc = "A Bazel provided tool for creating archives",
317            default = Label("@bazel_tools//tools/zip:zipper"),
318            cfg = "exec",
319            executable = True,
320        ),
321    },
322    fragments = ["cpp"],
323    host_fragments = ["cpp"],
324    outputs = {
325        "rust_doc_zip": "%{name}.zip",
326    },
327    toolchains = [
328        str(Label("//rust:toolchain_type")),
329        "@bazel_tools//tools/cpp:toolchain_type",
330    ],
331    incompatible_use_toolchain_transition = True,
332)