forked from bazelbuild/rules_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunpretty.bzl
More file actions
359 lines (305 loc) · 10.2 KB
/
unpretty.bzl
File metadata and controls
359 lines (305 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""A module defining Rust 'unpretty' rules"""
load("//rust/private:common.bzl", "rust_common")
load(
"//rust/private:rust.bzl",
"RUSTC_ATTRS",
"get_rust_test_flags",
)
load(
"//rust/private:rustc.bzl",
"collect_deps",
"collect_inputs",
"construct_arguments",
)
load(
"//rust/private:utils.bzl",
"determine_output_hash",
"find_cc_toolchain",
"find_toolchain",
)
# This list is determined by running the following command:
#
# rustc +nightly -Zunpretty=
#
UNPRETTY_MODES = [
"ast-tree,expanded",
"ast-tree",
"expanded,hygiene",
"expanded,identified",
"expanded",
"hir-tree",
"hir,identified",
"hir,typed",
"hir",
"identified",
"mir-cfg",
"mir",
"normal",
]
RustUnprettyInfo = provider(
doc = "A provider describing the Rust unpretty mode.",
fields = {
"modes": "Depset[string]: Can be any of {}".format(["'{}'".format(m) for m in UNPRETTY_MODES]),
},
)
def _rust_unpretty_flag_impl(ctx):
value = ctx.build_setting_value
invalid = []
for mode in value:
if mode not in UNPRETTY_MODES:
invalid.append(mode)
if invalid:
fail("{} build setting allowed to take values [{}] but was set to unallowed values: {}".format(
ctx.label,
", ".join(["'{}'".format(m) for m in UNPRETTY_MODES]),
invalid,
))
return RustUnprettyInfo(modes = depset(value))
rust_unpretty_flag = rule(
doc = "A build setting which represents the Rust unpretty mode. The allowed values are {}".format(UNPRETTY_MODES),
implementation = _rust_unpretty_flag_impl,
build_setting = config.string_list(
flag = True,
repeatable = True,
),
)
def _nightly_unpretty_transition_impl(settings, attr):
mode = settings[str(Label("//rust/settings:unpretty"))]
# Use the presence of _unpretty_modes as a proxy for whether this is a rust_unpretty target.
if hasattr(attr, "_unpretty_modes") and hasattr(attr, "mode"):
mode = mode + [attr.mode]
return {
str(Label("//rust/settings:unpretty")): depset(mode).to_list(),
str(Label("//rust/toolchain/channel")): "nightly",
}
nightly_unpretty_transition = transition(
implementation = _nightly_unpretty_transition_impl,
inputs = [str(Label("//rust/settings:unpretty"))],
outputs = [
str(Label("//rust/settings:unpretty")),
str(Label("//rust/toolchain/channel")),
],
)
def _get_unpretty_ready_crate_info(target, aspect_ctx):
"""Check that a target is suitable for expansion and extract the `CrateInfo` provider from it.
Args:
target (Target): The target the aspect is running on.
aspect_ctx (ctx, optional): The aspect's context object.
Returns:
CrateInfo, optional: A `CrateInfo` provider if rust unpretty should be run or `None`.
"""
# Ignore external targets
if target.label.workspace_root.startswith("external"):
return None
# Targets with specific tags will not be formatted
if aspect_ctx:
ignore_tags = [
"nounpretty",
"no-unpretty",
"no_unpretty",
]
for tag in ignore_tags:
if tag in aspect_ctx.rule.attr.tags:
return None
if rust_common.crate_info in target:
return target[rust_common.crate_info]
if rust_common.test_crate_info in target:
return target[rust_common.test_crate_info].crate
# Obviously ignore any targets that don't contain `CrateInfo`
return None
def _rust_unpretty_aspect_impl(target, ctx):
crate_info = _get_unpretty_ready_crate_info(target, ctx)
if not crate_info:
return []
# Avoid duplicate actions.
if OutputGroupInfo in target:
if hasattr(target[OutputGroupInfo], "rust_unpretty"):
return []
toolchain = find_toolchain(ctx)
cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
dep_info, build_info, _ = collect_deps(
deps = crate_info.deps.to_list(),
proc_macro_deps = crate_info.proc_macro_deps.to_list(),
aliases = crate_info.aliases,
)
lint_files = []
compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
ctx,
ctx.rule.file,
ctx.rule.files,
# Rust expand doesn't need to invoke transitive linking, therefore doesn't need linkstamps.
depset([]),
toolchain,
cc_toolchain,
feature_configuration,
crate_info,
dep_info,
build_info,
lint_files,
)
output_groups = {}
outputs = []
for mode in ctx.attr._unpretty_modes[RustUnprettyInfo].modes.to_list():
pretty_mode = mode.replace("-", "_")
mnemonic = "RustUnpretty{}".format("".join([
o.title()
for m in pretty_mode.split(",")
for o in m.split("_")
]))
unpretty_out = ctx.actions.declare_file(
"{}.unpretty.{}.rs".format(ctx.label.name, pretty_mode.replace(",", ".")),
sibling = crate_info.output,
)
output_groups.update({"rust_unpretty_{}".format(pretty_mode.replace(",", "_")): depset([unpretty_out])})
outputs.append(unpretty_out)
rust_flags = []
if crate_info.is_test:
rust_flags = get_rust_test_flags(ctx.rule.attr)
args, env = construct_arguments(
ctx = ctx,
attr = ctx.rule.attr,
file = ctx.file,
toolchain = toolchain,
tool_path = toolchain.rustc.path,
cc_toolchain = cc_toolchain,
feature_configuration = feature_configuration,
crate_info = crate_info,
dep_info = dep_info,
linkstamp_outs = linkstamp_outs,
ambiguous_libs = ambiguous_libs,
output_hash = determine_output_hash(crate_info.root, ctx.label),
rust_flags = rust_flags,
out_dir = out_dir,
build_env_files = build_env_files,
build_flags_files = build_flags_files,
emit = ["dep-info", "metadata"],
skip_expanding_rustc_env = True,
)
args.process_wrapper_flags.add("--stdout-file", unpretty_out)
# Expand all macros and dump the source to stdout.
# Tracking issue: https://github.com/rust-lang/rust/issues/43364
args.rustc_flags.add("-Zunpretty={}".format(mode))
ctx.actions.run(
executable = ctx.executable._process_wrapper,
inputs = compile_inputs,
outputs = [unpretty_out],
env = env,
arguments = args.all,
mnemonic = mnemonic,
toolchain = "@rules_rust//rust:toolchain_type",
)
output_groups.update({"rust_unpretty": depset(outputs)})
return [
OutputGroupInfo(**output_groups),
]
# Example: Expand all rust targets in the codebase.
# bazel build --aspects=@rules_rust//rust:defs.bzl%rust_unpretty_aspect \
# --output_groups=expanded \
# //...
rust_unpretty_aspect = aspect(
implementation = _rust_unpretty_aspect_impl,
fragments = ["cpp"],
attrs = {
"_unpretty_modes": attr.label(
doc = "The values to pass to `--unpretty`",
providers = [RustUnprettyInfo],
default = Label("//rust/settings:unpretty"),
),
} | RUSTC_ATTRS,
toolchains = [
str(Label("//rust:toolchain_type")),
"@bazel_tools//tools/cpp:toolchain_type",
],
required_providers = [
[rust_common.crate_info],
[rust_common.test_crate_info],
],
doc = """\
Executes Rust expand on specified targets.
This aspect applies to existing rust_library, rust_test, and rust_binary rules.
As an example, if the following is defined in `examples/hello_lib/BUILD.bazel`:
```python
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
```
Then the targets can be expanded with the following command:
```output
$ bazel build --aspects=@rules_rust//rust:defs.bzl%rust_unpretty_aspect \\
--output_groups=rust_unpretty_expanded \\
//hello_lib:all
```
""",
)
def _rust_unpretty_rule_impl(ctx):
mode = ctx.attr.mode
output_group = "rust_unpretty_{}".format(mode.replace(",", "_").replace("-", "_"))
files = []
for target in ctx.attr.deps:
files.append(getattr(target[OutputGroupInfo], output_group))
return [DefaultInfo(files = depset(transitive = files))]
rust_unpretty = rule(
implementation = _rust_unpretty_rule_impl,
cfg = nightly_unpretty_transition,
attrs = {
"deps": attr.label_list(
doc = "Rust targets to run unpretty on.",
providers = [
[rust_common.crate_info],
[rust_common.test_crate_info],
],
aspects = [rust_unpretty_aspect],
),
"mode": attr.string(
doc = "The value to pass to `--unpretty`",
values = UNPRETTY_MODES,
default = "expanded",
),
"_allowlist_function_transition": attr.label(
default = Label("//tools/allowlists/function_transition_allowlist"),
),
"_unpretty_modes": attr.label(
doc = "The values to pass to `--unpretty`",
providers = [RustUnprettyInfo],
default = Label("//rust/settings:unpretty"),
),
},
doc = """\
Executes rust unpretty on a specific target.
Similar to `rust_unpretty_aspect`, but allows specifying a list of dependencies \
within the build system.
For example, given the following example targets:
```python
load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
rust_library(
name = "hello_lib",
srcs = ["src/lib.rs"],
)
rust_test(
name = "greeting_test",
srcs = ["tests/greeting.rs"],
deps = [":hello_lib"],
)
```
Rust expand can be set as a build target with the following:
```python
load("@rules_rust//rust:defs.bzl", "rust_unpretty")
rust_unpretty(
name = "hello_library_expand",
testonly = True,
deps = [
":hello_lib",
":greeting_test",
],
mode = "expand",
)
```
""",
)