1use std::borrow::Cow;
2use std::cmp::Ordering;
3use std::fmt;
4
5use core::hash::{Hash, Hasher};
6
7use itertools::Itertools;
8
9use rustc_ast::ast::{self, UseTreeKind};
10use rustc_span::{
11 BytePos, DUMMY_SP, Span,
12 symbol::{self, sym},
13};
14
15use crate::comment::combine_strs_with_missing_comments;
16use crate::config::ImportGranularity;
17use crate::config::lists::*;
18use crate::config::{Edition, IndentStyle, StyleEdition};
19use crate::lists::{
20 ListFormatting, ListItem, Separator, definitive_tactic, itemize_list, write_list,
21};
22use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult};
23use crate::shape::Shape;
24use crate::sort::version_sort;
25use crate::source_map::SpanUtils;
26use crate::spanned::Spanned;
27use crate::utils::{is_same_visibility, mk_sp, rewrite_ident};
28use crate::visitor::FmtVisitor;
29
30pub(crate) fn path_to_imported_ident(path: &ast::Path) -> symbol::Ident {
33 path.segments.last().unwrap().ident
34}
35
36impl<'a> FmtVisitor<'a> {
37 pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
38 let span = item.span();
39 let shape = self.shape();
40 let rw = UseTree::from_ast(
41 &self.get_context(),
42 tree,
43 None,
44 Some(item.vis.clone()),
45 Some(item.span.lo()),
46 Some(item.attrs.clone()),
47 )
48 .rewrite_top_level(&self.get_context(), shape)
49 .ok();
50 match rw {
51 Some(ref s) if s.is_empty() => {
52 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
54 let trimmed_snippet = self.snippet(prev_span).trim_end();
55 let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
56 self.format_missing(span_end);
57 if self.buffer.ends_with('\n') {
59 self.buffer.pop();
60 self.line_number -= 1;
61 }
62 self.last_pos = source!(self, span).hi();
63 }
64 Some(ref s) => {
65 self.format_missing_with_indent(source!(self, span).lo());
66 self.push_str(s);
67 self.last_pos = source!(self, span).hi();
68 }
69 None => {
70 self.format_missing_with_indent(source!(self, span).lo());
71 self.format_missing(source!(self, span).hi());
72 }
73 }
74 }
75}
76
77#[derive(Clone, Eq, Hash, PartialEq)]
97pub(crate) enum UseSegmentKind {
98 Ident(String, Option<String>),
99 Slf(Option<String>),
100 Super(Option<String>),
101 Crate(Option<String>),
102 Glob,
103 List(Vec<UseTree>),
104}
105
106#[derive(Clone, Eq, PartialEq)]
107pub(crate) struct UseSegment {
108 pub(crate) kind: UseSegmentKind,
109 pub(crate) style_edition: StyleEdition,
110}
111
112#[derive(Clone)]
113pub(crate) struct UseTree {
114 pub(crate) path: Vec<UseSegment>,
115 pub(crate) span: Span,
116 pub(crate) list_item: Option<ListItem>,
118 visibility: Option<ast::Visibility>,
121 attrs: Option<ast::AttrVec>,
122}
123
124impl PartialEq for UseTree {
125 fn eq(&self, other: &UseTree) -> bool {
126 self.path == other.path
127 }
128}
129impl Eq for UseTree {}
130
131impl Spanned for UseTree {
132 fn span(&self) -> Span {
133 let lo = if let Some(ref attrs) = self.attrs {
134 attrs.iter().next().map_or(self.span.lo(), |a| a.span.lo())
135 } else {
136 self.span.lo()
137 };
138 mk_sp(lo, self.span.hi())
139 }
140}
141
142impl UseSegment {
143 fn remove_alias(&self) -> UseSegment {
145 let kind = match self.kind {
146 UseSegmentKind::Ident(ref s, _) => UseSegmentKind::Ident(s.clone(), None),
147 UseSegmentKind::Slf(_) => UseSegmentKind::Slf(None),
148 UseSegmentKind::Super(_) => UseSegmentKind::Super(None),
149 UseSegmentKind::Crate(_) => UseSegmentKind::Crate(None),
150 _ => return self.clone(),
151 };
152 UseSegment {
153 kind,
154 style_edition: self.style_edition,
155 }
156 }
157
158 fn equal_except_alias(&self, other: &Self) -> bool {
160 match (&self.kind, &other.kind) {
161 (UseSegmentKind::Ident(ref s1, _), UseSegmentKind::Ident(ref s2, _)) => s1 == s2,
162 (UseSegmentKind::Slf(_), UseSegmentKind::Slf(_))
163 | (UseSegmentKind::Super(_), UseSegmentKind::Super(_))
164 | (UseSegmentKind::Crate(_), UseSegmentKind::Crate(_))
165 | (UseSegmentKind::Glob, UseSegmentKind::Glob) => true,
166 (UseSegmentKind::List(ref list1), UseSegmentKind::List(ref list2)) => list1 == list2,
167 _ => false,
168 }
169 }
170
171 fn get_alias(&self) -> Option<&str> {
172 match &self.kind {
173 UseSegmentKind::Ident(_, a)
174 | UseSegmentKind::Slf(a)
175 | UseSegmentKind::Super(a)
176 | UseSegmentKind::Crate(a) => a.as_deref(),
177 _ => None,
178 }
179 }
180
181 fn from_path_segment(
182 context: &RewriteContext<'_>,
183 path_seg: &ast::PathSegment,
184 modsep: bool,
185 ) -> Option<UseSegment> {
186 let name = rewrite_ident(context, path_seg.ident);
187 if name.is_empty() || name == "{{root}}" {
188 return None;
189 }
190 let kind = match name {
191 "self" => UseSegmentKind::Slf(None),
192 "super" => UseSegmentKind::Super(None),
193 "crate" => UseSegmentKind::Crate(None),
194 _ => {
195 let mod_sep = if modsep { "::" } else { "" };
196 UseSegmentKind::Ident(format!("{mod_sep}{name}"), None)
197 }
198 };
199
200 Some(UseSegment {
201 kind,
202 style_edition: context.config.style_edition(),
203 })
204 }
205
206 fn contains_comment(&self) -> bool {
207 if let UseSegmentKind::List(list) = &self.kind {
208 list.iter().any(|subtree| subtree.contains_comment())
209 } else {
210 false
211 }
212 }
213}
214
215pub(crate) fn normalize_use_trees_with_granularity(
216 use_trees: Vec<UseTree>,
217 import_granularity: ImportGranularity,
218) -> Vec<UseTree> {
219 let merge_by = match import_granularity {
220 ImportGranularity::Item => return flatten_use_trees(use_trees, ImportGranularity::Item),
221 ImportGranularity::Preserve => return use_trees,
222 ImportGranularity::Crate => SharedPrefix::Crate,
223 ImportGranularity::Module => SharedPrefix::Module,
224 ImportGranularity::One => SharedPrefix::One,
225 };
226
227 let mut result = Vec::with_capacity(use_trees.len());
228 for use_tree in use_trees {
229 if use_tree.contains_comment() || use_tree.attrs.is_some() {
230 result.push(use_tree);
231 continue;
232 }
233
234 for mut flattened in use_tree.flatten(import_granularity) {
235 if let Some(tree) = result
236 .iter_mut()
237 .find(|tree| tree.share_prefix(&flattened, merge_by))
238 {
239 tree.merge(&flattened, merge_by);
240 } else {
241 if merge_by == SharedPrefix::Module {
243 flattened = flattened.nest_trailing_self();
244 }
245 result.push(flattened);
246 }
247 }
248 }
249 result
250}
251
252fn flatten_use_trees(
253 use_trees: Vec<UseTree>,
254 import_granularity: ImportGranularity,
255) -> Vec<UseTree> {
256 use_trees
259 .into_iter()
260 .flat_map(|tree| tree.flatten(import_granularity))
261 .map(UseTree::nest_trailing_self)
262 .unique()
263 .collect()
264}
265
266impl fmt::Debug for UseTree {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 fmt::Display::fmt(self, f)
269 }
270}
271
272impl fmt::Debug for UseSegment {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 fmt::Display::fmt(&self.kind, f)
275 }
276}
277
278impl fmt::Display for UseSegment {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 fmt::Display::fmt(&self.kind, f)
281 }
282}
283
284impl Hash for UseSegment {
285 fn hash<H: Hasher>(&self, state: &mut H) {
286 self.kind.hash(state);
287 }
288}
289
290impl fmt::Debug for UseSegmentKind {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 fmt::Display::fmt(self, f)
293 }
294}
295
296impl fmt::Display for UseSegmentKind {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 match *self {
299 UseSegmentKind::Glob => write!(f, "*"),
300 UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{s} as {alias}"),
301 UseSegmentKind::Ident(ref s, None) => write!(f, "{s}"),
302 UseSegmentKind::Slf(..) => write!(f, "self"),
303 UseSegmentKind::Super(..) => write!(f, "super"),
304 UseSegmentKind::Crate(..) => write!(f, "crate"),
305 UseSegmentKind::List(ref list) => {
306 write!(f, "{{")?;
307 for (i, item) in list.iter().enumerate() {
308 if i != 0 {
309 write!(f, ", ")?;
310 }
311 write!(f, "{item}")?;
312 }
313 write!(f, "}}")
314 }
315 }
316 }
317}
318impl fmt::Display for UseTree {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 for (i, segment) in self.path.iter().enumerate() {
321 if i != 0 {
322 write!(f, "::")?;
323 }
324 write!(f, "{segment}")?;
325 }
326 Ok(())
327 }
328}
329
330impl UseTree {
331 pub(crate) fn rewrite_top_level(
333 &self,
334 context: &RewriteContext<'_>,
335 shape: Shape,
336 ) -> RewriteResult {
337 let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
338 crate::utils::format_visibility(context, vis)
339 });
340 let use_str = self
341 .rewrite_result(
342 context,
343 shape
344 .offset_left(vis.len())
345 .max_width_error(shape.width, self.span())?,
346 )
347 .map(|s| {
348 if s.is_empty() {
349 s
350 } else {
351 format!("{}use {};", vis, s)
352 }
353 })?;
354 match self.attrs {
355 Some(ref attrs) if !attrs.is_empty() => {
356 let attr_str = attrs.rewrite_result(context, shape)?;
357 let lo = attrs.last().unknown_error()?.span.hi();
358 let hi = self.span.lo();
359 let span = mk_sp(lo, hi);
360
361 let allow_extend = if attrs.len() == 1 {
362 let line_len = attr_str.len() + 1 + use_str.len();
363 !attrs.first().unwrap().is_doc_comment()
364 && context.config.inline_attribute_width() >= line_len
365 } else {
366 false
367 };
368
369 combine_strs_with_missing_comments(
370 context,
371 &attr_str,
372 &use_str,
373 span,
374 shape,
375 allow_extend,
376 )
377 }
378 _ => Ok(use_str),
379 }
380 }
381
382 fn from_path(path: Vec<UseSegment>, span: Span) -> UseTree {
388 UseTree {
389 path,
390 span,
391 list_item: None,
392 visibility: None,
393 attrs: None,
394 }
395 }
396
397 pub(crate) fn from_ast_with_normalization(
398 context: &RewriteContext<'_>,
399 item: &ast::Item,
400 ) -> Option<UseTree> {
401 match item.kind {
402 ast::ItemKind::Use(ref use_tree) => Some(
403 UseTree::from_ast(
404 context,
405 use_tree,
406 None,
407 Some(item.vis.clone()),
408 Some(item.span.lo()),
409 if item.attrs.is_empty() {
410 None
411 } else {
412 Some(item.attrs.clone())
413 },
414 )
415 .normalize(),
416 ),
417 _ => None,
418 }
419 }
420
421 fn from_ast(
422 context: &RewriteContext<'_>,
423 a: &ast::UseTree,
424 list_item: Option<ListItem>,
425 visibility: Option<ast::Visibility>,
426 opt_lo: Option<BytePos>,
427 attrs: Option<ast::AttrVec>,
428 ) -> UseTree {
429 let span = if let Some(lo) = opt_lo {
430 mk_sp(lo, a.span.hi())
431 } else {
432 a.span
433 };
434 let mut result = UseTree {
435 path: vec![],
436 span,
437 list_item,
438 visibility,
439 attrs,
440 };
441
442 let leading_modsep =
443 context.config.edition() >= Edition::Edition2018 && a.prefix.is_global();
444
445 let mut modsep = leading_modsep;
446
447 for p in &a.prefix.segments {
448 if let Some(use_segment) = UseSegment::from_path_segment(context, p, modsep) {
449 result.path.push(use_segment);
450 modsep = false;
451 }
452 }
453
454 let style_edition = context.config.style_edition();
455
456 match a.kind {
457 UseTreeKind::Glob => {
458 if a.prefix.segments.len() == 1 && leading_modsep {
460 let kind = UseSegmentKind::Ident("".to_owned(), None);
461 result.path.push(UseSegment {
462 kind,
463 style_edition,
464 });
465 }
466 result.path.push(UseSegment {
467 kind: UseSegmentKind::Glob,
468 style_edition,
469 });
470 }
471 UseTreeKind::Nested {
472 items: ref list, ..
473 } => {
474 let items = itemize_list(
477 context.snippet_provider,
478 list.iter().map(|(tree, _)| tree),
479 "}",
480 ",",
481 |tree| tree.span.lo(),
482 |tree| tree.span.hi(),
483 |_| Ok("".to_owned()), context.snippet_provider.span_after(a.span, "{"),
485 a.span.hi(),
486 false,
487 );
488
489 if a.prefix.segments.len() == 1 && leading_modsep {
492 let kind = UseSegmentKind::Ident("".to_owned(), None);
493 result.path.push(UseSegment {
494 kind,
495 style_edition,
496 });
497 }
498 let kind = UseSegmentKind::List(
499 list.iter()
500 .zip(items)
501 .map(|(t, list_item)| {
502 Self::from_ast(context, &t.0, Some(list_item), None, None, None)
503 })
504 .collect(),
505 );
506 result.path.push(UseSegment {
507 kind,
508 style_edition,
509 });
510 }
511 UseTreeKind::Simple(ref rename) => {
512 let name = if a.prefix.segments.len() == 2 && leading_modsep {
517 context.snippet(a.prefix.span).to_owned()
518 } else {
519 rewrite_ident(context, path_to_imported_ident(&a.prefix)).to_owned()
520 };
521 let alias = rename.and_then(|ident| {
522 if ident.name == sym::underscore_imports {
523 Some("_".to_owned())
525 } else if ident == path_to_imported_ident(&a.prefix) {
526 None
527 } else {
528 Some(rewrite_ident(context, ident).to_owned())
529 }
530 });
531 let kind = match name.as_ref() {
532 "self" => UseSegmentKind::Slf(alias),
533 "super" => UseSegmentKind::Super(alias),
534 "crate" => UseSegmentKind::Crate(alias),
535 _ => UseSegmentKind::Ident(name, alias),
536 };
537
538 let segment = UseSegment {
539 kind,
540 style_edition,
541 };
542
543 result.path.pop();
545 result.path.push(segment);
546 }
547 }
548 result
549 }
550
551 pub(crate) fn normalize(mut self) -> UseTree {
553 let mut last = self.path.pop().expect("Empty use tree?");
554 let mut normalize_sole_list = false;
556 let mut aliased_self = false;
557
558 match last.kind {
560 _ if self.attrs.is_some() => (),
561 UseSegmentKind::List(ref list) if list.is_empty() => {
562 self.path = vec![];
563 return self;
564 }
565 UseSegmentKind::Slf(None) if self.path.is_empty() && self.visibility.is_some() => {
566 self.path = vec![];
567 return self;
568 }
569 _ => (),
570 }
571
572 if let UseSegmentKind::Slf(None) = last.kind {
574 if !self.path.is_empty() {
575 return self;
576 }
577 }
578
579 if let UseSegmentKind::Slf(_) = last.kind {
581 if let Some(UseSegment {
582 kind: UseSegmentKind::Ident(_, None),
583 ..
584 }) = self.path.last()
585 {
586 aliased_self = true;
587 }
588 }
589
590 let mut done = false;
591 if aliased_self {
592 match self.path.last_mut() {
593 Some(UseSegment {
594 kind: UseSegmentKind::Ident(_, ref mut old_rename),
595 ..
596 }) => {
597 assert!(old_rename.is_none());
598 if let UseSegmentKind::Slf(Some(rename)) = last.clone().kind {
599 *old_rename = Some(rename);
600 done = true;
601 }
602 }
603 _ => unreachable!(),
604 }
605 }
606
607 if done {
608 return self;
609 }
610
611 if let UseSegmentKind::List(ref list) = last.kind {
613 if list.len() == 1 && list[0].to_string() != "self" && !list[0].has_comment() {
614 normalize_sole_list = true;
615 }
616 }
617
618 if normalize_sole_list {
619 match last.kind {
620 UseSegmentKind::List(list) => {
621 for seg in &list[0].path {
622 self.path.push(seg.clone());
623 }
624 return self.normalize();
625 }
626 _ => unreachable!(),
627 }
628 }
629
630 if let UseSegmentKind::List(list) = last.kind {
632 let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
633 list.sort();
634 last = UseSegment {
635 kind: UseSegmentKind::List(list),
636 style_edition: last.style_edition,
637 };
638 }
639
640 self.path.push(last);
641 self
642 }
643
644 fn has_comment(&self) -> bool {
645 self.list_item.as_ref().map_or(false, ListItem::has_comment)
646 }
647
648 fn contains_comment(&self) -> bool {
649 self.has_comment() || self.path.iter().any(|path| path.contains_comment())
650 }
651
652 fn same_visibility(&self, other: &UseTree) -> bool {
653 match (&self.visibility, &other.visibility) {
654 (
655 Some(ast::Visibility {
656 kind: ast::VisibilityKind::Inherited,
657 ..
658 }),
659 None,
660 )
661 | (
662 None,
663 Some(ast::Visibility {
664 kind: ast::VisibilityKind::Inherited,
665 ..
666 }),
667 )
668 | (None, None) => true,
669 (Some(ref a), Some(ref b)) => is_same_visibility(a, b),
670 _ => false,
671 }
672 }
673
674 fn share_prefix(&self, other: &UseTree, shared_prefix: SharedPrefix) -> bool {
675 if self.path.is_empty()
676 || other.path.is_empty()
677 || self.attrs.is_some()
678 || self.contains_comment()
679 || !self.same_visibility(other)
680 {
681 false
682 } else {
683 match shared_prefix {
684 SharedPrefix::Crate => self.path[0] == other.path[0],
685 SharedPrefix::Module => {
686 self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
687 }
688 SharedPrefix::One => true,
689 }
690 }
691 }
692
693 fn flatten(self, import_granularity: ImportGranularity) -> Vec<UseTree> {
694 if self.path.is_empty() || self.contains_comment() {
695 return vec![self];
696 }
697 match &self.path.clone().last().unwrap().kind {
698 UseSegmentKind::List(list) => {
699 if list.len() == 1 && list[0].path.len() == 1 {
700 if let UseSegmentKind::Slf(..) = list[0].path[0].kind {
701 return vec![self];
702 };
703 }
704 let prefix = &self.path[..self.path.len() - 1];
705 let mut result = vec![];
706 for nested_use_tree in list {
707 for flattened in &mut nested_use_tree.clone().flatten(import_granularity) {
708 let mut new_path = prefix.to_vec();
709 new_path.append(&mut flattened.path);
710 result.push(UseTree {
711 path: new_path,
712 span: self.span,
713 list_item: None,
714 visibility: self.visibility.clone(),
715 attrs: match import_granularity {
717 ImportGranularity::Item => self.attrs.clone(),
718 _ => None,
719 },
720 });
721 }
722 }
723
724 result
725 }
726 _ => vec![self],
727 }
728 }
729
730 fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
731 let mut prefix = 0;
732 for (a, b) in self.path.iter().zip(other.path.iter()) {
733 if (prefix == 0 && a.equal_except_alias(b)) || a == b {
735 prefix += 1;
736 } else {
737 break;
738 }
739 }
740 if let Some(new_path) = merge_rest(&self.path, &other.path, prefix, merge_by) {
741 self.path = new_path;
742 self.span = self.span.to(other.span);
743 }
744 }
745
746 fn nest_trailing_self(mut self) -> UseTree {
748 if let Some(UseSegment {
749 kind: UseSegmentKind::Slf(..),
750 ..
751 }) = self.path.last()
752 {
753 let self_segment = self.path.pop().unwrap();
754 let style_edition = self_segment.style_edition;
755 let kind = UseSegmentKind::List(vec![UseTree::from_path(vec![self_segment], DUMMY_SP)]);
756 self.path.push(UseSegment {
757 kind,
758 style_edition,
759 });
760 }
761 self
762 }
763}
764
765fn merge_rest(
766 a: &[UseSegment],
767 b: &[UseSegment],
768 mut len: usize,
769 merge_by: SharedPrefix,
770) -> Option<Vec<UseSegment>> {
771 if a.len() == len && b.len() == len {
772 return None;
773 }
774 if a.len() != len && b.len() != len {
775 let style_edition = a[len].style_edition;
776 if let UseSegmentKind::List(ref list) = a[len].kind {
777 let mut list = list.clone();
778 merge_use_trees_inner(
779 &mut list,
780 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
781 merge_by,
782 );
783 let mut new_path = b[..len].to_vec();
784 let kind = UseSegmentKind::List(list);
785 new_path.push(UseSegment {
786 kind,
787 style_edition,
788 });
789 return Some(new_path);
790 }
791 } else if len == 1 {
792 let (common, rest) = if a.len() == len {
793 (&a[0], &b[1..])
794 } else {
795 (&b[0], &a[1..])
796 };
797 let kind = UseSegmentKind::Slf(common.get_alias().map(ToString::to_string));
798 let style_edition = a[0].style_edition;
799 let mut list = vec![UseTree::from_path(
800 vec![UseSegment {
801 kind,
802 style_edition,
803 }],
804 DUMMY_SP,
805 )];
806 match rest {
807 [
808 UseSegment {
809 kind: UseSegmentKind::List(rest_list),
810 ..
811 },
812 ] => list.extend(rest_list.clone()),
813 _ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)),
814 }
815 return Some(vec![
816 b[0].clone(),
817 UseSegment {
818 kind: UseSegmentKind::List(list),
819 style_edition,
820 },
821 ]);
822 } else {
823 len -= 1;
824 }
825 let mut list = vec![
826 UseTree::from_path(a[len..].to_vec(), DUMMY_SP),
827 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
828 ];
829 list.sort();
830 let mut new_path = b[..len].to_vec();
831 let kind = UseSegmentKind::List(list);
832 let style_edition = a[0].style_edition;
833 new_path.push(UseSegment {
834 kind,
835 style_edition,
836 });
837 Some(new_path)
838}
839
840fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
841 struct SimilarTree<'a> {
842 similarity: usize,
843 path_len: usize,
844 tree: &'a mut UseTree,
845 }
846
847 let similar_trees = trees.iter_mut().filter_map(|tree| {
848 if tree.share_prefix(&use_tree, merge_by) {
849 let similarity = if merge_by == SharedPrefix::One {
853 tree.path
854 .iter()
855 .zip(&use_tree.path)
856 .take_while(|(a, b)| a.equal_except_alias(b))
857 .count()
858 } else {
859 0
860 };
861
862 let path_len = tree.path.len();
863 Some(SimilarTree {
864 similarity,
865 tree,
866 path_len,
867 })
868 } else {
869 None
870 }
871 });
872
873 if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
874 if let Some(tree) = similar_trees.min_by_key(|tree| tree.path_len) {
875 if tree.path_len == 1 {
876 return;
877 }
878 }
879 } else if merge_by == SharedPrefix::One {
880 if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.similarity) {
881 if sim_tree.similarity > 0 {
882 sim_tree.tree.merge(&use_tree, merge_by);
883 return;
884 }
885 }
886 } else if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.path_len) {
887 if sim_tree.path_len > 1 {
888 sim_tree.tree.merge(&use_tree, merge_by);
889 return;
890 }
891 }
892 trees.push(use_tree);
893 trees.sort();
894}
895
896impl Hash for UseTree {
897 fn hash<H: Hasher>(&self, state: &mut H) {
898 self.path.hash(state);
899 }
900}
901
902impl PartialOrd for UseSegment {
903 fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
904 Some(self.cmp(other))
905 }
906}
907impl PartialOrd for UseTree {
908 fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
909 Some(self.cmp(other))
910 }
911}
912impl Ord for UseSegment {
913 fn cmp(&self, other: &UseSegment) -> Ordering {
914 use self::UseSegmentKind::*;
915
916 fn is_upper_snake_case(s: &str) -> bool {
917 s.chars()
918 .all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
919 }
920
921 match (&self.kind, &other.kind) {
922 (Slf(ref a), Slf(ref b))
923 | (Super(ref a), Super(ref b))
924 | (Crate(ref a), Crate(ref b)) => match (a, b) {
925 (Some(sa), Some(sb)) => {
926 if self.style_edition >= StyleEdition::Edition2024 {
927 version_sort(sa.trim_start_matches("r#"), sb.trim_start_matches("r#"))
928 } else {
929 a.cmp(b)
930 }
931 }
932 (_, _) => a.cmp(b),
933 },
934 (Glob, Glob) => Ordering::Equal,
935 (Ident(ref pia, ref aa), Ident(ref pib, ref ab)) => {
936 let (ia, ib) = if self.style_edition >= StyleEdition::Edition2024 {
937 (pia.trim_start_matches("r#"), pib.trim_start_matches("r#"))
938 } else {
939 (pia.as_str(), pib.as_str())
940 };
941
942 let ident_ord = if self.style_edition >= StyleEdition::Edition2024 {
943 version_sort(ia, ib)
944 } else {
945 if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) {
947 return Ordering::Greater;
948 }
949 if ia.starts_with(char::is_lowercase) && ib.starts_with(char::is_uppercase) {
950 return Ordering::Less;
951 }
952 if is_upper_snake_case(ia) && !is_upper_snake_case(ib) {
953 return Ordering::Greater;
954 }
955 if !is_upper_snake_case(ia) && is_upper_snake_case(ib) {
956 return Ordering::Less;
957 }
958 ia.cmp(ib)
959 };
960
961 if ident_ord != Ordering::Equal {
962 return ident_ord;
963 }
964 match (aa, ab) {
965 (None, Some(_)) => Ordering::Less,
966 (Some(_), None) => Ordering::Greater,
967 (Some(aas), Some(abs)) => {
968 if self.style_edition >= StyleEdition::Edition2024 {
969 version_sort(aas.trim_start_matches("r#"), abs.trim_start_matches("r#"))
970 } else {
971 aas.cmp(abs)
972 }
973 }
974 (None, None) => Ordering::Equal,
975 }
976 }
977 (List(ref a), List(ref b)) => {
978 for (a, b) in a.iter().zip(b.iter()) {
979 let ord = a.cmp(b);
980 if ord != Ordering::Equal {
981 return ord;
982 }
983 }
984
985 a.len().cmp(&b.len())
986 }
987 (Slf(_), _) => Ordering::Less,
988 (_, Slf(_)) => Ordering::Greater,
989 (Super(_), _) => Ordering::Less,
990 (_, Super(_)) => Ordering::Greater,
991 (Crate(_), _) => Ordering::Less,
992 (_, Crate(_)) => Ordering::Greater,
993 (Ident(..), _) => Ordering::Less,
994 (_, Ident(..)) => Ordering::Greater,
995 (Glob, _) => Ordering::Less,
996 (_, Glob) => Ordering::Greater,
997 }
998 }
999}
1000impl Ord for UseTree {
1001 fn cmp(&self, other: &UseTree) -> Ordering {
1002 for (a, b) in self.path.iter().zip(other.path.iter()) {
1003 let ord = a.cmp(b);
1004 if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
1008 {
1009 return ord;
1010 }
1011 }
1012
1013 self.path.len().cmp(&other.path.len())
1014 }
1015}
1016
1017fn rewrite_nested_use_tree(
1018 context: &RewriteContext<'_>,
1019 use_tree_list: &[UseTree],
1020 shape: Shape,
1021) -> RewriteResult {
1022 let mut list_items = Vec::with_capacity(use_tree_list.len());
1023 let nested_shape = match context.config.imports_indent() {
1024 IndentStyle::Block => shape
1025 .block_indent(context.config.tab_spaces())
1026 .with_max_width(context.config)
1027 .sub_width(1)
1028 .unknown_error()?,
1029 IndentStyle::Visual => shape.visual_indent(0),
1030 };
1031 for use_tree in use_tree_list {
1032 if let Some(mut list_item) = use_tree.list_item.clone() {
1033 list_item.item = use_tree.rewrite_result(context, nested_shape);
1034 list_items.push(list_item);
1035 } else {
1036 list_items.push(ListItem::from_str(
1037 use_tree.rewrite_result(context, nested_shape)?,
1038 ));
1039 }
1040 }
1041 let has_nested_list = use_tree_list.iter().any(|use_segment| {
1042 use_segment.path.last().map_or(false, |last_segment| {
1043 matches!(last_segment.kind, UseSegmentKind::List(..))
1044 })
1045 });
1046
1047 let remaining_width = if has_nested_list {
1048 0
1049 } else {
1050 shape.width.saturating_sub(2)
1051 };
1052
1053 let tactic = definitive_tactic(
1054 &list_items,
1055 context.config.imports_layout(),
1056 Separator::Comma,
1057 remaining_width,
1058 );
1059
1060 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
1061 && tactic != DefinitiveListTactic::Horizontal;
1062 let trailing_separator = if ends_with_newline {
1063 context.config.trailing_comma()
1064 } else {
1065 SeparatorTactic::Never
1066 };
1067 let fmt = ListFormatting::new(nested_shape, context.config)
1068 .tactic(tactic)
1069 .trailing_separator(trailing_separator)
1070 .ends_with_newline(ends_with_newline)
1071 .preserve_newline(true)
1072 .nested(has_nested_list);
1073
1074 let list_str = write_list(&list_items, &fmt)?;
1075
1076 let result = if (list_str.contains('\n')
1077 || list_str.len() > remaining_width
1078 || tactic == DefinitiveListTactic::Vertical)
1079 && context.config.imports_indent() == IndentStyle::Block
1080 {
1081 format!(
1082 "{{\n{}{}\n{}}}",
1083 nested_shape.indent.to_string(context.config),
1084 list_str,
1085 shape.indent.to_string(context.config)
1086 )
1087 } else {
1088 format!("{{{list_str}}}")
1089 };
1090
1091 Ok(result)
1092}
1093
1094impl Rewrite for UseSegment {
1095 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1096 self.rewrite_result(context, shape).ok()
1097 }
1098
1099 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1100 Ok(match self.kind {
1101 UseSegmentKind::Ident(ref ident, Some(ref rename)) => {
1102 format!("{ident} as {rename}")
1103 }
1104 UseSegmentKind::Ident(ref ident, None) => ident.clone(),
1105 UseSegmentKind::Slf(Some(ref rename)) => format!("self as {rename}"),
1106 UseSegmentKind::Slf(None) => "self".to_owned(),
1107 UseSegmentKind::Super(Some(ref rename)) => format!("super as {rename}"),
1108 UseSegmentKind::Super(None) => "super".to_owned(),
1109 UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {rename}"),
1110 UseSegmentKind::Crate(None) => "crate".to_owned(),
1111 UseSegmentKind::Glob => "*".to_owned(),
1112 UseSegmentKind::List(ref use_tree_list) => {
1113 rewrite_nested_use_tree(
1114 context,
1115 use_tree_list,
1116 shape
1118 .offset_left(1)
1119 .and_then(|s| s.sub_width(1))
1120 .unknown_error()?,
1121 )?
1122 }
1123 })
1124 }
1125}
1126
1127impl Rewrite for UseTree {
1128 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1129 self.rewrite_result(context, shape).ok()
1130 }
1131
1132 fn rewrite_result(&self, context: &RewriteContext<'_>, mut shape: Shape) -> RewriteResult {
1134 let mut result = String::with_capacity(256);
1135 let mut iter = self.path.iter().peekable();
1136 while let Some(segment) = iter.next() {
1137 let segment_str = segment.rewrite_result(context, shape)?;
1138 result.push_str(&segment_str);
1139 if iter.peek().is_some() {
1140 result.push_str("::");
1141 shape = shape
1143 .offset_left(2 + segment_str.len())
1144 .max_width_error(shape.width, self.span())?;
1145 }
1146 }
1147 Ok(result)
1148 }
1149}
1150
1151#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1152enum SharedPrefix {
1153 Crate,
1154 Module,
1155 One,
1156}
1157
1158#[cfg(test)]
1159mod test {
1160 use super::*;
1161
1162 fn parse_use_tree(s: &str) -> UseTree {
1165 use std::iter::Peekable;
1166 use std::mem::swap;
1167 use std::str::Chars;
1168
1169 struct Parser<'a> {
1170 input: Peekable<Chars<'a>>,
1171 style_edition: StyleEdition,
1172 }
1173
1174 impl<'a> Parser<'a> {
1175 fn bump(&mut self) {
1176 self.input.next().unwrap();
1177 }
1178
1179 fn eat(&mut self, c: char) {
1180 assert_eq!(self.input.next().unwrap(), c);
1181 }
1182
1183 fn push_segment(
1184 &self,
1185 result: &mut Vec<UseSegment>,
1186 buf: &mut String,
1187 alias_buf: &mut Option<String>,
1188 ) {
1189 let style_edition = self.style_edition;
1190 if !buf.is_empty() {
1191 let mut alias = None;
1192 swap(alias_buf, &mut alias);
1193
1194 match buf.as_ref() {
1195 "self" => {
1196 let kind = UseSegmentKind::Slf(alias);
1197 result.push(UseSegment {
1198 kind,
1199 style_edition,
1200 });
1201 *buf = String::new();
1202 *alias_buf = None;
1203 }
1204 "super" => {
1205 let kind = UseSegmentKind::Super(alias);
1206 result.push(UseSegment {
1207 kind,
1208 style_edition,
1209 });
1210 *buf = String::new();
1211 *alias_buf = None;
1212 }
1213 "crate" => {
1214 let kind = UseSegmentKind::Crate(alias);
1215 result.push(UseSegment {
1216 kind,
1217 style_edition,
1218 });
1219 *buf = String::new();
1220 *alias_buf = None;
1221 }
1222 _ => {
1223 let mut name = String::new();
1224 swap(buf, &mut name);
1225 let kind = UseSegmentKind::Ident(name, alias);
1226 result.push(UseSegment {
1227 kind,
1228 style_edition,
1229 });
1230 }
1231 }
1232 }
1233 }
1234
1235 fn parse_in_list(&mut self) -> UseTree {
1236 let mut result = vec![];
1237 let mut buf = String::new();
1238 let mut alias_buf = None;
1239 while let Some(&c) = self.input.peek() {
1240 match c {
1241 '{' => {
1242 assert!(buf.is_empty());
1243 self.bump();
1244 let kind = UseSegmentKind::List(self.parse_list());
1245 result.push(UseSegment {
1246 kind,
1247 style_edition: self.style_edition,
1248 });
1249 self.eat('}');
1250 }
1251 '*' => {
1252 assert!(buf.is_empty());
1253 self.bump();
1254 let kind = UseSegmentKind::Glob;
1255 result.push(UseSegment {
1256 kind,
1257 style_edition: self.style_edition,
1258 });
1259 }
1260 ':' => {
1261 self.bump();
1262 self.eat(':');
1263 self.push_segment(&mut result, &mut buf, &mut alias_buf);
1264 }
1265 '}' | ',' => {
1266 self.push_segment(&mut result, &mut buf, &mut alias_buf);
1267 return UseTree {
1268 path: result,
1269 span: DUMMY_SP,
1270 list_item: None,
1271 visibility: None,
1272 attrs: None,
1273 };
1274 }
1275 ' ' => {
1276 self.bump();
1277 self.eat('a');
1278 self.eat('s');
1279 self.eat(' ');
1280 alias_buf = Some(String::new());
1281 }
1282 c => {
1283 self.bump();
1284 if let Some(ref mut buf) = alias_buf {
1285 buf.push(c);
1286 } else {
1287 buf.push(c);
1288 }
1289 }
1290 }
1291 }
1292 self.push_segment(&mut result, &mut buf, &mut alias_buf);
1293 UseTree {
1294 path: result,
1295 span: DUMMY_SP,
1296 list_item: None,
1297 visibility: None,
1298 attrs: None,
1299 }
1300 }
1301
1302 fn parse_list(&mut self) -> Vec<UseTree> {
1303 let mut result = vec![];
1304 loop {
1305 match self.input.peek().unwrap() {
1306 ',' | ' ' => self.bump(),
1307 '}' => {
1308 return result;
1309 }
1310 _ => result.push(self.parse_in_list()),
1311 }
1312 }
1313 }
1314 }
1315
1316 let mut parser = Parser {
1317 input: s.chars().peekable(),
1318 style_edition: StyleEdition::Edition2015,
1319 };
1320 parser.parse_in_list()
1321 }
1322
1323 macro_rules! parse_use_trees {
1324 ($($s:expr),* $(,)*) => {
1325 vec![
1326 $(parse_use_tree($s),)*
1327 ]
1328 }
1329 }
1330
1331 macro_rules! test_merge {
1332 ($by:ident, [$($input:expr),* $(,)*], [$($output:expr),* $(,)*]) => {
1333 assert_eq!(
1334 normalize_use_trees_with_granularity(
1335 parse_use_trees!($($input,)*),
1336 ImportGranularity::$by,
1337 ),
1338 parse_use_trees!($($output,)*),
1339 );
1340 }
1341 }
1342
1343 #[test]
1344 fn test_use_tree_merge_crate() {
1345 test_merge!(
1346 Crate,
1347 ["a::b::{c, d}", "a::b::{e, f}"],
1348 ["a::b::{c, d, e, f}"]
1349 );
1350 test_merge!(Crate, ["a::b::c", "a::b"], ["a::{b, b::c}"]);
1351 test_merge!(Crate, ["a::b", "a::b"], ["a::b"]);
1352 test_merge!(Crate, ["a", "a::b", "a::b::c"], ["a::{self, b, b::c}"]);
1353 test_merge!(
1354 Crate,
1355 ["a", "a::b", "a::b::c", "a::b::c::d"],
1356 ["a::{self, b, b::{c, c::d}}"]
1357 );
1358 test_merge!(
1359 Crate,
1360 ["a", "a::b", "a::b::c", "a::b"],
1361 ["a::{self, b, b::c}"]
1362 );
1363 test_merge!(
1364 Crate,
1365 ["a::{b::{self, c}, d::e}", "a::d::f"],
1366 ["a::{b::{self, c}, d::{e, f}}"]
1367 );
1368 test_merge!(
1369 Crate,
1370 ["a::d::f", "a::{b::{self, c}, d::e}"],
1371 ["a::{b::{self, c}, d::{e, f}}"]
1372 );
1373 test_merge!(
1374 Crate,
1375 ["a::{c, d, b}", "a::{d, e, b, a, f}", "a::{f, g, c}"],
1376 ["a::{a, b, c, d, e, f, g}"]
1377 );
1378 test_merge!(
1379 Crate,
1380 ["a::{self}", "b::{self as foo}"],
1381 ["a::{self}", "b::{self as foo}"]
1382 );
1383 }
1384
1385 #[test]
1386 fn test_use_tree_merge_module() {
1387 test_merge!(
1388 Module,
1389 ["foo::b", "foo::{a, c, d::e}"],
1390 ["foo::{a, b, c}", "foo::d::e"]
1391 );
1392
1393 test_merge!(
1394 Module,
1395 ["foo::{a::b, a::c, d::e, d::f}"],
1396 ["foo::a::{b, c}", "foo::d::{e, f}"]
1397 );
1398 }
1399
1400 #[test]
1401 fn test_use_tree_merge_one() {
1402 test_merge!(One, ["a", "b"], ["{a, b}"]);
1403
1404 test_merge!(One, ["a::{aa, ab}", "b", "a"], ["{a::{self, aa, ab}, b}"]);
1405
1406 test_merge!(One, ["a as x", "b as y"], ["{a as x, b as y}"]);
1407
1408 test_merge!(
1409 One,
1410 ["a::{aa as xa, ab}", "b", "a"],
1411 ["{a::{self, aa as xa, ab}, b}"]
1412 );
1413
1414 test_merge!(
1415 One,
1416 ["a", "a::{aa, ab::{aba, abb}}"],
1417 ["a::{self, aa, ab::{aba, abb}}"]
1418 );
1419
1420 test_merge!(One, ["a", "b::{ba, *}"], ["{a, b::{ba, *}}"]);
1421
1422 test_merge!(One, ["a", "b", "a::aa"], ["{a::{self, aa}, b}"]);
1423
1424 test_merge!(
1425 One,
1426 ["a::aa::aaa", "a::ac::aca", "a::aa::*"],
1427 ["a::{aa::{aaa, *}, ac::aca}"]
1428 );
1429
1430 test_merge!(
1431 One,
1432 ["a", "b::{ba, bb}", "a::{aa::*, ab::aba}"],
1433 ["{a::{self, aa::*, ab::aba}, b::{ba, bb}}"]
1434 );
1435
1436 test_merge!(
1437 One,
1438 ["b", "a::ac::{aca, acb}", "a::{aa::*, ab}"],
1439 ["{a::{aa::*, ab, ac::{aca, acb}}, b}"]
1440 );
1441 }
1442
1443 #[test]
1444 fn test_flatten_use_trees() {
1445 assert_eq!(
1446 flatten_use_trees(
1447 parse_use_trees!["foo::{a::{b, c}, d::e}"],
1448 ImportGranularity::Item
1449 ),
1450 parse_use_trees!["foo::a::b", "foo::a::c", "foo::d::e"]
1451 );
1452
1453 assert_eq!(
1454 flatten_use_trees(
1455 parse_use_trees!["foo::{self, a, b::{c, d}, e::*}"],
1456 ImportGranularity::Item
1457 ),
1458 parse_use_trees![
1459 "foo::{self}",
1460 "foo::a",
1461 "foo::b::c",
1462 "foo::b::d",
1463 "foo::e::*"
1464 ]
1465 );
1466 }
1467
1468 #[test]
1469 fn test_use_tree_flatten() {
1470 assert_eq!(
1471 parse_use_tree("a::b::{c, d, e, f}").flatten(ImportGranularity::Item),
1472 parse_use_trees!("a::b::c", "a::b::d", "a::b::e", "a::b::f",)
1473 );
1474
1475 assert_eq!(
1476 parse_use_tree("a::b::{c::{d, e, f}, g, h::{i, j, k}}")
1477 .flatten(ImportGranularity::Item),
1478 parse_use_trees![
1479 "a::b::c::d",
1480 "a::b::c::e",
1481 "a::b::c::f",
1482 "a::b::g",
1483 "a::b::h::i",
1484 "a::b::h::j",
1485 "a::b::h::k",
1486 ]
1487 );
1488 }
1489
1490 #[test]
1491 fn test_use_tree_normalize() {
1492 assert_eq!(parse_use_tree("a::self").normalize(), parse_use_tree("a"));
1493 assert_eq!(
1494 parse_use_tree("a::self as foo").normalize(),
1495 parse_use_tree("a as foo")
1496 );
1497 assert_eq!(
1498 parse_use_tree("a::{self}").normalize(),
1499 parse_use_tree("a::{self}")
1500 );
1501 assert_eq!(parse_use_tree("a::{b}").normalize(), parse_use_tree("a::b"));
1502 assert_eq!(
1503 parse_use_tree("a::{b, c::self}").normalize(),
1504 parse_use_tree("a::{b, c}")
1505 );
1506 assert_eq!(
1507 parse_use_tree("a::{b as bar, c::self}").normalize(),
1508 parse_use_tree("a::{b as bar, c}")
1509 );
1510 }
1511
1512 #[test]
1513 fn test_use_tree_ord() {
1514 assert!(parse_use_tree("a").normalize() < parse_use_tree("aa").normalize());
1515 assert!(parse_use_tree("a").normalize() < parse_use_tree("a::a").normalize());
1516 assert!(parse_use_tree("a").normalize() < parse_use_tree("*").normalize());
1517 assert!(parse_use_tree("a").normalize() < parse_use_tree("{a, b}").normalize());
1518 assert!(parse_use_tree("*").normalize() < parse_use_tree("{a, b}").normalize());
1519
1520 assert!(
1521 parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, dddddddd}").normalize()
1522 < parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, ddddddddd}").normalize()
1523 );
1524 assert!(
1525 parse_use_tree("serde::de::{Deserialize}").normalize()
1526 < parse_use_tree("serde_json").normalize()
1527 );
1528 assert!(parse_use_tree("a::b::c").normalize() < parse_use_tree("a::b::*").normalize());
1529 assert!(
1530 parse_use_tree("foo::{Bar, Baz}").normalize()
1531 < parse_use_tree("{Bar, Baz}").normalize()
1532 );
1533
1534 assert!(
1535 parse_use_tree("foo::{qux as bar}").normalize()
1536 < parse_use_tree("foo::{self as bar}").normalize()
1537 );
1538 assert!(
1539 parse_use_tree("foo::{qux as bar}").normalize()
1540 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1541 );
1542 assert!(
1543 parse_use_tree("foo::{self as bar, baz}").normalize()
1544 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1545 );
1546
1547 assert!(parse_use_tree("foo").normalize() < parse_use_tree("Foo").normalize());
1548 assert!(parse_use_tree("foo").normalize() < parse_use_tree("foo::Bar").normalize());
1549
1550 assert!(
1551 parse_use_tree("std::cmp::{d, c, b, a}").normalize()
1552 < parse_use_tree("std::cmp::{b, e, g, f}").normalize()
1553 );
1554 }
1555
1556 #[test]
1557 fn test_use_tree_nest_trailing_self() {
1558 assert_eq!(
1559 parse_use_tree("a::b::self").nest_trailing_self(),
1560 parse_use_tree("a::b::{self}")
1561 );
1562 assert_eq!(
1563 parse_use_tree("a::b::c").nest_trailing_self(),
1564 parse_use_tree("a::b::c")
1565 );
1566 assert_eq!(
1567 parse_use_tree("a::b::{c, d}").nest_trailing_self(),
1568 parse_use_tree("a::b::{c, d}")
1569 );
1570 assert_eq!(
1571 parse_use_tree("a::b::{self, c}").nest_trailing_self(),
1572 parse_use_tree("a::b::{self, c}")
1573 );
1574 }
1575}