rust-lang / rust-lang/rustfmt

Deduplicate imports

Open
#5,410 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-imports P-low
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

Hello!

I searched the issues and could not find a similar issue, if there is already one on that topic I missed feel free to close this one.

I find myself solving some merge conflicts lately that happen for use statements, sometimes ending up with more than one import of the same name e.g.:

use std::vec::{Vec, Vec};

And running rustfmt on that does not deduplicate the import.

In practice the use statements causing issues are much bigger and it can be a bit of pain to deduplicate imports manually. In addition, the duplicate import prevents compilation because of the name Vec being redefined

error[E0252]: the name Vec is defined multiple times

Rust playground:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0cd8ef07ca6cde1a2892c9b8e1697ff4

It feels like it should be possible as I've already seen rustfmt merging multiple imports from the same module into one use statement, so there is a mechanism to group names together and sort them, I'm guessing that switching the underlying container for the grouped names to some Set-like object should do the trick.

I haven't had time to check the source for that particular case, but I thought I might as well open the issue here if someone knew where the code for this is and how it could be changed to manage that case 🙂

Cheers!

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 Rust Playground reproducer linked in the issue and inspect rustfmt's import-merging logic for grouped names. Trace how duplicate names are represented and add coverage for use std::vec::{Vec, Vec};; done means rustfmt removes the duplicate and the formatted code no longer triggers E0252.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.