2 use std::cmp::Ordering;
5 use rustc_ast::ast::{self, UseTreeKind};
8 BytePos, Span, DUMMY_SP,
11 use crate::comment::combine_strs_with_missing_comments;
12 use crate::config::lists::*;
13 use crate::config::{Edition, IndentStyle};
15 definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
17 use crate::rewrite::{Rewrite, RewriteContext};
18 use crate::shape::Shape;
19 use crate::source_map::SpanUtils;
20 use crate::spanned::Spanned;
21 use crate::utils::{is_same_visibility, mk_sp, rewrite_ident};
22 use crate::visitor::FmtVisitor;
24 /// Returns a name imported by a `use` declaration.
25 /// E.g., returns `Ordering` for `std::cmp::Ordering` and `self` for `std::cmp::self`.
26 pub(crate) fn path_to_imported_ident(path: &ast::Path) -> symbol::Ident {
27 path.segments.last().unwrap().ident
30 impl<'a> FmtVisitor<'a> {
31 pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
32 let span = item.span();
33 let shape = self.shape();
34 let rw = UseTree::from_ast(
38 Some(item.vis.clone()),
40 Some(item.attrs.clone()),
42 .rewrite_top_level(&self.get_context(), shape);
44 Some(ref s) if s.is_empty() => {
45 // Format up to last newline
46 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
47 let trimmed_snippet = self.snippet(prev_span).trim_end();
48 let span_end = self.last_pos + BytePos(trimmed_snippet.len() as u32);
49 self.format_missing(span_end);
50 // We have an excessive newline from the removed import.
51 if self.buffer.ends_with('\n') {
53 self.line_number -= 1;
55 self.last_pos = source!(self, span).hi();
58 self.format_missing_with_indent(source!(self, span).lo());
60 self.last_pos = source!(self, span).hi();
63 self.format_missing_with_indent(source!(self, span).lo());
64 self.format_missing(source!(self, span).hi());
70 // Ordering of imports
72 // We order imports by translating to our own representation and then sorting.
73 // The Rust AST data structures are really bad for this. Rustfmt applies a bunch
74 // of normalisations to imports and since we want to sort based on the result
75 // of these (and to maintain idempotence) we must apply the same normalisations
76 // to the data structures for sorting.
78 // We sort `self` and `super` before other imports, then identifier imports,
79 // then glob imports, then lists of imports. We do not take aliases into account
80 // when ordering unless the imports are identical except for the alias (rare in
83 // FIXME(#2531): we should unify the comparison code here with the formatting
84 // code elsewhere since we are essentially string-ifying twice. Furthermore, by
85 // parsing to our own format on comparison, we repeat a lot of work when
88 // FIXME we do a lot of allocation to make our own representation.
89 #[derive(Clone, Eq, PartialEq)]
90 pub(crate) enum UseSegment {
91 Ident(String, Option<String>),
93 Super(Option<String>),
94 Crate(Option<String>),
100 pub(crate) struct UseTree {
101 pub(crate) path: Vec<UseSegment>,
102 pub(crate) span: Span,
103 // Comment information within nested use tree.
104 pub(crate) list_item: Option<ListItem>,
105 // Additional fields for top level use items.
106 // Should we have another struct for top-level use items rather than reusing this?
107 visibility: Option<ast::Visibility>,
108 attrs: Option<Vec<ast::Attribute>>,
111 impl PartialEq for UseTree {
112 fn eq(&self, other: &UseTree) -> bool {
113 self.path == other.path
116 impl Eq for UseTree {}
118 impl Spanned for UseTree {
119 fn span(&self) -> Span {
120 let lo = if let Some(ref attrs) = self.attrs {
121 attrs.iter().next().map_or(self.span.lo(), |a| a.span.lo())
125 mk_sp(lo, self.span.hi())
130 // Clone a version of self with any top-level alias removed.
131 fn remove_alias(&self) -> UseSegment {
133 UseSegment::Ident(ref s, _) => UseSegment::Ident(s.clone(), None),
134 UseSegment::Slf(_) => UseSegment::Slf(None),
135 UseSegment::Super(_) => UseSegment::Super(None),
136 UseSegment::Crate(_) => UseSegment::Crate(None),
141 fn from_path_segment(
142 context: &RewriteContext<'_>,
143 path_seg: &ast::PathSegment,
145 ) -> Option<UseSegment> {
146 let name = rewrite_ident(context, path_seg.ident);
147 if name.is_empty() || name == "{{root}}" {
151 "self" => UseSegment::Slf(None),
152 "super" => UseSegment::Super(None),
153 "crate" => UseSegment::Crate(None),
155 let mod_sep = if modsep { "::" } else { "" };
156 UseSegment::Ident(format!("{}{}", mod_sep, name), None)
162 pub(crate) fn merge_use_trees(use_trees: Vec<UseTree>, merge_by: SharedPrefix) -> Vec<UseTree> {
163 let mut result = Vec::with_capacity(use_trees.len());
164 for use_tree in use_trees {
165 if use_tree.has_comment() || use_tree.attrs.is_some() {
166 result.push(use_tree);
170 for flattened in use_tree.flatten() {
171 if let Some(tree) = result
173 .find(|tree| tree.share_prefix(&flattened, merge_by))
175 tree.merge(&flattened, merge_by);
177 result.push(flattened);
184 pub(crate) fn flatten_use_trees(use_trees: Vec<UseTree>) -> Vec<UseTree> {
187 .flat_map(UseTree::flatten)
189 // If a path ends in `::self`, rewrite it to `::{self}`.
190 if let Some(UseSegment::Slf(..)) = tree.path.last() {
191 let self_segment = tree.path.pop().unwrap();
192 tree.path.push(UseSegment::List(vec![UseTree::from_path(
202 impl fmt::Debug for UseTree {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 fmt::Display::fmt(self, f)
208 impl fmt::Debug for UseSegment {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 fmt::Display::fmt(self, f)
214 impl fmt::Display for UseSegment {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 UseSegment::Glob => write!(f, "*"),
218 UseSegment::Ident(ref s, _) => write!(f, "{}", s),
219 UseSegment::Slf(..) => write!(f, "self"),
220 UseSegment::Super(..) => write!(f, "super"),
221 UseSegment::Crate(..) => write!(f, "crate"),
222 UseSegment::List(ref list) => {
224 for (i, item) in list.iter().enumerate() {
228 write!(f, "{}", item)?;
235 impl fmt::Display for UseTree {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 for (i, segment) in self.path.iter().enumerate() {
241 write!(f, "{}", segment)?;
248 // Rewrite use tree with `use ` and a trailing `;`.
249 pub(crate) fn rewrite_top_level(
251 context: &RewriteContext<'_>,
253 ) -> Option<String> {
254 let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
255 crate::utils::format_visibility(context, &vis)
258 .rewrite(context, shape.offset_left(vis.len())?)
263 format!("{}use {};", vis, s)
267 Some(ref attrs) if !attrs.is_empty() => {
268 let attr_str = attrs.rewrite(context, shape)?;
269 let lo = attrs.last().as_ref()?.span.hi();
270 let hi = self.span.lo();
271 let span = mk_sp(lo, hi);
273 let allow_extend = if attrs.len() == 1 {
274 let line_len = attr_str.len() + 1 + use_str.len();
275 !attrs.first().unwrap().is_doc_comment()
276 && context.config.inline_attribute_width() >= line_len
281 combine_strs_with_missing_comments(
294 // FIXME: Use correct span?
295 // The given span is essentially incorrect, since we are reconstructing
296 // use-statements. This should not be a problem, though, since we have
297 // already tried to extract comment and observed that there are no comment
298 // around the given use item, and the span will not be used afterward.
299 fn from_path(path: Vec<UseSegment>, span: Span) -> UseTree {
309 pub(crate) fn from_ast_with_normalization(
310 context: &RewriteContext<'_>,
312 ) -> Option<UseTree> {
314 ast::ItemKind::Use(ref use_tree) => Some(
319 Some(item.vis.clone()),
320 Some(item.span.lo()),
321 if item.attrs.is_empty() {
324 Some(item.attrs.clone())
334 context: &RewriteContext<'_>,
336 list_item: Option<ListItem>,
337 visibility: Option<ast::Visibility>,
338 opt_lo: Option<BytePos>,
339 attrs: Option<Vec<ast::Attribute>>,
341 let span = if let Some(lo) = opt_lo {
342 mk_sp(lo, a.span.hi())
346 let mut result = UseTree {
355 context.config.edition() >= Edition::Edition2018 && a.prefix.is_global();
357 let mut modsep = leading_modsep;
359 for p in &a.prefix.segments {
360 if let Some(use_segment) = UseSegment::from_path_segment(context, p, modsep) {
361 result.path.push(use_segment);
367 UseTreeKind::Glob => {
368 // in case of a global path and the glob starts at the root, e.g., "::*"
369 if a.prefix.segments.len() == 1 && leading_modsep {
370 result.path.push(UseSegment::Ident("".to_owned(), None));
372 result.path.push(UseSegment::Glob);
374 UseTreeKind::Nested(ref list) => {
375 // Extract comments between nested use items.
376 // This needs to be done before sorting use items.
377 let items: Vec<_> = itemize_list(
378 context.snippet_provider,
379 list.iter().map(|(tree, _)| tree),
382 |tree| tree.span.lo(),
383 |tree| tree.span.hi(),
384 |_| Some("".to_owned()), // We only need comments for now.
385 context.snippet_provider.span_after(a.span, "{"),
390 // in case of a global path and the nested list starts at the root,
391 // e.g., "::{foo, bar}"
392 if a.prefix.segments.len() == 1 && leading_modsep {
393 result.path.push(UseSegment::Ident("".to_owned(), None));
395 result.path.push(UseSegment::List(
397 .zip(items.into_iter())
398 .map(|(t, list_item)| {
399 Self::from_ast(context, &t.0, Some(list_item), None, None, None)
404 UseTreeKind::Simple(ref rename, ..) => {
405 // If the path has leading double colons and is composed of only 2 segments, then we
406 // bypass the call to path_to_imported_ident which would get only the ident and
407 // lose the path root, e.g., `that` in `::that`.
408 // The span of `a.prefix` contains the leading colons.
409 let name = if a.prefix.segments.len() == 2 && leading_modsep {
410 context.snippet(a.prefix.span).to_owned()
412 rewrite_ident(context, path_to_imported_ident(&a.prefix)).to_owned()
414 let alias = rename.and_then(|ident| {
415 if ident.name == sym::underscore_imports {
418 } else if ident == path_to_imported_ident(&a.prefix) {
421 Some(rewrite_ident(context, ident).to_owned())
424 let segment = match name.as_ref() {
425 "self" => UseSegment::Slf(alias),
426 "super" => UseSegment::Super(alias),
427 "crate" => UseSegment::Crate(alias),
428 _ => UseSegment::Ident(name, alias),
431 // `name` is already in result.
433 result.path.push(segment);
439 // Do the adjustments that rustfmt does elsewhere to use paths.
440 pub(crate) fn normalize(mut self) -> UseTree {
441 let mut last = self.path.pop().expect("Empty use tree?");
442 // Hack around borrow checker.
443 let mut normalize_sole_list = false;
444 let mut aliased_self = false;
446 // Remove foo::{} or self without attributes.
448 _ if self.attrs.is_some() => (),
449 UseSegment::List(ref list) if list.is_empty() => {
453 UseSegment::Slf(None) if self.path.is_empty() && self.visibility.is_some() => {
460 // Normalise foo::self -> foo.
461 if let UseSegment::Slf(None) = last {
462 if !self.path.is_empty() {
467 // Normalise foo::self as bar -> foo as bar.
468 if let UseSegment::Slf(_) = last {
469 match self.path.last() {
470 Some(UseSegment::Ident(_, None)) => {
477 let mut done = false;
479 match self.path.last_mut() {
480 Some(UseSegment::Ident(_, ref mut old_rename)) => {
481 assert!(old_rename.is_none());
482 if let UseSegment::Slf(Some(rename)) = last.clone() {
483 *old_rename = Some(rename);
495 // Normalise foo::{bar} -> foo::bar
496 if let UseSegment::List(ref list) = last {
497 if list.len() == 1 && list[0].to_string() != "self" {
498 normalize_sole_list = true;
502 if normalize_sole_list {
504 UseSegment::List(list) => {
505 for seg in &list[0].path {
506 self.path.push(seg.clone());
508 return self.normalize();
514 // Recursively normalize elements of a list use (including sorting the list).
515 if let UseSegment::List(list) = last {
516 let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
518 last = UseSegment::List(list);
521 self.path.push(last);
525 fn has_comment(&self) -> bool {
526 self.list_item.as_ref().map_or(false, ListItem::has_comment)
529 fn same_visibility(&self, other: &UseTree) -> bool {
530 match (&self.visibility, &other.visibility) {
532 Some(ast::Visibility {
533 kind: ast::VisibilityKind::Inherited,
540 Some(ast::Visibility {
541 kind: ast::VisibilityKind::Inherited,
545 | (None, None) => true,
546 (Some(ref a), Some(ref b)) => is_same_visibility(a, b),
551 fn share_prefix(&self, other: &UseTree, shared_prefix: SharedPrefix) -> bool {
552 if self.path.is_empty()
553 || other.path.is_empty()
554 || self.attrs.is_some()
555 || !self.same_visibility(other)
559 match shared_prefix {
560 SharedPrefix::Crate => self.path[0] == other.path[0],
561 SharedPrefix::Module => {
562 self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
568 fn flatten(self) -> Vec<UseTree> {
569 if self.path.is_empty() {
572 match self.path.clone().last().unwrap() {
573 UseSegment::List(list) => {
574 if list.len() == 1 && list[0].path.len() == 1 {
575 match list[0].path[0] {
576 UseSegment::Slf(..) => return vec![self],
580 let prefix = &self.path[..self.path.len() - 1];
581 let mut result = vec![];
582 for nested_use_tree in list {
583 for flattend in &mut nested_use_tree.clone().flatten() {
584 let mut new_path = prefix.to_vec();
585 new_path.append(&mut flattend.path);
586 result.push(UseTree {
590 visibility: self.visibility.clone(),
602 fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
604 for (a, b) in self.path.iter().zip(other.path.iter()) {
611 if let Some(new_path) = merge_rest(&self.path, &other.path, prefix, merge_by) {
612 self.path = new_path;
613 self.span = self.span.to(other.span);
622 merge_by: SharedPrefix,
623 ) -> Option<Vec<UseSegment>> {
624 if a.len() == len && b.len() == len {
627 if a.len() != len && b.len() != len {
628 if let UseSegment::List(ref list) = a[len] {
629 let mut list = list.clone();
630 merge_use_trees_inner(
632 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
635 let mut new_path = b[..len].to_vec();
636 new_path.push(UseSegment::List(list));
637 return Some(new_path);
640 let rest = if a.len() == len { &b[1..] } else { &a[1..] };
643 UseSegment::List(vec![
644 UseTree::from_path(vec![UseSegment::Slf(None)], DUMMY_SP),
645 UseTree::from_path(rest.to_vec(), DUMMY_SP),
652 UseTree::from_path(a[len..].to_vec(), DUMMY_SP),
653 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
656 let mut new_path = b[..len].to_vec();
657 new_path.push(UseSegment::List(list));
661 fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
662 let similar_trees = trees
664 .filter(|tree| tree.share_prefix(&use_tree, merge_by));
665 if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
666 if let Some(tree) = similar_trees.min_by_key(|tree| tree.path.len()) {
667 if tree.path.len() == 1 {
671 } else if let Some(tree) = similar_trees.max_by_key(|tree| tree.path.len()) {
672 if tree.path.len() > 1 {
673 tree.merge(&use_tree, merge_by);
677 trees.push(use_tree);
681 impl PartialOrd for UseSegment {
682 fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
683 Some(self.cmp(other))
686 impl PartialOrd for UseTree {
687 fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
688 Some(self.cmp(other))
691 impl Ord for UseSegment {
692 fn cmp(&self, other: &UseSegment) -> Ordering {
693 use self::UseSegment::*;
695 fn is_upper_snake_case(s: &str) -> bool {
697 .all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
700 match (self, other) {
701 (&Slf(ref a), &Slf(ref b))
702 | (&Super(ref a), &Super(ref b))
703 | (&Crate(ref a), &Crate(ref b)) => a.cmp(b),
704 (&Glob, &Glob) => Ordering::Equal,
705 (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => {
706 // snake_case < CamelCase < UPPER_SNAKE_CASE
707 if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) {
708 return Ordering::Greater;
710 if ia.starts_with(char::is_lowercase) && ib.starts_with(char::is_uppercase) {
711 return Ordering::Less;
713 if is_upper_snake_case(ia) && !is_upper_snake_case(ib) {
714 return Ordering::Greater;
716 if !is_upper_snake_case(ia) && is_upper_snake_case(ib) {
717 return Ordering::Less;
719 let ident_ord = ia.cmp(ib);
720 if ident_ord != Ordering::Equal {
723 if aa.is_none() && ab.is_some() {
724 return Ordering::Less;
726 if aa.is_some() && ab.is_none() {
727 return Ordering::Greater;
731 (&List(ref a), &List(ref b)) => {
732 for (a, b) in a.iter().zip(b.iter()) {
734 if ord != Ordering::Equal {
739 a.len().cmp(&b.len())
741 (&Slf(_), _) => Ordering::Less,
742 (_, &Slf(_)) => Ordering::Greater,
743 (&Super(_), _) => Ordering::Less,
744 (_, &Super(_)) => Ordering::Greater,
745 (&Crate(_), _) => Ordering::Less,
746 (_, &Crate(_)) => Ordering::Greater,
747 (&Ident(..), _) => Ordering::Less,
748 (_, &Ident(..)) => Ordering::Greater,
749 (&Glob, _) => Ordering::Less,
750 (_, &Glob) => Ordering::Greater,
754 impl Ord for UseTree {
755 fn cmp(&self, other: &UseTree) -> Ordering {
756 for (a, b) in self.path.iter().zip(other.path.iter()) {
758 // The comparison without aliases is a hack to avoid situations like
759 // comparing `a::b` to `a as c` - where the latter should be ordered
760 // first since it is shorter.
761 if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
767 self.path.len().cmp(&other.path.len())
771 fn rewrite_nested_use_tree(
772 context: &RewriteContext<'_>,
773 use_tree_list: &[UseTree],
775 ) -> Option<String> {
776 let mut list_items = Vec::with_capacity(use_tree_list.len());
777 let nested_shape = match context.config.imports_indent() {
778 IndentStyle::Block => shape
779 .block_indent(context.config.tab_spaces())
780 .with_max_width(context.config)
782 IndentStyle::Visual => shape.visual_indent(0),
784 for use_tree in use_tree_list {
785 if let Some(mut list_item) = use_tree.list_item.clone() {
786 list_item.item = use_tree.rewrite(context, nested_shape);
787 list_items.push(list_item);
789 list_items.push(ListItem::from_str(use_tree.rewrite(context, nested_shape)?));
792 let has_nested_list = use_tree_list.iter().any(|use_segment| {
796 .map_or(false, |last_segment| match last_segment {
797 UseSegment::List(..) => true,
802 let remaining_width = if has_nested_list {
805 shape.width.saturating_sub(2)
808 let tactic = definitive_tactic(
810 context.config.imports_layout(),
815 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
816 && tactic != DefinitiveListTactic::Horizontal;
817 let trailing_separator = if ends_with_newline {
818 context.config.trailing_comma()
820 SeparatorTactic::Never
822 let fmt = ListFormatting::new(nested_shape, context.config)
824 .trailing_separator(trailing_separator)
825 .ends_with_newline(ends_with_newline)
826 .preserve_newline(true)
827 .nested(has_nested_list);
829 let list_str = write_list(&list_items, &fmt)?;
831 let result = if (list_str.contains('\n') || list_str.len() > remaining_width)
832 && context.config.imports_indent() == IndentStyle::Block
836 nested_shape.indent.to_string(context.config),
838 shape.indent.to_string(context.config)
841 format!("{{{}}}", list_str)
847 impl Rewrite for UseSegment {
848 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
850 UseSegment::Ident(ref ident, Some(ref rename)) => format!("{} as {}", ident, rename),
851 UseSegment::Ident(ref ident, None) => ident.clone(),
852 UseSegment::Slf(Some(ref rename)) => format!("self as {}", rename),
853 UseSegment::Slf(None) => "self".to_owned(),
854 UseSegment::Super(Some(ref rename)) => format!("super as {}", rename),
855 UseSegment::Super(None) => "super".to_owned(),
856 UseSegment::Crate(Some(ref rename)) => format!("crate as {}", rename),
857 UseSegment::Crate(None) => "crate".to_owned(),
858 UseSegment::Glob => "*".to_owned(),
859 UseSegment::List(ref use_tree_list) => rewrite_nested_use_tree(
863 shape.offset_left(1)?.sub_width(1)?,
869 impl Rewrite for UseTree {
870 // This does NOT format attributes and visibility or add a trailing `;`.
871 fn rewrite(&self, context: &RewriteContext<'_>, mut shape: Shape) -> Option<String> {
872 let mut result = String::with_capacity(256);
873 let mut iter = self.path.iter().peekable();
874 while let Some(ref segment) = iter.next() {
875 let segment_str = segment.rewrite(context, shape)?;
876 result.push_str(&segment_str);
877 if iter.peek().is_some() {
878 result.push_str("::");
880 shape = shape.offset_left(2 + segment_str.len())?;
887 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
888 pub(crate) enum SharedPrefix {
896 use rustc_span::DUMMY_SP;
898 // Parse the path part of an import. This parser is not robust and is only
899 // suitable for use in a test harness.
900 fn parse_use_tree(s: &str) -> UseTree {
901 use std::iter::Peekable;
906 input: Peekable<Chars<'a>>,
909 impl<'a> Parser<'a> {
911 self.input.next().unwrap();
914 fn eat(&mut self, c: char) {
915 assert!(self.input.next().unwrap() == c);
919 result: &mut Vec<UseSegment>,
921 alias_buf: &mut Option<String>,
924 let mut alias = None;
925 swap(alias_buf, &mut alias);
929 result.push(UseSegment::Slf(alias));
930 *buf = String::new();
934 result.push(UseSegment::Super(alias));
935 *buf = String::new();
939 result.push(UseSegment::Crate(alias));
940 *buf = String::new();
944 let mut name = String::new();
945 swap(buf, &mut name);
946 result.push(UseSegment::Ident(name, alias));
952 fn parse_in_list(&mut self) -> UseTree {
953 let mut result = vec![];
954 let mut buf = String::new();
955 let mut alias_buf = None;
956 while let Some(&c) = self.input.peek() {
959 assert!(buf.is_empty());
961 result.push(UseSegment::List(self.parse_list()));
965 assert!(buf.is_empty());
967 result.push(UseSegment::Glob);
972 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
975 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
989 alias_buf = Some(String::new());
993 if let Some(ref mut buf) = alias_buf {
1001 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
1011 fn parse_list(&mut self) -> Vec<UseTree> {
1012 let mut result = vec![];
1014 match self.input.peek().unwrap() {
1015 ',' | ' ' => self.bump(),
1019 _ => result.push(self.parse_in_list()),
1025 let mut parser = Parser {
1026 input: s.chars().peekable(),
1028 parser.parse_in_list()
1031 macro_rules! parse_use_trees {
1032 ($($s:expr),* $(,)*) => {
1034 $(parse_use_tree($s),)*
1039 macro_rules! test_merge {
1040 ($by:ident, [$($input:expr),* $(,)*], [$($output:expr),* $(,)*]) => {
1042 merge_use_trees(parse_use_trees!($($input,)*), SharedPrefix::$by),
1043 parse_use_trees!($($output,)*),
1049 fn test_use_tree_merge_crate() {
1052 ["a::b::{c, d}", "a::b::{e, f}"],
1053 ["a::b::{c, d, e, f}"]
1055 test_merge!(Crate, ["a::b::c", "a::b"], ["a::{b, b::c}"]);
1056 test_merge!(Crate, ["a::b", "a::b"], ["a::b"]);
1057 test_merge!(Crate, ["a", "a::b", "a::b::c"], ["a::{self, b, b::c}"]);
1060 ["a", "a::b", "a::b::c", "a::b::c::d"],
1061 ["a::{self, b, b::{c, c::d}}"]
1065 ["a", "a::b", "a::b::c", "a::b"],
1066 ["a::{self, b, b::c}"]
1070 ["a::{b::{self, c}, d::e}", "a::d::f"],
1071 ["a::{b::{self, c}, d::{e, f}}"]
1075 ["a::d::f", "a::{b::{self, c}, d::e}"],
1076 ["a::{b::{self, c}, d::{e, f}}"]
1080 ["a::{c, d, b}", "a::{d, e, b, a, f}", "a::{f, g, c}"],
1081 ["a::{a, b, c, d, e, f, g}"]
1085 ["a::{self}", "b::{self as foo}"],
1086 ["a::{self}", "b::{self as foo}"]
1091 fn test_use_tree_merge_module() {
1094 ["foo::b", "foo::{a, c, d::e}"],
1095 ["foo::{a, b, c}", "foo::d::e"]
1100 ["foo::{a::b, a::c, d::e, d::f}"],
1101 ["foo::a::{b, c}", "foo::d::{e, f}"]
1106 fn test_flatten_use_trees() {
1108 flatten_use_trees(parse_use_trees!["foo::{a::{b, c}, d::e}"]),
1109 parse_use_trees!["foo::a::b", "foo::a::c", "foo::d::e"]
1113 flatten_use_trees(parse_use_trees!["foo::{self, a, b::{c, d}, e::*}"]),
1125 fn test_use_tree_flatten() {
1127 parse_use_tree("a::b::{c, d, e, f}").flatten(),
1128 parse_use_trees!("a::b::c", "a::b::d", "a::b::e", "a::b::f",)
1132 parse_use_tree("a::b::{c::{d, e, f}, g, h::{i, j, k}}").flatten(),
1146 fn test_use_tree_normalize() {
1147 assert_eq!(parse_use_tree("a::self").normalize(), parse_use_tree("a"));
1149 parse_use_tree("a::self as foo").normalize(),
1150 parse_use_tree("a as foo")
1153 parse_use_tree("a::{self}").normalize(),
1154 parse_use_tree("a::{self}")
1156 assert_eq!(parse_use_tree("a::{b}").normalize(), parse_use_tree("a::b"));
1158 parse_use_tree("a::{b, c::self}").normalize(),
1159 parse_use_tree("a::{b, c}")
1162 parse_use_tree("a::{b as bar, c::self}").normalize(),
1163 parse_use_tree("a::{b as bar, c}")
1168 fn test_use_tree_ord() {
1169 assert!(parse_use_tree("a").normalize() < parse_use_tree("aa").normalize());
1170 assert!(parse_use_tree("a").normalize() < parse_use_tree("a::a").normalize());
1171 assert!(parse_use_tree("a").normalize() < parse_use_tree("*").normalize());
1172 assert!(parse_use_tree("a").normalize() < parse_use_tree("{a, b}").normalize());
1173 assert!(parse_use_tree("*").normalize() < parse_use_tree("{a, b}").normalize());
1176 parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, dddddddd}").normalize()
1177 < parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, ddddddddd}").normalize()
1180 parse_use_tree("serde::de::{Deserialize}").normalize()
1181 < parse_use_tree("serde_json").normalize()
1183 assert!(parse_use_tree("a::b::c").normalize() < parse_use_tree("a::b::*").normalize());
1185 parse_use_tree("foo::{Bar, Baz}").normalize()
1186 < parse_use_tree("{Bar, Baz}").normalize()
1190 parse_use_tree("foo::{qux as bar}").normalize()
1191 < parse_use_tree("foo::{self as bar}").normalize()
1194 parse_use_tree("foo::{qux as bar}").normalize()
1195 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1198 parse_use_tree("foo::{self as bar, baz}").normalize()
1199 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1202 assert!(parse_use_tree("foo").normalize() < parse_use_tree("Foo").normalize());
1203 assert!(parse_use_tree("foo").normalize() < parse_use_tree("foo::Bar").normalize());
1206 parse_use_tree("std::cmp::{d, c, b, a}").normalize()
1207 < parse_use_tree("std::cmp::{b, e, g, f}").normalize()