rust-lang / rust-lang/rustfmt

Group imports together with imports_granularity results in non-idempotent formatting

Open
#6,195 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

When group_imports = "StdExternalCrate" is combined with imports_granularity = "Module", rustfmt can format a file in a non-idempotent way, i.e. running rustfmt twice in a row results in a different formatting.

Reduced from a case in the stdlib (https://github.com/rust-lang/rust/issues/126394).

Minimal repro:

# rustfmt.toml
version = "Two"
group_imports = "StdExternalCrate"
imports_granularity = "Module"
$ rustfmt --version
rustfmt 1.7.0-nightly (72fdf91 2024-06-05)
# file.rs
use a::c;
// foo
use a::b;
use a::d;

First run (rustfmt file.rs):

// foo
use a::b;
use a::{c, d};

Second run (rustfmt file.rs):

// foo
use a::{b, c, d};

Removing the group_imports or imports_granularity options removes the issue. The problem seems to be caused by the comment, without it it works fine.

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 with the minimal rustfmt.toml and file.rs reproduction, running rustfmt twice with group_imports set to StdExternalCrate and imports_granularity set to Module. Trace the import-grouping and comment-handling entry points involved in the changed output. Done means formatting the reproduction is idempotent while preserving the reported behavior without either option.

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
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.