rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

group_imports reorders `use` statements arounds comments, changing their meaning

Open RalfJung opened this issue 1 year ago • 1 comments

This is similar to https://github.com/rust-lang/rustfmt/issues/3720, but for group_imports settings such as StdExternalCrate. https://github.com/rust-lang/rust/pull/126776 shows the consequences of that: it is now impossible to have a "chunk" of use statements that have a comment above them. rustfmt will happily reorder them and keep the comment attached to the immediate use item after it, therefore fundamentally changing its meaning. That's extremely frustrating -- having the tool make it essentially impossible to have comments that clarify the intent of my code.

In situations like this:

use a;
use b;
use c;

// comment
use d;
use e;

rustfmt should view the comment as "breaking apart" the use block into multiple blocks, similar to what it does if there was something else, like a mod, in place of the comment. group_imports should then be applied to both groups separately. That would avoid such semantics-altering reformatting.

RalfJung avatar Jul 14 '24 06:07 RalfJung

Linking the tracking issue for group_imports https://github.com/rust-lang/rustfmt/issues/5083

ytmimi avatar Jul 15 '24 14:07 ytmimi

I can think of a number of different approaches that could be taken:

  1. After a blank line and a comment, omit the following lines from grouping (and sorting?).
  2. After a blank line and a comment, treat the following lines as a new set of imports to be subdivided (again) into StdExternalCrate.
  3. Allow each of the groups (Std, External, Crate) to be further subdivided into subgroups with blank lines and comments. But assume one StdExternalCrate grouping for the module.
  4. Strictly format imports into the three groups and remove extra blank lines. Comments are always interpreted as describing a single import.

I think 2 and 3 would be too surprising in some cases. I guess I would advocate for 1 as that feels like a best attempt at a middle ground. To be honest, I also have some sympathy for 4. It kinda seems to me that automatic grouping and user grouping are incompatible and you should choose one or the other.

camsteffen avatar Oct 13 '25 23:10 camsteffen