rust-lang / rustfmt

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

max_width is not stable/deterministic #5743

Open matthiaskrgr opened 1 year ago

matthiaskrgr commented 1 year ago

If I have a repo that uses rustfmt defaults, (e.g. max_width=100), I can run

 cargo fmt -- --config max_width=100
 cargo fmt -- --config max_width=80
 cargo fmt -- --config max_width=100

which will not restore the code to its original formatting but leave some modifications in place. (for example seen on the cargo repo)

ytmimi commented 1 year ago

I cloned cargo and ran the commands mentioned above.

From the diff I'm seeing 2 distinct cases: 1) Some AST nodes get wrapped in braces 2) comment placement shifts

Here are some concrete examples to highlight those cases:

ytmimi commented 1 year ago

Frankly I don't think this is an issue.

For case 1) above, running rustfmt with max_width=80 subtly changed the AST in a way that rustfmt won't restore by default.

For case 2) since comments are not represented in the AST they're one of the few things rustfmt has to peek back into the source file to find. rustfmt try's not to move comments around, but in this case it did. If rustfmt finds the comment on the next line after formatting with a different max_width it won't try to re-position it on the previous line just because there might now be room.

Out of the two cases listed above I think 2) might be worth looking into in order to understand why setting max_width=80 places the comment to the next line.