rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
5.85k stars 860 forks source link

Internal error when trying to format code with inline block comment #6200

Open Sorseg opened 1 week ago

Sorseg commented 1 week ago

When formatting this file cargo +nightly fmt does not modify the file and reports this error:

error[internal]: left behind trailing whitespace
   --> <...>/riano/src/main.rs:353:353:58
    |
353 |                                     piano.sustain = true; 
    |                                                          ^
    |

warning: rustfmt has failed to format. See previous 1 errors.
$ cargo +nightly fmt --version
rustfmt 1.7.0-nightly (59e2c01 2024-06-17)

Removing the block comment on this line allows rustfmt to format the file again.

Thank you for maintaining this! :orange_heart:

ytmimi commented 1 week ago

@Sorseg linking to the file is definitely useful. When you get a chance could you try to create a minimal test case that someone could use to reproduce the issue.

Sorseg commented 1 week ago

I was able to boil it down to this

struct S {
    f: u32,
}

fn main() {
    let s = Some(S { f: 42 });
    match s {
        Some( S{f: /* some special value */3}) => { }
        _ => {}
    }
}

cargo fmt doesn't error, just silently does nothing

Is this workable?

Thank you for taking a look

ytmimi commented 6 days ago

If you set error_on_unformatted = true you'll get some additional information about why this failed to format. The issue here is that rustfmt isn't expecting to find a comment between f: 3 in the pattern. To prevent dropping the comment rustfmt doesn't rewrite the code:

You should see an error similar to this:

error[internal]: not formatted because a comment would be lost
 --> <stdin>:7
  |
7 |     match s {
  |
  = note: set `error_on_unformatted = false` to suppress the warning against comments or string literals

warning: rustfmt has failed to format. See previous 1 errors.
ytmimi commented 6 days ago

I believe we'd need to make adjustments in the Rewrite for PatField impl to address this, though my current recommendation would be to not write comments within struct fields: https://github.com/rust-lang/rustfmt/blob/e4944185ae09c99f59b460e358909f329010ea9c/src/patterns.rs#L385-L433