fork/rules_rust

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

UebelAndreMigrate all settings labels from aliases to using settings package (#3032)c3d71edd

main
10.3 KiB346 linesraw
1"""A module defining rustfmt rules"""
2
3load(":common.bzl", "rust_common")
4
5def _get_rustfmt_ready_crate_info(target):
6    """Check that a target is suitable for rustfmt and extract the `CrateInfo` provider from it.
7
8    Args:
9        target (Target): The target the aspect is running on.
10
11    Returns:
12        CrateInfo, optional: A `CrateInfo` provider if clippy should be run or `None`.
13    """
14
15    # Ignore external targets
16    if target.label.workspace_name:
17        return None
18
19    # Obviously ignore any targets that don't contain `CrateInfo`
20    if rust_common.crate_info in target:
21        return target[rust_common.crate_info]
22    elif rust_common.test_crate_info in target:
23        return target[rust_common.test_crate_info].crate
24    else:
25        return None
26
27def _find_rustfmtable_srcs(crate_info, aspect_ctx = None):
28    """Parse a `CrateInfo` provider for rustfmt formattable sources.
29
30    Args:
31        crate_info (CrateInfo): A `CrateInfo` provider.
32        aspect_ctx (ctx, optional): The aspect's context object.
33
34    Returns:
35        list: A list of formattable sources (`File`).
36    """
37
38    # Targets with specific tags will not be formatted
39    if aspect_ctx:
40        ignore_tags = [
41            "no_format",
42            "no_rustfmt",
43            "norustfmt",
44        ]
45
46        for tag in aspect_ctx.rule.attr.tags:
47            if tag.replace("-", "_").lower() in ignore_tags:
48                return []
49
50    # Filter out any generated files
51    srcs = [src for src in crate_info.srcs.to_list() if src.is_source]
52
53    return srcs
54
55def _generate_manifest(edition, srcs, ctx):
56    workspace = ctx.label.workspace_name or ctx.workspace_name
57
58    # Gather the source paths to non-generated files
59    content = ctx.actions.args()
60    content.set_param_file_format("multiline")
61    content.add_all(srcs, format_each = workspace + "/%s")
62    content.add(edition)
63
64    # Write the rustfmt manifest
65    manifest = ctx.actions.declare_file(ctx.label.name + ".rustfmt")
66    ctx.actions.write(
67        output = manifest,
68        content = content,
69    )
70
71    return manifest
72
73def _perform_check(edition, srcs, ctx):
74    rustfmt_toolchain = ctx.toolchains[Label("//rust/rustfmt:toolchain_type")]
75
76    config = ctx.file._config
77    marker = ctx.actions.declare_file(ctx.label.name + ".rustfmt.ok")
78
79    args = ctx.actions.args()
80    args.add("--touch-file", marker)
81    args.add("--")
82    args.add(rustfmt_toolchain.rustfmt)
83    args.add("--config-path", config)
84    args.add("--edition", edition)
85    args.add("--check")
86    args.add_all(srcs)
87
88    ctx.actions.run(
89        executable = ctx.executable._process_wrapper,
90        inputs = srcs + [config],
91        outputs = [marker],
92        tools = [rustfmt_toolchain.all_files],
93        arguments = [args],
94        mnemonic = "Rustfmt",
95        progress_message = "Rustfmt %{label}",
96    )
97
98    return marker
99
100def _rustfmt_aspect_impl(target, ctx):
101    crate_info = _get_rustfmt_ready_crate_info(target)
102
103    if not crate_info:
104        return []
105
106    srcs = _find_rustfmtable_srcs(crate_info, ctx)
107
108    # If there are no formattable sources, do nothing.
109    if not srcs:
110        return []
111
112    edition = crate_info.edition
113
114    marker = _perform_check(edition, srcs, ctx)
115
116    return [
117        OutputGroupInfo(
118            rustfmt_checks = depset([marker]),
119        ),
120    ]
121
122rustfmt_aspect = aspect(
123    implementation = _rustfmt_aspect_impl,
124    doc = """\
125This aspect is used to gather information about a crate for use in rustfmt and perform rustfmt checks
126
127Output Groups:
128
129- `rustfmt_checks`: Executes `rustfmt --check` on the specified target.
130
131The build setting `@rules_rust//rust/settings:rustfmt.toml` is used to control the Rustfmt [configuration settings][cs]
132used at runtime.
133
134[cs]: https://rust-lang.github.io/rustfmt/
135
136This aspect is executed on any target which provides the `CrateInfo` provider. However
137users may tag a target with `no-rustfmt` or `no-format` to have it skipped. Additionally,
138generated source files are also ignored by this aspect.
139""",
140    attrs = {
141        "_config": attr.label(
142            doc = "The `rustfmt.toml` file used for formatting",
143            allow_single_file = True,
144            default = Label("//rust/settings:rustfmt.toml"),
145        ),
146        "_process_wrapper": attr.label(
147            doc = "A process wrapper for running rustfmt on all platforms",
148            cfg = "exec",
149            executable = True,
150            default = Label("//util/process_wrapper"),
151        ),
152    },
153    required_providers = [
154        [rust_common.crate_info],
155        [rust_common.test_crate_info],
156    ],
157    fragments = ["cpp"],
158    toolchains = [
159        str(Label("//rust/rustfmt:toolchain_type")),
160    ],
161)
162
163def _rustfmt_test_manifest_aspect_impl(target, ctx):
164    crate_info = _get_rustfmt_ready_crate_info(target)
165
166    if not crate_info:
167        return []
168
169    # Parse the edition to use for formatting from the target
170    edition = crate_info.edition
171
172    srcs = _find_rustfmtable_srcs(crate_info, ctx)
173    manifest = _generate_manifest(edition, srcs, ctx)
174
175    return [
176        OutputGroupInfo(
177            rustfmt_manifest = depset([manifest]),
178        ),
179    ]
180
181# This aspect contains functionality split out of `rustfmt_aspect` which broke when
182# `required_providers` was added to it. Aspects which have `required_providers` seems
183# to not function with attributes that also require providers.
184_rustfmt_test_manifest_aspect = aspect(
185    implementation = _rustfmt_test_manifest_aspect_impl,
186    doc = """\
187This aspect is used to gather information about a crate for use in `rustfmt_test`
188
189Output Groups:
190
191- `rustfmt_manifest`: A manifest used by rustfmt binaries to provide crate specific settings.
192""",
193    fragments = ["cpp"],
194    toolchains = [
195        str(Label("//rust/rustfmt:toolchain_type")),
196    ],
197)
198
199def _rustfmt_test_impl(ctx):
200    # The executable of a test target must be the output of an action in
201    # the rule implementation. This file is simply a symlink to the real
202    # rustfmt test runner.
203    is_windows = ctx.executable._runner.extension == ".exe"
204    runner = ctx.actions.declare_file("{}{}".format(
205        ctx.label.name,
206        ".exe" if is_windows else "",
207    ))
208
209    ctx.actions.symlink(
210        output = runner,
211        target_file = ctx.executable._runner,
212        is_executable = True,
213    )
214
215    crate_infos = [_get_rustfmt_ready_crate_info(target) for target in ctx.attr.targets]
216    srcs = [depset(_find_rustfmtable_srcs(crate_info)) for crate_info in crate_infos if crate_info]
217
218    # Some targets may be included in tests but tagged as "no-format". In this
219    # case, there will be no manifest.
220    manifests = [getattr(target[OutputGroupInfo], "rustfmt_manifest", None) for target in ctx.attr.targets]
221    manifests = depset(transitive = [manifest for manifest in manifests if manifest])
222
223    runfiles = ctx.runfiles(
224        transitive_files = depset(transitive = srcs + [manifests]),
225    )
226
227    runfiles = runfiles.merge(
228        ctx.attr._runner[DefaultInfo].default_runfiles,
229    )
230
231    workspace = ctx.label.workspace_name or ctx.workspace_name
232
233    return [
234        DefaultInfo(
235            files = depset([runner]),
236            runfiles = runfiles,
237            executable = runner,
238        ),
239        RunEnvironmentInfo(
240            environment = {
241                "RUSTFMT_MANIFESTS": ctx.configuration.host_path_separator.join([
242                    workspace + "/" + manifest.short_path
243                    for manifest in sorted(manifests.to_list())
244                ]),
245                "RUST_BACKTRACE": "1",
246            },
247        ),
248    ]
249
250rustfmt_test = rule(
251    implementation = _rustfmt_test_impl,
252    doc = "A test rule for performing `rustfmt --check` on a set of targets",
253    attrs = {
254        "targets": attr.label_list(
255            doc = "Rust targets to run `rustfmt --check` on.",
256            providers = [
257                [rust_common.crate_info],
258                [rust_common.test_crate_info],
259            ],
260            aspects = [_rustfmt_test_manifest_aspect],
261        ),
262        "_runner": attr.label(
263            doc = "The rustfmt test runner",
264            cfg = "exec",
265            executable = True,
266            default = Label("//tools/rustfmt:rustfmt_test"),
267        ),
268    },
269    test = True,
270)
271
272def _rustfmt_toolchain_impl(ctx):
273    make_variables = {
274        "RUSTFMT": ctx.file.rustfmt.path,
275    }
276
277    if ctx.attr.rustc:
278        make_variables.update({
279            "RUSTC": ctx.file.rustc.path,
280        })
281
282    make_variable_info = platform_common.TemplateVariableInfo(make_variables)
283
284    all_files = [ctx.file.rustfmt] + ctx.files.rustc_lib
285    if ctx.file.rustc:
286        all_files.append(ctx.file.rustc)
287
288    toolchain = platform_common.ToolchainInfo(
289        rustfmt = ctx.file.rustfmt,
290        rustc = ctx.file.rustc,
291        rustc_lib = depset(ctx.files.rustc_lib),
292        all_files = depset(all_files),
293        make_variables = make_variable_info,
294    )
295
296    return [
297        toolchain,
298        make_variable_info,
299    ]
300
301rustfmt_toolchain = rule(
302    doc = "A toolchain for [rustfmt](https://rust-lang.github.io/rustfmt/)",
303    implementation = _rustfmt_toolchain_impl,
304    attrs = {
305        "rustc": attr.label(
306            doc = "The location of the `rustc` binary. Can be a direct source or a filegroup containing one item.",
307            allow_single_file = True,
308            cfg = "exec",
309        ),
310        "rustc_lib": attr.label(
311            doc = "The libraries used by rustc during compilation.",
312            cfg = "exec",
313        ),
314        "rustfmt": attr.label(
315            doc = "The location of the `rustfmt` binary. Can be a direct source or a filegroup containing one item.",
316            allow_single_file = True,
317            cfg = "exec",
318            mandatory = True,
319        ),
320    },
321    toolchains = [
322        str(Label("@rules_rust//rust:toolchain_type")),
323    ],
324)
325
326def _current_rustfmt_toolchain_impl(ctx):
327    toolchain = ctx.toolchains[str(Label("@rules_rust//rust/rustfmt:toolchain_type"))]
328
329    return [
330        toolchain,
331        toolchain.make_variables,
332        DefaultInfo(
333            files = depset([
334                toolchain.rustfmt,
335            ]),
336            runfiles = ctx.runfiles(transitive_files = toolchain.all_files),
337        ),
338    ]
339
340current_rustfmt_toolchain = rule(
341    doc = "A rule for exposing the current registered `rustfmt_toolchain`.",
342    implementation = _current_rustfmt_toolchain_impl,
343    toolchains = [
344        str(Label("@rules_rust//rust/rustfmt:toolchain_type")),
345    ],
346)