rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

Comment before semicolon prevents formatting expression

Open junbl opened this issue 2 years ago • 2 comments

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)
    ;

Playground

Occurs in rustfmt 1.5.1-nightly (b44197a 2022-09-05) and rustfmt 1.5.1-stable (4b91a6e 2022-08-08).

junbl avatar Sep 06 '22 15:09 junbl

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)

ytmimi avatar Sep 07 '22 00:09 ytmimi

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)
    ;

junbl avatar Sep 09 '22 22:09 junbl