fork/rules_rust

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

Cameron MulhernPrevents running of clippy on bindgen targets (#1320)1590670a

0.5.0
11.0 KiB326 linesraw
1# Copyright 2020 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"""A module defining clippy rules"""
16
17load("//rust/private:common.bzl", "rust_common")
18load("//rust/private:providers.bzl", "CaptureClippyOutputInfo", "ClippyInfo")
19load(
20    "//rust/private:rustc.bzl",
21    "collect_deps",
22    "collect_inputs",
23    "construct_arguments",
24)
25load(
26    "//rust/private:utils.bzl",
27    "determine_output_hash",
28    "find_cc_toolchain",
29    "find_toolchain",
30)
31
32ClippyFlagsInfo = provider(
33    doc = "Pass each value as an additional flag to clippy invocations",
34    fields = {"clippy_flags": "List[string] Flags to pass to clippy"},
35)
36
37def _clippy_flags_impl(ctx):
38    return ClippyFlagsInfo(clippy_flags = ctx.build_setting_value)
39
40clippy_flags = rule(
41    doc = (
42        "Add custom clippy flags from the command line with `--@rules_rust//:clippy_flags`."
43    ),
44    implementation = _clippy_flags_impl,
45    build_setting = config.string_list(flag = True),
46)
47
48def _get_clippy_ready_crate_info(target, aspect_ctx):
49    """Check that a target is suitable for clippy and extract the `CrateInfo` provider from it.
50
51    Args:
52        target (Target): The target the aspect is running on.
53        aspect_ctx (ctx, optional): The aspect's context object.
54
55    Returns:
56        CrateInfo, optional: A `CrateInfo` provider if clippy should be run or `None`.
57    """
58
59    # Ignore external targets
60    if target.label.workspace_root.startswith("external"):
61        return None
62
63    # Targets annotated with `noclippy` will not be formatted
64    if aspect_ctx and "noclippy" in aspect_ctx.rule.attr.tags:
65        return None
66
67    # Obviously ignore any targets that don't contain `CrateInfo`
68    if rust_common.crate_info not in target:
69        return None
70
71    return target[rust_common.crate_info]
72
73def _clippy_aspect_impl(target, ctx):
74    crate_info = _get_clippy_ready_crate_info(target, ctx)
75    if not crate_info:
76        return [ClippyInfo(output = depset([]))]
77
78    toolchain = find_toolchain(ctx)
79    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
80
81    dep_info, build_info, linkstamps = collect_deps(
82        deps = crate_info.deps,
83        proc_macro_deps = crate_info.proc_macro_deps,
84        aliases = crate_info.aliases,
85        # Clippy doesn't need to invoke transitive linking, therefore doesn't need linkstamps.
86        are_linkstamps_supported = False,
87    )
88
89    compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
90        ctx,
91        ctx.rule.file,
92        ctx.rule.files,
93        linkstamps,
94        toolchain,
95        cc_toolchain,
96        feature_configuration,
97        crate_info,
98        dep_info,
99        build_info,
100    )
101
102    args, env = construct_arguments(
103        ctx = ctx,
104        attr = ctx.rule.attr,
105        file = ctx.file,
106        toolchain = toolchain,
107        tool_path = toolchain.clippy_driver.path,
108        cc_toolchain = cc_toolchain,
109        feature_configuration = feature_configuration,
110        crate_info = crate_info,
111        dep_info = dep_info,
112        linkstamp_outs = linkstamp_outs,
113        ambiguous_libs = ambiguous_libs,
114        output_hash = determine_output_hash(crate_info.root, ctx.label),
115        rust_flags = [],
116        out_dir = out_dir,
117        build_env_files = build_env_files,
118        build_flags_files = build_flags_files,
119        emit = ["dep-info", "metadata"],
120    )
121
122    if crate_info.is_test:
123        args.rustc_flags.add("--test")
124
125    clippy_flags = ctx.attr._clippy_flags[ClippyFlagsInfo].clippy_flags
126
127    # For remote execution purposes, the clippy_out file must be a sibling of crate_info.output
128    # or rustc may fail to create intermediate output files because the directory does not exist.
129    if ctx.attr._capture_output[CaptureClippyOutputInfo].capture_output:
130        clippy_out = ctx.actions.declare_file(ctx.label.name + ".clippy.out", sibling = crate_info.output)
131        args.process_wrapper_flags.add("--stderr-file", clippy_out.path)
132
133        if clippy_flags:
134            fail("""Combining @rules_rust//:clippy_flags with @rules_rust//:capture_clippy_output=true is currently not supported.
135See https://github.com/bazelbuild/rules_rust/pull/1264#discussion_r853241339 for more detail.""")
136
137        # If we are capturing the output, we want the build system to be able to keep going
138        # and consume the output. Some clippy lints are denials, so we treat them as warnings.
139        args.rustc_flags.add("-Wclippy::all")
140    else:
141        # A marker file indicating clippy has executed successfully.
142        # This file is necessary because "ctx.actions.run" mandates an output.
143        clippy_out = ctx.actions.declare_file(ctx.label.name + ".clippy.ok", sibling = crate_info.output)
144        args.process_wrapper_flags.add("--touch-file", clippy_out.path)
145
146        if clippy_flags:
147            args.rustc_flags.extend(clippy_flags)
148        else:
149            # The user didn't provide any clippy flags explicitly so we apply conservative defaults.
150
151            # Turn any warnings from clippy or rustc into an error, as otherwise
152            # Bazel will consider the execution result of the aspect to be "success",
153            # and Clippy won't be re-triggered unless the source file is modified.
154            args.rustc_flags.add("-Dwarnings")
155
156    # Upstream clippy requires one of these two filenames or it silently uses
157    # the default config. Enforce the naming so users are not confused.
158    valid_config_file_names = [".clippy.toml", "clippy.toml"]
159    if ctx.file._config.basename not in valid_config_file_names:
160        fail("The clippy config file must be named one of: {}".format(valid_config_file_names))
161    env["CLIPPY_CONF_DIR"] = "${{pwd}}/{}".format(ctx.file._config.dirname)
162    compile_inputs = depset([ctx.file._config], transitive = [compile_inputs])
163
164    ctx.actions.run(
165        executable = ctx.executable._process_wrapper,
166        inputs = compile_inputs,
167        outputs = [clippy_out],
168        env = env,
169        tools = [toolchain.clippy_driver],
170        arguments = args.all,
171        mnemonic = "Clippy",
172    )
173
174    return [
175        OutputGroupInfo(clippy_checks = depset([clippy_out])),
176        ClippyInfo(output = depset([clippy_out])),
177    ]
178
179# Example: Run the clippy checker on all targets in the codebase.
180#   bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \
181#               --output_groups=clippy_checks \
182#               //...
183rust_clippy_aspect = aspect(
184    fragments = ["cpp"],
185    host_fragments = ["cpp"],
186    attrs = {
187        "_capture_output": attr.label(
188            doc = "Value of the `capture_clippy_output` build setting",
189            default = Label("//:capture_clippy_output"),
190        ),
191        "_cc_toolchain": attr.label(
192            doc = (
193                "Required attribute to access the cc_toolchain. See [Accessing the C++ toolchain]" +
194                "(https://docs.bazel.build/versions/master/integrating-with-rules-cc.html#accessing-the-c-toolchain)"
195            ),
196            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
197        ),
198        "_clippy_flags": attr.label(
199            doc = "Arguments to pass to clippy",
200            default = Label("//:clippy_flags"),
201        ),
202        "_config": attr.label(
203            doc = "The `clippy.toml` file used for configuration",
204            allow_single_file = True,
205            default = Label("//:clippy.toml"),
206        ),
207        "_error_format": attr.label(
208            doc = "The desired `--error-format` flags for clippy",
209            default = "//:error_format",
210        ),
211        "_extra_rustc_flags": attr.label(default = "//:extra_rustc_flags"),
212        "_process_wrapper": attr.label(
213            doc = "A process wrapper for running clippy on all platforms",
214            default = Label("//util/process_wrapper"),
215            executable = True,
216            cfg = "exec",
217        ),
218    },
219    provides = [ClippyInfo],
220    toolchains = [
221        str(Label("//rust:toolchain")),
222        "@bazel_tools//tools/cpp:toolchain_type",
223    ],
224    incompatible_use_toolchain_transition = True,
225    implementation = _clippy_aspect_impl,
226    doc = """\
227Executes the clippy checker on specified targets.
228
229This aspect applies to existing rust_library, rust_test, and rust_binary rules.
230
231As an example, if the following is defined in `examples/hello_lib/BUILD.bazel`:
232
233```python
234load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
235
236rust_library(
237    name = "hello_lib",
238    srcs = ["src/lib.rs"],
239)
240
241rust_test(
242    name = "greeting_test",
243    srcs = ["tests/greeting.rs"],
244    deps = [":hello_lib"],
245)
246```
247
248Then the targets can be analyzed with clippy using the following command:
249
250```output
251$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect \
252              --output_groups=clippy_checks //hello_lib:all
253```
254""",
255)
256
257def _rust_clippy_rule_impl(ctx):
258    clippy_ready_targets = [dep for dep in ctx.attr.deps if "clippy_checks" in dir(dep[OutputGroupInfo])]
259    files = depset([], transitive = [dep[OutputGroupInfo].clippy_checks for dep in clippy_ready_targets])
260    return [DefaultInfo(files = files)]
261
262rust_clippy = rule(
263    implementation = _rust_clippy_rule_impl,
264    attrs = {
265        "deps": attr.label_list(
266            doc = "Rust targets to run clippy on.",
267            providers = [rust_common.crate_info],
268            aspects = [rust_clippy_aspect],
269        ),
270    },
271    doc = """\
272Executes the clippy checker on a specific target.
273
274Similar to `rust_clippy_aspect`, but allows specifying a list of dependencies \
275within the build system.
276
277For example, given the following example targets:
278
279```python
280load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
281
282rust_library(
283    name = "hello_lib",
284    srcs = ["src/lib.rs"],
285)
286
287rust_test(
288    name = "greeting_test",
289    srcs = ["tests/greeting.rs"],
290    deps = [":hello_lib"],
291)
292```
293
294Rust clippy can be set as a build target with the following:
295
296```python
297load("@rules_rust//rust:defs.bzl", "rust_clippy")
298
299rust_clippy(
300    name = "hello_library_clippy",
301    testonly = True,
302    deps = [
303        ":hello_lib",
304        ":greeting_test",
305    ],
306)
307```
308""",
309)
310
311def _capture_clippy_output_impl(ctx):
312    """Implementation of the `capture_clippy_output` rule
313
314    Args:
315        ctx (ctx): The rule's context object
316
317    Returns:
318        list: A list containing the CaptureClippyOutputInfo provider
319    """
320    return [CaptureClippyOutputInfo(capture_output = ctx.build_setting_value)]
321
322capture_clippy_output = rule(
323    doc = "Control whether to print clippy output or store it to a file, using the configured error_format.",
324    implementation = _capture_clippy_output_impl,
325    build_setting = config.bool(flag = True),
326)