]> git.lizzy.rs Git - rust.git/commitdiff
Fix import_granularity option when the use tree has an alias
authorStéphane Campinas <stephane.campinas@gmail.com>
Mon, 31 Jan 2022 22:45:30 +0000 (23:45 +0100)
committerCaleb Cartwright <calebcartwright@users.noreply.github.com>
Fri, 4 Feb 2022 00:56:53 +0000 (18:56 -0600)
src/imports.rs
tests/source/5131.rs [new file with mode: 0644]
tests/target/5131.rs [new file with mode: 0644]

index 40e0d06f99df8d14b7279dabb7bf503c747a6fcc..c60bec6d4a2014cb677fcd6f5d0c83169de3b271 100644 (file)
@@ -238,7 +238,8 @@ impl fmt::Display for UseSegment {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             UseSegment::Glob => write!(f, "*"),
-            UseSegment::Ident(ref s, _) => write!(f, "{}", s),
+            UseSegment::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias),
+            UseSegment::Ident(ref s, None) => write!(f, "{}", s),
             UseSegment::Slf(..) => write!(f, "self"),
             UseSegment::Super(..) => write!(f, "super"),
             UseSegment::Crate(..) => write!(f, "crate"),
@@ -622,7 +623,8 @@ fn flatten(self) -> Vec<UseTree> {
     fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
         let mut prefix = 0;
         for (a, b) in self.path.iter().zip(other.path.iter()) {
-            if a.equal_except_alias(b) {
+            // only discard the alias at the root of the tree
+            if (prefix == 0 && a.equal_except_alias(b)) || a == b {
                 prefix += 1;
             } else {
                 break;
diff --git a/tests/source/5131.rs b/tests/source/5131.rs
new file mode 100644 (file)
index 0000000..3e91391
--- /dev/null
@@ -0,0 +1,33 @@
+// rustfmt-imports_granularity: Module
+
+#![allow(dead_code)]
+
+mod a {
+    pub mod b {
+        pub struct Data {
+            pub a: i32,
+        }
+    }
+
+    use crate::a::b::Data;
+    use crate::a::b::Data as Data2;
+
+    pub fn data(a: i32) -> Data {
+        Data { a }
+    }
+
+    pub fn data2(a: i32) -> Data2 {
+        Data2 { a }
+    }
+
+    #[cfg(test)]
+    mod tests {
+        use super::*;
+
+        #[test]
+        pub fn test() {
+            data(1);
+            data2(1);
+        }
+    }
+}
diff --git a/tests/target/5131.rs b/tests/target/5131.rs
new file mode 100644 (file)
index 0000000..763024d
--- /dev/null
@@ -0,0 +1,32 @@
+// rustfmt-imports_granularity: Module
+
+#![allow(dead_code)]
+
+mod a {
+    pub mod b {
+        pub struct Data {
+            pub a: i32,
+        }
+    }
+
+    use crate::a::b::{Data, Data as Data2};
+
+    pub fn data(a: i32) -> Data {
+        Data { a }
+    }
+
+    pub fn data2(a: i32) -> Data2 {
+        Data2 { a }
+    }
+
+    #[cfg(test)]
+    mod tests {
+        use super::*;
+
+        #[test]
+        pub fn test() {
+            data(1);
+            data2(1);
+        }
+    }
+}