Skip to content

Commit 53da92e

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 860a73b commit 53da92e

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

ci/style.sh

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,48 @@ 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+
# Suffix all braced macros except `macro_rules!` with `_fmt_tmp()`. Also
30+
# remove the bang.
31+
perl -pi -e 's/(?!macro_rules)\b(\w+)!\s*\{/fn $1_fmt_tmp() {/g' "$file"
32+
33+
# Replace `#[cfg(...)]` within `cfg_if` with `cfg_tmp!([...])` which
34+
# `rustfmt` will format. We put braces within the parens so it is easy to
35+
# match (matching 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. Replace this
40+
# with just the keyword, plus an indicator comment at the start of the line
41+
# (at the start because of rust-lang/rustfmt#5464).
42+
perl -pi -e 's/^(\s*)(.*)\{const\}/$1\/\* FMT-CONST \*\/$2const/g' "$file"
43+
44+
# We need to invoke `rustfmt` directly since `cargo fmt` can't figure out
45+
# the module tree with the hacks in place.
46+
rustfmt --config-path rustfmt.toml "$file" ${check:+"$check"}
47+
48+
# Reset everything
49+
perl -pi -e 's/fn (\w+)_fmt_tmp\(\)/$1!/g' "$file"
50+
perl -pi -0777 -e 's/cfg_tmp!\(\[(.*?)\]\)/#[cfg($1)]/gms' "$file"
51+
52+
# Rustfmt sometimes puts our `/* FMT-CONST */` comment on the preceding line
53+
# so we need to do a multiline match.
54+
perl -pi -0777 -e 's/\/\* FMT-CONST \*\/(?:\n\s*)?(.*?)const/$1{const}/gms' "$file"
55+
done < "$tmpfile"
56+
57+
rm "$tmpfile"
1758

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

rustfmt.toml

Lines changed: 1 addition & 0 deletions
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)