Skip to content

Commit 6ab46bb

Browse files
committed
ci: Use some tricks to format macro bodies
We have a lot of syntax contained within macro bodies, which `rustfmt` doesn't touch. Add a hack that replaces relevant macro invocations with functions, formats, then resets.
1 parent 64ed860 commit 6ab46bb

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

ci/style.sh

+47-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,53 @@ rustc ci/style.rs && ./style src
1313

1414
command -v rustfmt
1515
rustfmt -V
16-
cargo fmt --all -- ${check:+"$check"}
16+
17+
# Save a list of all source files
18+
tmpfile="file-list~" # trailing tilde for gitignore
19+
find src -name '*.rs' > "$tmpfile"
20+
21+
# Before formatting, replace all macro identifiers with a function signature.
22+
# This allows `rustfmt` to format it.
23+
while IFS= read -r file; do
24+
if [ "$file" = "src/macros.rs" ]; then
25+
# Too much special syntax in `macros.rs` that we don't want to format
26+
continue
27+
fi
28+
29+
# Turn all braced macro `foo! { /* ... */ }` invocations into
30+
# `fn foo_fmt_tmp() { /* ... */ }`.
31+
perl -pi -e 's/(?!macro_rules)\b(\w+)!\s*\{/fn $1_fmt_tmp() {/g' "$file"
32+
33+
# Replace `if #[cfg(...)]` within `cfg_if` with `if cfg_tmp!([...])` which
34+
# `rustfmt` will format. We put brackets within the parens so it is easy to
35+
# match (trying to match parentheses would catch the first closing `)` which
36+
# wouldn't be correct for something like `all(any(...), ...)`).
37+
perl -pi -0777 -e 's/if #\[cfg\((.*?)\)\]/if cfg_tmp!([$1])/gms' "$file"
38+
39+
# We have some instances of `{const}` that make macros happy but aren't
40+
# valid syntax. Replace this with just the keyword, plus an indicator
41+
# comment on the preceding line (which is where rustfmt puts it. Also
42+
# rust-lang/rustfmt#5464).
43+
perl -pi -e 's/^(\s*)(.*)\{const\}/$1\/\* FMT-CONST \*\/\n$1$2const/g' "$file"
44+
45+
# Format the file. We need to invoke `rustfmt` directly since `cargo fmt`
46+
# can't figure out the module tree with the hacks in place.
47+
failed=false
48+
rustfmt --config-path rustfmt.toml "$file" ${check:+"$check"} || failed=true
49+
50+
# Restore all changes to the files.
51+
perl -pi -e 's/fn (\w+)_fmt_tmp\(\)/$1!/g' "$file"
52+
perl -pi -0777 -e 's/cfg_tmp!\(\[(.*?)\]\)/#[cfg($1)]/gms' "$file"
53+
perl -pi -0777 -e 's/\/\* FMT-CONST \*\/(?:\n\s*)?(.*?)const/$1\{const\}/gms' "$file"
54+
55+
# Defer emitting the failure until after the files get reset
56+
if [ "$failed" != "false" ]; then
57+
echo "Formatting failed"
58+
exit 1
59+
fi
60+
done < "$tmpfile"
61+
62+
rm "$tmpfile"
1763

1864
if shellcheck --version ; then
1965
find . -name '*.sh' -print0 | xargs -0 shellcheck

rustfmt.toml

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
error_on_line_overflow = true
2+
edition = "2021"

0 commit comments

Comments
 (0)