rust-lang / rust-lang/rustfmt

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

Open
#6,241 5 comments 12 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-comments A-imports C-bug I-unexpected-motion only-with-option UO-group_imports
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the provided use statements, comment, and group_imports setting such as StdExternalCrate, then compare the formatted output with the expected separate groups. Trace the formatter's import-grouping behavior and add a regression test showing that a comment between use blocks prevents them from being reordered together.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.