-
Notifications
You must be signed in to change notification settings - Fork 898
/
imports.rs
1506 lines (1387 loc) · 50.2 KB
/
imports.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
use core::hash::{Hash, Hasher};
use itertools::Itertools;
use rustc_ast::ast::{self, UseTreeKind};
use rustc_span::{
symbol::{self, sym},
BytePos, Span, DUMMY_SP,
};
use crate::comment::combine_strs_with_missing_comments;
use crate::config::lists::*;
use crate::config::ImportGranularity;
use crate::config::{Edition, IndentStyle, Version};
use crate::lists::{
definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
};
use crate::rewrite::{Rewrite, RewriteContext};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::spanned::Spanned;
use crate::utils::{is_same_visibility, mk_sp, rewrite_ident};
use crate::visitor::FmtVisitor;
/// Returns a name imported by a `use` declaration.
/// E.g., returns `Ordering` for `std::cmp::Ordering` and `self` for `std::cmp::self`.
pub(crate) fn path_to_imported_ident(path: &ast::Path) -> symbol::Ident {
path.segments.last().unwrap().ident
}
impl<'a> FmtVisitor<'a> {
pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
let span = item.span();
let shape = self.shape();
let rw = UseTree::from_ast(
&self.get_context(),
tree,
None,
Some(item.vis.clone()),
Some(item.span.lo()),
Some(item.attrs.clone()),
)
.rewrite_top_level(&self.get_context(), shape);
match rw {
Some(ref s) if s.is_empty() => {
// Format up to last newline
let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
let trimmed_snippet = self.snippet(prev_span).trim_end();
let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
self.format_missing(span_end);
// We have an excessive newline from the removed import.
if self.buffer.ends_with('\n') {
self.buffer.pop();
self.line_number -= 1;
}
self.last_pos = source!(self, span).hi();
}
Some(ref s) => {
self.format_missing_with_indent(source!(self, span).lo());
self.push_str(s);
self.last_pos = source!(self, span).hi();
}
None => {
self.format_missing_with_indent(source!(self, span).lo());
self.format_missing(source!(self, span).hi());
}
}
}
}
// Ordering of imports
// We order imports by translating to our own representation and then sorting.
// The Rust AST data structures are really bad for this. Rustfmt applies a bunch
// of normalisations to imports and since we want to sort based on the result
// of these (and to maintain idempotence) we must apply the same normalisations
// to the data structures for sorting.
//
// We sort `self` and `super` before other imports, then identifier imports,
// then glob imports, then lists of imports. We do not take aliases into account
// when ordering unless the imports are identical except for the alias (rare in
// practice).
// FIXME(#2531): we should unify the comparison code here with the formatting
// code elsewhere since we are essentially string-ifying twice. Furthermore, by
// parsing to our own format on comparison, we repeat a lot of work when
// sorting.
// FIXME we do a lot of allocation to make our own representation.
#[derive(Clone, Eq, Hash, PartialEq)]
pub(crate) enum UseSegmentKind {
Ident(String, Option<String>),
Slf(Option<String>),
Super(Option<String>),
Crate(Option<String>),
Glob,
List(Vec<UseTree>),
}
#[derive(Clone, Eq, PartialEq)]
pub(crate) struct UseSegment {
pub(crate) kind: UseSegmentKind,
pub(crate) version: Version,
}
#[derive(Clone)]
pub(crate) struct UseTree {
pub(crate) path: Vec<UseSegment>,
pub(crate) span: Span,
// Comment information within nested use tree.
pub(crate) list_item: Option<ListItem>,
// Additional fields for top level use items.
// Should we have another struct for top-level use items rather than reusing this?
visibility: Option<ast::Visibility>,
attrs: Option<ast::AttrVec>,
}
impl PartialEq for UseTree {
fn eq(&self, other: &UseTree) -> bool {
self.path == other.path
}
}
impl Eq for UseTree {}
impl Spanned for UseTree {
fn span(&self) -> Span {
let lo = if let Some(ref attrs) = self.attrs {
attrs.iter().next().map_or(self.span.lo(), |a| a.span.lo())
} else {
self.span.lo()
};
mk_sp(lo, self.span.hi())
}
}
impl UseSegment {
// Clone a version of self with any top-level alias removed.
fn remove_alias(&self) -> UseSegment {
let kind = match self.kind {
UseSegmentKind::Ident(ref s, _) => UseSegmentKind::Ident(s.clone(), None),
UseSegmentKind::Slf(_) => UseSegmentKind::Slf(None),
UseSegmentKind::Super(_) => UseSegmentKind::Super(None),
UseSegmentKind::Crate(_) => UseSegmentKind::Crate(None),
_ => return self.clone(),
};
UseSegment {
kind,
version: self.version,
}
}
// Check if self == other with their aliases removed.
fn equal_except_alias(&self, other: &Self) -> bool {
match (&self.kind, &other.kind) {
(UseSegmentKind::Ident(ref s1, _), UseSegmentKind::Ident(ref s2, _)) => s1 == s2,
(UseSegmentKind::Slf(_), UseSegmentKind::Slf(_))
| (UseSegmentKind::Super(_), UseSegmentKind::Super(_))
| (UseSegmentKind::Crate(_), UseSegmentKind::Crate(_))
| (UseSegmentKind::Glob, UseSegmentKind::Glob) => true,
(UseSegmentKind::List(ref list1), UseSegmentKind::List(ref list2)) => list1 == list2,
_ => false,
}
}
fn get_alias(&self) -> Option<&str> {
match &self.kind {
UseSegmentKind::Ident(_, a)
| UseSegmentKind::Slf(a)
| UseSegmentKind::Super(a)
| UseSegmentKind::Crate(a) => a.as_deref(),
_ => None,
}
}
fn from_path_segment(
context: &RewriteContext<'_>,
path_seg: &ast::PathSegment,
modsep: bool,
) -> Option<UseSegment> {
let name = rewrite_ident(context, path_seg.ident);
if name.is_empty() || name == "{{root}}" {
return None;
}
let kind = match name {
"self" => UseSegmentKind::Slf(None),
"super" => UseSegmentKind::Super(None),
"crate" => UseSegmentKind::Crate(None),
_ => {
let mod_sep = if modsep { "::" } else { "" };
UseSegmentKind::Ident(format!("{mod_sep}{name}"), None)
}
};
Some(UseSegment {
kind,
version: context.config.version(),
})
}
fn contains_comment(&self) -> bool {
if let UseSegmentKind::List(list) = &self.kind {
list.iter().any(|subtree| subtree.contains_comment())
} else {
false
}
}
}
pub(crate) fn normalize_use_trees_with_granularity(
use_trees: Vec<UseTree>,
import_granularity: ImportGranularity,
) -> Vec<UseTree> {
let merge_by = match import_granularity {
ImportGranularity::Item => return flatten_use_trees(use_trees, ImportGranularity::Item),
ImportGranularity::Preserve => return use_trees,
ImportGranularity::Crate => SharedPrefix::Crate,
ImportGranularity::Module => SharedPrefix::Module,
ImportGranularity::One => SharedPrefix::One,
};
let mut result = Vec::with_capacity(use_trees.len());
for use_tree in use_trees {
if use_tree.contains_comment() || use_tree.attrs.is_some() {
result.push(use_tree);
continue;
}
for mut flattened in use_tree.flatten(import_granularity) {
if let Some(tree) = result
.iter_mut()
.find(|tree| tree.share_prefix(&flattened, merge_by))
{
tree.merge(&flattened, merge_by);
} else {
// If this is the first tree with this prefix, handle potential trailing ::self
if merge_by == SharedPrefix::Module {
flattened = flattened.nest_trailing_self();
}
result.push(flattened);
}
}
}
result
}
fn flatten_use_trees(
use_trees: Vec<UseTree>,
import_granularity: ImportGranularity,
) -> Vec<UseTree> {
// Return non-sorted single occurrence of the use-trees text string;
// order is by first occurrence of the use-tree.
use_trees
.into_iter()
.flat_map(|tree| tree.flatten(import_granularity))
.map(UseTree::nest_trailing_self)
.unique()
.collect()
}
impl fmt::Debug for UseTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Debug for UseSegment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.kind, f)
}
}
impl fmt::Display for UseSegment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.kind, f)
}
}
impl Hash for UseSegment {
fn hash<H: Hasher>(&self, state: &mut H) {
self.kind.hash(state);
}
}
impl fmt::Debug for UseSegmentKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for UseSegmentKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
UseSegmentKind::Glob => write!(f, "*"),
UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{s} as {alias}"),
UseSegmentKind::Ident(ref s, None) => write!(f, "{s}"),
UseSegmentKind::Slf(..) => write!(f, "self"),
UseSegmentKind::Super(..) => write!(f, "super"),
UseSegmentKind::Crate(..) => write!(f, "crate"),
UseSegmentKind::List(ref list) => {
write!(f, "{{")?;
for (i, item) in list.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{item}")?;
}
write!(f, "}}")
}
}
}
}
impl fmt::Display for UseTree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, segment) in self.path.iter().enumerate() {
if i != 0 {
write!(f, "::")?;
}
write!(f, "{segment}")?;
}
Ok(())
}
}
impl UseTree {
// Rewrite use tree with `use ` and a trailing `;`.
pub(crate) fn rewrite_top_level(
&self,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
crate::utils::format_visibility(context, vis)
});
let use_str = self
.rewrite(context, shape.offset_left(vis.len())?)
.map(|s| {
if s.is_empty() {
s
} else {
format!("{}use {};", vis, s)
}
})?;
match self.attrs {
Some(ref attrs) if !attrs.is_empty() => {
let attr_str = attrs.rewrite(context, shape)?;
let lo = attrs.last().as_ref()?.span.hi();
let hi = self.span.lo();
let span = mk_sp(lo, hi);
let allow_extend = if attrs.len() == 1 {
let line_len = attr_str.len() + 1 + use_str.len();
!attrs.first().unwrap().is_doc_comment()
&& context.config.inline_attribute_width() >= line_len
} else {
false
};
combine_strs_with_missing_comments(
context,
&attr_str,
&use_str,
span,
shape,
allow_extend,
)
}
_ => Some(use_str),
}
}
// FIXME: Use correct span?
// The given span is essentially incorrect, since we are reconstructing
// use-statements. This should not be a problem, though, since we have
// already tried to extract comment and observed that there are no comment
// around the given use item, and the span will not be used afterward.
fn from_path(path: Vec<UseSegment>, span: Span) -> UseTree {
UseTree {
path,
span,
list_item: None,
visibility: None,
attrs: None,
}
}
pub(crate) fn from_ast_with_normalization(
context: &RewriteContext<'_>,
item: &ast::Item,
) -> Option<UseTree> {
match item.kind {
ast::ItemKind::Use(ref use_tree) => Some(
UseTree::from_ast(
context,
use_tree,
None,
Some(item.vis.clone()),
Some(item.span.lo()),
if item.attrs.is_empty() {
None
} else {
Some(item.attrs.clone())
},
)
.normalize(),
),
_ => None,
}
}
fn from_ast(
context: &RewriteContext<'_>,
a: &ast::UseTree,
list_item: Option<ListItem>,
visibility: Option<ast::Visibility>,
opt_lo: Option<BytePos>,
attrs: Option<ast::AttrVec>,
) -> UseTree {
let span = if let Some(lo) = opt_lo {
mk_sp(lo, a.span.hi())
} else {
a.span
};
let mut result = UseTree {
path: vec![],
span,
list_item,
visibility,
attrs,
};
let leading_modsep =
context.config.edition() >= Edition::Edition2018 && a.prefix.is_global();
let mut modsep = leading_modsep;
for p in &a.prefix.segments {
if let Some(use_segment) = UseSegment::from_path_segment(context, p, modsep) {
result.path.push(use_segment);
modsep = false;
}
}
let version = context.config.version();
match a.kind {
UseTreeKind::Glob => {
// in case of a global path and the glob starts at the root, e.g., "::*"
if a.prefix.segments.len() == 1 && leading_modsep {
let kind = UseSegmentKind::Ident("".to_owned(), None);
result.path.push(UseSegment { kind, version });
}
result.path.push(UseSegment {
kind: UseSegmentKind::Glob,
version,
});
}
UseTreeKind::Nested(ref list) => {
// Extract comments between nested use items.
// This needs to be done before sorting use items.
let items = itemize_list(
context.snippet_provider,
list.iter().map(|(tree, _)| tree),
"}",
",",
|tree| tree.span.lo(),
|tree| tree.span.hi(),
|_| Some("".to_owned()), // We only need comments for now.
context.snippet_provider.span_after(a.span, "{"),
a.span.hi(),
false,
);
// in case of a global path and the nested list starts at the root,
// e.g., "::{foo, bar}"
if a.prefix.segments.len() == 1 && leading_modsep {
let kind = UseSegmentKind::Ident("".to_owned(), None);
result.path.push(UseSegment { kind, version });
}
let kind = UseSegmentKind::List(
list.iter()
.zip(items)
.map(|(t, list_item)| {
Self::from_ast(context, &t.0, Some(list_item), None, None, None)
})
.collect(),
);
result.path.push(UseSegment { kind, version });
}
UseTreeKind::Simple(ref rename) => {
// If the path has leading double colons and is composed of only 2 segments, then we
// bypass the call to path_to_imported_ident which would get only the ident and
// lose the path root, e.g., `that` in `::that`.
// The span of `a.prefix` contains the leading colons.
let name = if a.prefix.segments.len() == 2 && leading_modsep {
context.snippet(a.prefix.span).to_owned()
} else {
rewrite_ident(context, path_to_imported_ident(&a.prefix)).to_owned()
};
let alias = rename.and_then(|ident| {
if ident.name == sym::underscore_imports {
// for impl-only-use
Some("_".to_owned())
} else if ident == path_to_imported_ident(&a.prefix) {
None
} else {
Some(rewrite_ident(context, ident).to_owned())
}
});
let kind = match name.as_ref() {
"self" => UseSegmentKind::Slf(alias),
"super" => UseSegmentKind::Super(alias),
"crate" => UseSegmentKind::Crate(alias),
_ => UseSegmentKind::Ident(name, alias),
};
let segment = UseSegment { kind, version };
// `name` is already in result.
result.path.pop();
result.path.push(segment);
}
}
result
}
// Do the adjustments that rustfmt does elsewhere to use paths.
pub(crate) fn normalize(mut self) -> UseTree {
let mut last = self.path.pop().expect("Empty use tree?");
// Hack around borrow checker.
let mut normalize_sole_list = false;
let mut aliased_self = false;
// Remove foo::{} or self without attributes.
match last.kind {
_ if self.attrs.is_some() => (),
UseSegmentKind::List(ref list) if list.is_empty() => {
self.path = vec![];
return self;
}
UseSegmentKind::Slf(None) if self.path.is_empty() && self.visibility.is_some() => {
self.path = vec![];
return self;
}
_ => (),
}
// Normalise foo::self -> foo.
if let UseSegmentKind::Slf(None) = last.kind {
if !self.path.is_empty() {
return self;
}
}
// Normalise foo::self as bar -> foo as bar.
if let UseSegmentKind::Slf(_) = last.kind {
if let Some(UseSegment {
kind: UseSegmentKind::Ident(_, None),
..
}) = self.path.last()
{
aliased_self = true;
}
}
let mut done = false;
if aliased_self {
match self.path.last_mut() {
Some(UseSegment {
kind: UseSegmentKind::Ident(_, ref mut old_rename),
..
}) => {
assert!(old_rename.is_none());
if let UseSegmentKind::Slf(Some(rename)) = last.clone().kind {
*old_rename = Some(rename);
done = true;
}
}
_ => unreachable!(),
}
}
if done {
return self;
}
// Normalise foo::{bar} -> foo::bar
if let UseSegmentKind::List(ref list) = last.kind {
if list.len() == 1 && list[0].to_string() != "self" {
normalize_sole_list = true;
}
}
if normalize_sole_list {
match last.kind {
UseSegmentKind::List(list) => {
for seg in &list[0].path {
self.path.push(seg.clone());
}
return self.normalize();
}
_ => unreachable!(),
}
}
// Recursively normalize elements of a list use (including sorting the list).
if let UseSegmentKind::List(list) = last.kind {
let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
list.sort();
last = UseSegment {
kind: UseSegmentKind::List(list),
version: last.version,
};
}
self.path.push(last);
self
}
fn has_comment(&self) -> bool {
self.list_item.as_ref().map_or(false, ListItem::has_comment)
}
fn contains_comment(&self) -> bool {
self.has_comment() || self.path.iter().any(|path| path.contains_comment())
}
fn same_visibility(&self, other: &UseTree) -> bool {
match (&self.visibility, &other.visibility) {
(
Some(ast::Visibility {
kind: ast::VisibilityKind::Inherited,
..
}),
None,
)
| (
None,
Some(ast::Visibility {
kind: ast::VisibilityKind::Inherited,
..
}),
)
| (None, None) => true,
(Some(ref a), Some(ref b)) => is_same_visibility(a, b),
_ => false,
}
}
fn share_prefix(&self, other: &UseTree, shared_prefix: SharedPrefix) -> bool {
if self.path.is_empty()
|| other.path.is_empty()
|| self.attrs.is_some()
|| self.contains_comment()
|| !self.same_visibility(other)
{
false
} else {
match shared_prefix {
SharedPrefix::Crate => self.path[0] == other.path[0],
SharedPrefix::Module => {
self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
}
SharedPrefix::One => true,
}
}
}
fn flatten(self, import_granularity: ImportGranularity) -> Vec<UseTree> {
if self.path.is_empty() || self.contains_comment() {
return vec![self];
}
match &self.path.clone().last().unwrap().kind {
UseSegmentKind::List(list) => {
if list.len() == 1 && list[0].path.len() == 1 {
if let UseSegmentKind::Slf(..) = list[0].path[0].kind {
return vec![self];
};
}
let prefix = &self.path[..self.path.len() - 1];
let mut result = vec![];
for nested_use_tree in list {
for flattend in &mut nested_use_tree.clone().flatten(import_granularity) {
let mut new_path = prefix.to_vec();
new_path.append(&mut flattend.path);
result.push(UseTree {
path: new_path,
span: self.span,
list_item: None,
visibility: self.visibility.clone(),
// only retain attributes for `ImportGranularity::Item`
attrs: match import_granularity {
ImportGranularity::Item => self.attrs.clone(),
_ => None,
},
});
}
}
result
}
_ => vec![self],
}
}
fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
let mut prefix = 0;
for (a, b) in self.path.iter().zip(other.path.iter()) {
// only discard the alias at the root of the tree
if (prefix == 0 && a.equal_except_alias(b)) || a == b {
prefix += 1;
} else {
break;
}
}
if let Some(new_path) = merge_rest(&self.path, &other.path, prefix, merge_by) {
self.path = new_path;
self.span = self.span.to(other.span);
}
}
/// If this tree ends in `::self`, rewrite it to `::{self}`.
fn nest_trailing_self(mut self) -> UseTree {
if let Some(UseSegment {
kind: UseSegmentKind::Slf(..),
..
}) = self.path.last()
{
let self_segment = self.path.pop().unwrap();
let version = self_segment.version;
let kind = UseSegmentKind::List(vec![UseTree::from_path(vec![self_segment], DUMMY_SP)]);
self.path.push(UseSegment { kind, version });
}
self
}
}
fn merge_rest(
a: &[UseSegment],
b: &[UseSegment],
mut len: usize,
merge_by: SharedPrefix,
) -> Option<Vec<UseSegment>> {
if a.len() == len && b.len() == len {
return None;
}
if a.len() != len && b.len() != len {
let version = a[len].version;
if let UseSegmentKind::List(ref list) = a[len].kind {
let mut list = list.clone();
merge_use_trees_inner(
&mut list,
UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
merge_by,
);
let mut new_path = b[..len].to_vec();
let kind = UseSegmentKind::List(list);
new_path.push(UseSegment { kind, version });
return Some(new_path);
}
} else if len == 1 {
let (common, rest) = if a.len() == len {
(&a[0], &b[1..])
} else {
(&b[0], &a[1..])
};
let kind = UseSegmentKind::Slf(common.get_alias().map(ToString::to_string));
let version = a[0].version;
let mut list = vec![UseTree::from_path(
vec![UseSegment { kind, version }],
DUMMY_SP,
)];
match rest {
[
UseSegment {
kind: UseSegmentKind::List(rest_list),
..
},
] => list.extend(rest_list.clone()),
_ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)),
}
return Some(vec![
b[0].clone(),
UseSegment {
kind: UseSegmentKind::List(list),
version,
},
]);
} else {
len -= 1;
}
let mut list = vec![
UseTree::from_path(a[len..].to_vec(), DUMMY_SP),
UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
];
list.sort();
let mut new_path = b[..len].to_vec();
let kind = UseSegmentKind::List(list);
let version = a[0].version;
new_path.push(UseSegment { kind, version });
Some(new_path)
}
fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
struct SimilarTree<'a> {
similarity: usize,
path_len: usize,
tree: &'a mut UseTree,
}
let similar_trees = trees.iter_mut().filter_map(|tree| {
if tree.share_prefix(&use_tree, merge_by) {
// In the case of `SharedPrefix::One`, `similarity` is used for deciding with which
// tree `use_tree` should be merge.
// In other cases `similarity` won't be used, so set it to `0` as a dummy value.
let similarity = if merge_by == SharedPrefix::One {
tree.path
.iter()
.zip(&use_tree.path)
.take_while(|(a, b)| a.equal_except_alias(b))
.count()
} else {
0
};
let path_len = tree.path.len();
Some(SimilarTree {
similarity,
tree,
path_len,
})
} else {
None
}
});
if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
if let Some(tree) = similar_trees.min_by_key(|tree| tree.path_len) {
if tree.path_len == 1 {
return;
}
}
} else if merge_by == SharedPrefix::One {
if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.similarity) {
if sim_tree.similarity > 0 {
sim_tree.tree.merge(&use_tree, merge_by);
return;
}
}
} else if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.path_len) {
if sim_tree.path_len > 1 {
sim_tree.tree.merge(&use_tree, merge_by);
return;
}
}
trees.push(use_tree);
trees.sort();
}
impl Hash for UseTree {
fn hash<H: Hasher>(&self, state: &mut H) {
self.path.hash(state);
}
}
impl PartialOrd for UseSegment {
fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd for UseTree {
fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for UseSegment {
fn cmp(&self, other: &UseSegment) -> Ordering {
use self::UseSegmentKind::*;
fn is_upper_snake_case(s: &str) -> bool {
s.chars()
.all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
}
match (&self.kind, &other.kind) {
(Slf(ref a), Slf(ref b))
| (Super(ref a), Super(ref b))
| (Crate(ref a), Crate(ref b)) => match (a, b) {
(Some(sa), Some(sb)) => {
if self.version == Version::Two {
sa.trim_start_matches("r#").cmp(sb.trim_start_matches("r#"))
} else {
a.cmp(b)
}
}
(_, _) => a.cmp(b),
},
(Glob, Glob) => Ordering::Equal,
(Ident(ref pia, ref aa), Ident(ref pib, ref ab)) => {
let (ia, ib) = if self.version == Version::Two {
(pia.trim_start_matches("r#"), pib.trim_start_matches("r#"))
} else {
(pia.as_str(), pib.as_str())
};
// snake_case < CamelCase < UPPER_SNAKE_CASE
if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) {
return Ordering::Greater;
}
if ia.starts_with(char::is_lowercase) && ib.starts_with(char::is_uppercase) {
return Ordering::Less;
}
if is_upper_snake_case(ia) && !is_upper_snake_case(ib) {
return Ordering::Greater;
}
if !is_upper_snake_case(ia) && is_upper_snake_case(ib) {
return Ordering::Less;
}
let ident_ord = ia.cmp(ib);
if ident_ord != Ordering::Equal {
return ident_ord;
}
match (aa, ab) {
(None, Some(_)) => Ordering::Less,
(Some(_), None) => Ordering::Greater,
(Some(aas), Some(abs)) => {
if self.version == Version::Two {
aas.trim_start_matches("r#")
.cmp(abs.trim_start_matches("r#"))
} else {
aas.cmp(abs)
}
}
(None, None) => Ordering::Equal,
}
}
(List(ref a), List(ref b)) => {
for (a, b) in a.iter().zip(b.iter()) {
let ord = a.cmp(b);
if ord != Ordering::Equal {
return ord;
}
}
a.len().cmp(&b.len())
}
(Slf(_), _) => Ordering::Less,
(_, Slf(_)) => Ordering::Greater,
(Super(_), _) => Ordering::Less,
(_, Super(_)) => Ordering::Greater,
(Crate(_), _) => Ordering::Less,
(_, Crate(_)) => Ordering::Greater,
(Ident(..), _) => Ordering::Less,
(_, Ident(..)) => Ordering::Greater,
(Glob, _) => Ordering::Less,
(_, Glob) => Ordering::Greater,
}
}
}
impl Ord for UseTree {
fn cmp(&self, other: &UseTree) -> Ordering {
for (a, b) in self.path.iter().zip(other.path.iter()) {
let ord = a.cmp(b);
// The comparison without aliases is a hack to avoid situations like
// comparing `a::b` to `a as c` - where the latter should be ordered
// first since it is shorter.
if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
{
return ord;
}
}
self.path.len().cmp(&other.path.len())
}
}
fn rewrite_nested_use_tree(
context: &RewriteContext<'_>,
use_tree_list: &[UseTree],
shape: Shape,
) -> Option<String> {
let mut list_items = Vec::with_capacity(use_tree_list.len());
let nested_shape = match context.config.imports_indent() {
IndentStyle::Block => shape
.block_indent(context.config.tab_spaces())
.with_max_width(context.config)
.sub_width(1)?,
IndentStyle::Visual => shape.visual_indent(0),
};
for use_tree in use_tree_list {
if let Some(mut list_item) = use_tree.list_item.clone() {
list_item.item = use_tree.rewrite(context, nested_shape);
list_items.push(list_item);
} else {
list_items.push(ListItem::from_str(use_tree.rewrite(context, nested_shape)?));
}
}
let has_nested_list = use_tree_list.iter().any(|use_segment| {