rustfmt
rustfmt copied to clipboard
Comment before semicolon prevents formatting expression
This code:
let unformatted = { 1}
// comment
;
or this:
let unformatted = { 1} // comment
;
will pass through rustfmt unchanged. Removing the comment causes the code to be formatted correctly, and other expressions are not affected.
You may be asking "why would anybody want to do this?" I keep a semicolon on its own line in a long chain of builder methods that I frequently have to modify, e.g.
builder
.configure(cfg_fn1)
.configure(cfg_fn2)
// .configure(cfg_fn3)
;
Occurs in rustfmt 1.5.1-nightly (b44197a 2022-09-05)
and rustfmt 1.5.1-stable (4b91a6e 2022-08-08)
.
If you run rustfmt --config=error_on_unformatted=true
with the following input:
fn main() {
let unformatted = { 1}
// comment
;
builder
.configure(cfg_fn1)
.configure(cfg_fn2)
// .configure(cfg_fn3)
;
}
You'll see that rustfmt isn't formatting the code because the comment would be lost:
error[internal]: not formatted because a comment would be lost
--> <stdin>:2
|
2 | let unformatted = { 1}
|
= note: set `error_on_unformatted = false` to suppress the warning against comments or string literals
error[internal]: not formatted because a comment would be lost
--> <stdin>:6
|
6 | builder
|
= note: set `error_on_unformatted = false` to suppress the warning against comments or string literals
warning: rustfmt has failed to format. See previous 2 errors.
using rustfmt 1.5.1-stable (4b91a6ea 2022-08-08)
If you run rustfmt --config=error_on_unformatted=true with the following input:
That's good to know about, thanks!
To be clear, I wouldn't expect it to move the comment or the semicolon. Maybe it's impossible with how rustfmt works, but I was expecting it to format the other expressions inside and leave that part alone. For example, the first example could become
let unformatted = { 1 }
// comment
;
or, I guess
let unformatted = { 1 }; // comment
but
builder
.configure(|x| {
unformatted. method (x)
})
// .configure(cfg_fn3)
;
becomes
builder
.configure(|x| { unformatted.method(x) })
// .configure(cfg_fn3)
;