From b70465c93fad022209fd6c9ef298149570405e1f Mon Sep 17 00:00:00 2001 From: Wafarm Date: Thu, 15 Aug 2024 23:13:50 +0800 Subject: [PATCH] Fix list use formatting --- src/imports.rs | 22 ++++++++++++++++++++-- tests/source/issue-6277/one.rs | 5 +++++ tests/source/issue-6277/two.rs | 5 +++++ tests/target/issue-6277/one.rs | 1 + tests/target/issue-6277/two.rs | 1 + 5 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 tests/source/issue-6277/one.rs create mode 100644 tests/source/issue-6277/two.rs create mode 100644 tests/target/issue-6277/one.rs create mode 100644 tests/target/issue-6277/two.rs diff --git a/src/imports.rs b/src/imports.rs index 94b62ef7aa0..6b95bbf38f6 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -627,8 +627,21 @@ impl UseTree { } // Recursively normalize elements of a list use (including sorting the list). + let mut should_renormalize = false; if let UseSegmentKind::List(list) = last.kind { - let mut list = list.into_iter().map(UseTree::normalize).collect::>(); + let original_size = list.len(); + let mut list = list + .into_iter() + .map(UseTree::normalize) + // Filter away empty elements + .filter(|elem| !elem.path.is_empty()) + .collect::>(); + + // We need to normalize again if list length is reduced to + // 0 (may remove) or 1 (may extract the element) + should_renormalize = + original_size != list.len() && (list.len() == 0 || list.len() == 1); + list.sort(); last = UseSegment { kind: UseSegmentKind::List(list), @@ -637,7 +650,12 @@ impl UseTree { } self.path.push(last); - self + + if should_renormalize { + self.normalize() + } else { + self + } } fn has_comment(&self) -> bool { diff --git a/tests/source/issue-6277/one.rs b/tests/source/issue-6277/one.rs new file mode 100644 index 00000000000..1a3046cd8f8 --- /dev/null +++ b/tests/source/issue-6277/one.rs @@ -0,0 +1,5 @@ +use core::{ + slice, + + fmt::{}, +}; diff --git a/tests/source/issue-6277/two.rs b/tests/source/issue-6277/two.rs new file mode 100644 index 00000000000..435c63fc32b --- /dev/null +++ b/tests/source/issue-6277/two.rs @@ -0,0 +1,5 @@ +use core::{ + + fmt::{Debug, Display}, + slice::{}, +}; diff --git a/tests/target/issue-6277/one.rs b/tests/target/issue-6277/one.rs new file mode 100644 index 00000000000..52596bd1de3 --- /dev/null +++ b/tests/target/issue-6277/one.rs @@ -0,0 +1 @@ +use core::slice; diff --git a/tests/target/issue-6277/two.rs b/tests/target/issue-6277/two.rs new file mode 100644 index 00000000000..076e91fc42e --- /dev/null +++ b/tests/target/issue-6277/two.rs @@ -0,0 +1 @@ +use core::fmt::{Debug, Display};