rust-lang / rust-lang/rustfmt

`imports_granularity=Item` incorrectly removes a `#[cfg]`'d item with same target as another `#[cfg]`'d item

Open
#6,806 2 comments 0 reactions 1 assignee View on GitHub

@matthewhughes934 is already working on this.

Since Feb 25, 2026.

C-bug I-unexpectedly-removes-code UO-imports_granularity
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

Consider the following file (example.rs):

mod os {}

#[cfg(libloading_docs)]
use crate::os::unix as imp;
#[cfg(all(not(libloading_docs), unix))]   // <-- this will be removed
use crate::os::unix as imp;               // <-- and this as well
#[cfg(all(not(libloading_docs), windows))]
use crate::os::windows as imp;

pub fn use_the_imp() -> String {
    let my_instance = imp::MyStruct::new();
    my_instance.do_something().to_string()
}

Using the following rustfmt invocation:

rustfmt --config imports_granularity=Item example.rs

The final content is:

mod os {}

#[cfg(libloading_docs)]
use crate::os::unix as imp;
#[cfg(all(not(libloading_docs), windows))]
use crate::os::windows as imp;

pub fn use_the_imp() -> String {
    let my_instance = imp::MyStruct::new();
    my_instance.do_something().to_string()
}

which is not equivalent to the original one.

Rustfmt version:

❯ rustfmt --version
rustfmt 1.8.0-nightly (a1208bf765 2025-09-03)

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.