Skip to content

Commit 509ac2e

Browse files
magurotunacalebcartwright
authored andcommitted
Implement One option for imports_granularity (#4669)
This option merges all imports into a single `use` statement as long as they have the same visibility.
1 parent a9876e8 commit 509ac2e

File tree

6 files changed

+288
-19
lines changed

6 files changed

+288
-19
lines changed

Configurations.md

+18-1
Original file line numberDiff line numberDiff line change
@@ -1710,7 +1710,7 @@ pub enum Foo {}
17101710
Merge together related imports based on their paths.
17111711

17121712
- **Default value**: `Preserve`
1713-
- **Possible values**: `Preserve`, `Crate`, `Module`, `Item`
1713+
- **Possible values**: `Preserve`, `Crate`, `Module`, `Item`, `One`
17141714
- **Stable**: No
17151715

17161716
#### `Preserve` (default):
@@ -1764,6 +1764,23 @@ use qux::h;
17641764
use qux::i;
17651765
```
17661766

1767+
#### `One`:
1768+
1769+
Merge all imports into a single `use` statement as long as they have the same visibility.
1770+
1771+
```rust
1772+
pub use foo::{x, y};
1773+
use {
1774+
bar::{
1775+
a,
1776+
b::{self, f, g},
1777+
c,
1778+
d::e,
1779+
},
1780+
qux::{h, i},
1781+
};
1782+
```
1783+
17671784
## `merge_imports`
17681785

17691786
This option is deprecated. Use `imports_granularity = "Crate"` instead.

src/config/options.rs

+2
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ pub enum ImportGranularity {
130130
Module,
131131
/// Use one `use` statement per imported item.
132132
Item,
133+
/// Use one `use` statement including all items.
134+
One,
133135
}
134136

135137
#[config_type]

src/formatting/imports.rs

+128-18
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,29 @@ impl UseSegment {
143143
}
144144
}
145145

146+
// Check if self == other with their aliases removed.
147+
fn equal_except_alias(&self, other: &Self) -> bool {
148+
match (self, other) {
149+
(UseSegment::Ident(ref s1, _), UseSegment::Ident(ref s2, _)) => s1 == s2,
150+
(UseSegment::Slf(_), UseSegment::Slf(_))
151+
| (UseSegment::Super(_), UseSegment::Super(_))
152+
| (UseSegment::Crate(_), UseSegment::Crate(_))
153+
| (UseSegment::Glob, UseSegment::Glob) => true,
154+
(UseSegment::List(ref list1), UseSegment::List(ref list2)) => list1 == list2,
155+
_ => false,
156+
}
157+
}
158+
159+
fn get_alias(&self) -> Option<&str> {
160+
match self {
161+
UseSegment::Ident(_, a)
162+
| UseSegment::Slf(a)
163+
| UseSegment::Super(a)
164+
| UseSegment::Crate(a) => a.as_deref(),
165+
_ => None,
166+
}
167+
}
168+
146169
fn from_path_segment(
147170
context: &RewriteContext<'_>,
148171
path_seg: &ast::PathSegment,
@@ -579,6 +602,7 @@ impl UseTree {
579602
SharedPrefix::Module => {
580603
self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
581604
}
605+
SharedPrefix::One => true,
582606
}
583607
}
584608
}
@@ -616,7 +640,7 @@ impl UseTree {
616640
fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
617641
let mut prefix = 0;
618642
for (a, b) in self.path.iter().zip(other.path.iter()) {
619-
if *a == *b {
643+
if a.equal_except_alias(b) {
620644
prefix += 1;
621645
} else {
622646
break;
@@ -651,14 +675,20 @@ fn merge_rest(
651675
return Some(new_path);
652676
}
653677
} else if len == 1 {
654-
let rest = if a.len() == len { &b[1..] } else { &a[1..] };
655-
return Some(vec![
656-
b[0].clone(),
657-
UseSegment::List(vec![
658-
UseTree::from_path(vec![UseSegment::Slf(None)], DUMMY_SP),
659-
UseTree::from_path(rest.to_vec(), DUMMY_SP),
660-
]),
661-
]);
678+
let (common, rest) = if a.len() == len {
679+
(&a[0], &b[1..])
680+
} else {
681+
(&b[0], &a[1..])
682+
};
683+
let mut list = vec![UseTree::from_path(
684+
vec![UseSegment::Slf(common.get_alias().map(ToString::to_string))],
685+
DUMMY_SP,
686+
)];
687+
match rest {
688+
[UseSegment::List(rest_list)] => list.extend(rest_list.clone()),
689+
_ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)),
690+
}
691+
return Some(vec![b[0].clone(), UseSegment::List(list)]);
662692
} else {
663693
len -= 1;
664694
}
@@ -673,18 +703,54 @@ fn merge_rest(
673703
}
674704

675705
fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
676-
let similar_trees = trees
677-
.iter_mut()
678-
.filter(|tree| tree.share_prefix(&use_tree, merge_by));
706+
struct SimilarTree<'a> {
707+
similarity: usize,
708+
path_len: usize,
709+
tree: &'a mut UseTree,
710+
}
711+
712+
let similar_trees = trees.iter_mut().filter_map(|tree| {
713+
if tree.share_prefix(&use_tree, merge_by) {
714+
// In the case of `SharedPrefix::One`, `similarity` is used for deciding with which
715+
// tree `use_tree` should be merge.
716+
// In other cases `similarity` won't be used, so set it to `0` as a dummy value.
717+
let similarity = if merge_by == SharedPrefix::One {
718+
tree.path
719+
.iter()
720+
.zip(&use_tree.path)
721+
.take_while(|(a, b)| a.equal_except_alias(b))
722+
.count()
723+
} else {
724+
0
725+
};
726+
727+
let path_len = tree.path.len();
728+
Some(SimilarTree {
729+
similarity,
730+
tree,
731+
path_len,
732+
})
733+
} else {
734+
None
735+
}
736+
});
737+
679738
if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
680-
if let Some(tree) = similar_trees.min_by_key(|tree| tree.path.len()) {
681-
if tree.path.len() == 1 {
739+
if let Some(tree) = similar_trees.min_by_key(|tree| tree.path_len) {
740+
if tree.path_len == 1 {
741+
return;
742+
}
743+
}
744+
} else if merge_by == SharedPrefix::One {
745+
if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.similarity) {
746+
if sim_tree.similarity > 0 {
747+
sim_tree.tree.merge(&use_tree, merge_by);
682748
return;
683749
}
684750
}
685-
} else if let Some(tree) = similar_trees.max_by_key(|tree| tree.path.len()) {
686-
if tree.path.len() > 1 {
687-
tree.merge(&use_tree, merge_by);
751+
} else if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.path_len) {
752+
if sim_tree.path_len > 1 {
753+
sim_tree.tree.merge(&use_tree, merge_by);
688754
return;
689755
}
690756
}
@@ -897,6 +963,7 @@ impl Rewrite for UseTree {
897963
pub(crate) enum SharedPrefix {
898964
Crate,
899965
Module,
966+
One,
900967
}
901968

902969
#[cfg(test)]
@@ -921,7 +988,7 @@ mod test {
921988
}
922989

923990
fn eat(&mut self, c: char) {
924-
assert!(self.input.next().unwrap() == c);
991+
assert_eq!(self.input.next().unwrap(), c);
925992
}
926993

927994
fn push_segment(
@@ -1111,6 +1178,49 @@ mod test {
11111178
);
11121179
}
11131180

1181+
#[test]
1182+
fn test_use_tree_merge_one() {
1183+
test_merge!(One, ["a", "b"], ["{a, b}"]);
1184+
1185+
test_merge!(One, ["a::{aa, ab}", "b", "a"], ["{a::{self, aa, ab}, b}"]);
1186+
1187+
test_merge!(One, ["a as x", "b as y"], ["{a as x, b as y}"]);
1188+
1189+
test_merge!(
1190+
One,
1191+
["a::{aa as xa, ab}", "b", "a"],
1192+
["{a::{self, aa as xa, ab}, b}"]
1193+
);
1194+
1195+
test_merge!(
1196+
One,
1197+
["a", "a::{aa, ab::{aba, abb}}"],
1198+
["a::{self, aa, ab::{aba, abb}}"]
1199+
);
1200+
1201+
test_merge!(One, ["a", "b::{ba, *}"], ["{a, b::{ba, *}}"]);
1202+
1203+
test_merge!(One, ["a", "b", "a::aa"], ["{a::{self, aa}, b}"]);
1204+
1205+
test_merge!(
1206+
One,
1207+
["a::aa::aaa", "a::ac::aca", "a::aa::*"],
1208+
["a::{aa::{aaa, *}, ac::aca}"]
1209+
);
1210+
1211+
test_merge!(
1212+
One,
1213+
["a", "b::{ba, bb}", "a::{aa::*, ab::aba}"],
1214+
["{a::{self, aa::*, ab::aba}, b::{ba, bb}}"]
1215+
);
1216+
1217+
test_merge!(
1218+
One,
1219+
["b", "a::ac::{aca, acb}", "a::{aa::*, ab}"],
1220+
["{a::{aa::*, ab, ac::{aca, acb}}, b}"]
1221+
);
1222+
}
1223+
11141224
#[test]
11151225
fn test_flatten_use_trees() {
11161226
assert_eq!(

src/formatting/reorder.rs

+1
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ fn rewrite_reorderable_or_regroupable_items(
234234
merge_use_trees(normalized_items, SharedPrefix::Module)
235235
}
236236
ImportGranularity::Item => flatten_use_trees(normalized_items),
237+
ImportGranularity::One => merge_use_trees(normalized_items, SharedPrefix::One),
237238
ImportGranularity::Preserve => normalized_items,
238239
};
239240

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// rustfmt-imports_granularity: One
2+
3+
use b;
4+
use a::ac::{aca, acb};
5+
use a::{aa::*, ab};
6+
7+
use a as x;
8+
use b::ba;
9+
use a::{aa, ab};
10+
11+
use a::aa::aaa;
12+
use a::ab::aba as x;
13+
use a::aa::*;
14+
15+
use a::aa;
16+
use a::ad::ada;
17+
#[cfg(test)]
18+
use a::{ab, ac::aca};
19+
use b;
20+
#[cfg(test)]
21+
use b::{
22+
ba, bb,
23+
bc::bca::{bcaa, bcab},
24+
};
25+
26+
pub use a::aa;
27+
pub use a::ae;
28+
use a::{ab, ac, ad};
29+
use b::ba;
30+
pub use b::{bb, bc::bca};
31+
32+
use a::aa::aaa;
33+
use a::ac::{aca, acb};
34+
use a::{aa::*, ab};
35+
use b::{
36+
ba,
37+
bb::{self, bba},
38+
};
39+
40+
use crate::a;
41+
use crate::b::ba;
42+
use c::ca;
43+
44+
use super::a;
45+
use c::ca;
46+
use super::b::ba;
47+
48+
use crate::a;
49+
use super::b;
50+
use c::{self, ca};
51+
52+
use a::{
53+
// some comment
54+
aa::{aaa, aab},
55+
ab,
56+
// another comment
57+
ac::aca,
58+
};
59+
use b as x;
60+
use a::ad::ada;
+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// rustfmt-imports_granularity: One
2+
3+
use {
4+
a::{
5+
aa::*,
6+
ab,
7+
ac::{aca, acb},
8+
},
9+
b,
10+
};
11+
12+
use {
13+
a::{self as x, aa, ab},
14+
b::ba,
15+
};
16+
17+
use a::{
18+
aa::{aaa, *},
19+
ab::aba as x,
20+
};
21+
22+
#[cfg(test)]
23+
use a::{ab, ac::aca};
24+
#[cfg(test)]
25+
use b::{
26+
ba, bb,
27+
bc::bca::{bcaa, bcab},
28+
};
29+
use {
30+
a::{aa, ad::ada},
31+
b,
32+
};
33+
34+
pub use {
35+
a::{aa, ae},
36+
b::{bb, bc::bca},
37+
};
38+
use {
39+
a::{ab, ac, ad},
40+
b::ba,
41+
};
42+
43+
use {
44+
a::{
45+
aa::{aaa, *},
46+
ab,
47+
ac::{aca, acb},
48+
},
49+
b::{
50+
ba,
51+
bb::{self, bba},
52+
},
53+
};
54+
55+
use {
56+
crate::{a, b::ba},
57+
c::ca,
58+
};
59+
60+
use {
61+
super::{a, b::ba},
62+
c::ca,
63+
};
64+
65+
use {
66+
super::b,
67+
crate::a,
68+
c::{self, ca},
69+
};
70+
71+
use {
72+
a::{
73+
aa::{aaa, aab},
74+
ab,
75+
ac::aca,
76+
ad::ada,
77+
},
78+
b as x,
79+
};

0 commit comments

Comments
 (0)