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 impl fmt::Debug for UseTree {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 fmt::Display::fmt(self, f)
190 impl fmt::Debug for UseSegment {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 fmt::Display::fmt(self, f)
196 impl fmt::Display for UseSegment {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 UseSegment::Glob => write!(f, "*"),
200 UseSegment::Ident(ref s, _) => write!(f, "{}", s),
201 UseSegment::Slf(..) => write!(f, "self"),
202 UseSegment::Super(..) => write!(f, "super"),
203 UseSegment::Crate(..) => write!(f, "crate"),
204 UseSegment::List(ref list) => {
206 for (i, item) in list.iter().enumerate() {
210 write!(f, "{}", item)?;
217 impl fmt::Display for UseTree {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 for (i, segment) in self.path.iter().enumerate() {
223 write!(f, "{}", segment)?;
230 // Rewrite use tree with `use ` and a trailing `;`.
231 pub(crate) fn rewrite_top_level(
233 context: &RewriteContext<'_>,
235 ) -> Option<String> {
236 let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
237 crate::utils::format_visibility(context, &vis)
240 .rewrite(context, shape.offset_left(vis.len())?)
245 format!("{}use {};", vis, s)
249 Some(ref attrs) if !attrs.is_empty() => {
250 let attr_str = attrs.rewrite(context, shape)?;
251 let lo = attrs.last().as_ref()?.span.hi();
252 let hi = self.span.lo();
253 let span = mk_sp(lo, hi);
255 let allow_extend = if attrs.len() == 1 {
256 let line_len = attr_str.len() + 1 + use_str.len();
257 !attrs.first().unwrap().is_doc_comment()
258 && context.config.inline_attribute_width() >= line_len
263 combine_strs_with_missing_comments(
276 // FIXME: Use correct span?
277 // The given span is essentially incorrect, since we are reconstructing
278 // use-statements. This should not be a problem, though, since we have
279 // already tried to extract comment and observed that there are no comment
280 // around the given use item, and the span will not be used afterward.
281 fn from_path(path: Vec<UseSegment>, span: Span) -> UseTree {
291 pub(crate) fn from_ast_with_normalization(
292 context: &RewriteContext<'_>,
294 ) -> Option<UseTree> {
296 ast::ItemKind::Use(ref use_tree) => Some(
301 Some(item.vis.clone()),
302 Some(item.span.lo()),
303 if item.attrs.is_empty() {
306 Some(item.attrs.clone())
316 context: &RewriteContext<'_>,
318 list_item: Option<ListItem>,
319 visibility: Option<ast::Visibility>,
320 opt_lo: Option<BytePos>,
321 attrs: Option<Vec<ast::Attribute>>,
323 let span = if let Some(lo) = opt_lo {
324 mk_sp(lo, a.span.hi())
328 let mut result = UseTree {
337 context.config.edition() >= Edition::Edition2018 && a.prefix.is_global();
339 let mut modsep = leading_modsep;
341 for p in &a.prefix.segments {
342 if let Some(use_segment) = UseSegment::from_path_segment(context, p, modsep) {
343 result.path.push(use_segment);
349 UseTreeKind::Glob => {
350 // in case of a global path and the glob starts at the root, e.g., "::*"
351 if a.prefix.segments.len() == 1 && leading_modsep {
352 result.path.push(UseSegment::Ident("".to_owned(), None));
354 result.path.push(UseSegment::Glob);
356 UseTreeKind::Nested(ref list) => {
357 // Extract comments between nested use items.
358 // This needs to be done before sorting use items.
359 let items: Vec<_> = itemize_list(
360 context.snippet_provider,
361 list.iter().map(|(tree, _)| tree),
364 |tree| tree.span.lo(),
365 |tree| tree.span.hi(),
366 |_| Some("".to_owned()), // We only need comments for now.
367 context.snippet_provider.span_after(a.span, "{"),
372 // in case of a global path and the nested list starts at the root,
373 // e.g., "::{foo, bar}"
374 if a.prefix.segments.len() == 1 && leading_modsep {
375 result.path.push(UseSegment::Ident("".to_owned(), None));
377 result.path.push(UseSegment::List(
379 .zip(items.into_iter())
380 .map(|(t, list_item)| {
381 Self::from_ast(context, &t.0, Some(list_item), None, None, None)
386 UseTreeKind::Simple(ref rename, ..) => {
387 // If the path has leading double colons and is composed of only 2 segments, then we
388 // bypass the call to path_to_imported_ident which would get only the ident and
389 // lose the path root, e.g., `that` in `::that`.
390 // The span of `a.prefix` contains the leading colons.
391 let name = if a.prefix.segments.len() == 2 && leading_modsep {
392 context.snippet(a.prefix.span).to_owned()
394 rewrite_ident(context, path_to_imported_ident(&a.prefix)).to_owned()
396 let alias = rename.and_then(|ident| {
397 if ident.name == sym::underscore_imports {
400 } else if ident == path_to_imported_ident(&a.prefix) {
403 Some(rewrite_ident(context, ident).to_owned())
406 let segment = match name.as_ref() {
407 "self" => UseSegment::Slf(alias),
408 "super" => UseSegment::Super(alias),
409 "crate" => UseSegment::Crate(alias),
410 _ => UseSegment::Ident(name, alias),
413 // `name` is already in result.
415 result.path.push(segment);
421 // Do the adjustments that rustfmt does elsewhere to use paths.
422 pub(crate) fn normalize(mut self) -> UseTree {
423 let mut last = self.path.pop().expect("Empty use tree?");
424 // Hack around borrow checker.
425 let mut normalize_sole_list = false;
426 let mut aliased_self = false;
428 // Remove foo::{} or self without attributes.
430 _ if self.attrs.is_some() => (),
431 UseSegment::List(ref list) if list.is_empty() => {
435 UseSegment::Slf(None) if self.path.is_empty() && self.visibility.is_some() => {
442 // Normalise foo::self -> foo.
443 if let UseSegment::Slf(None) = last {
444 if !self.path.is_empty() {
449 // Normalise foo::self as bar -> foo as bar.
450 if let UseSegment::Slf(_) = last {
451 match self.path.last() {
452 Some(UseSegment::Ident(_, None)) => {
459 let mut done = false;
461 match self.path.last_mut() {
462 Some(UseSegment::Ident(_, ref mut old_rename)) => {
463 assert!(old_rename.is_none());
464 if let UseSegment::Slf(Some(rename)) = last.clone() {
465 *old_rename = Some(rename);
477 // Normalise foo::{bar} -> foo::bar
478 if let UseSegment::List(ref list) = last {
479 if list.len() == 1 && list[0].to_string() != "self" {
480 normalize_sole_list = true;
484 if normalize_sole_list {
486 UseSegment::List(list) => {
487 for seg in &list[0].path {
488 self.path.push(seg.clone());
490 return self.normalize();
496 // Recursively normalize elements of a list use (including sorting the list).
497 if let UseSegment::List(list) = last {
498 let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
500 last = UseSegment::List(list);
503 self.path.push(last);
507 fn has_comment(&self) -> bool {
508 self.list_item.as_ref().map_or(false, ListItem::has_comment)
511 fn same_visibility(&self, other: &UseTree) -> bool {
512 match (&self.visibility, &other.visibility) {
514 Some(ast::Visibility {
515 kind: ast::VisibilityKind::Inherited,
522 Some(ast::Visibility {
523 kind: ast::VisibilityKind::Inherited,
527 | (None, None) => true,
528 (Some(ref a), Some(ref b)) => is_same_visibility(a, b),
533 fn share_prefix(&self, other: &UseTree, shared_prefix: SharedPrefix) -> bool {
534 if self.path.is_empty()
535 || other.path.is_empty()
536 || self.attrs.is_some()
537 || !self.same_visibility(other)
541 match shared_prefix {
542 SharedPrefix::Crate => self.path[0] == other.path[0],
543 SharedPrefix::Module => {
544 self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
550 fn flatten(self) -> Vec<UseTree> {
551 if self.path.is_empty() {
554 match self.path.clone().last().unwrap() {
555 UseSegment::List(list) => {
556 if list.len() == 1 && list[0].path.len() == 1 {
557 match list[0].path[0] {
558 UseSegment::Slf(..) => return vec![self],
562 let prefix = &self.path[..self.path.len() - 1];
563 let mut result = vec![];
564 for nested_use_tree in list {
565 for flattend in &mut nested_use_tree.clone().flatten() {
566 let mut new_path = prefix.to_vec();
567 new_path.append(&mut flattend.path);
568 result.push(UseTree {
572 visibility: self.visibility.clone(),
584 fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
586 for (a, b) in self.path.iter().zip(other.path.iter()) {
593 if let Some(new_path) = merge_rest(&self.path, &other.path, prefix, merge_by) {
594 self.path = new_path;
595 self.span = self.span.to(other.span);
604 merge_by: SharedPrefix,
605 ) -> Option<Vec<UseSegment>> {
606 if a.len() == len && b.len() == len {
609 if a.len() != len && b.len() != len {
610 if let UseSegment::List(ref list) = a[len] {
611 let mut list = list.clone();
612 merge_use_trees_inner(
614 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
617 let mut new_path = b[..len].to_vec();
618 new_path.push(UseSegment::List(list));
619 return Some(new_path);
622 let rest = if a.len() == len { &b[1..] } else { &a[1..] };
625 UseSegment::List(vec![
626 UseTree::from_path(vec![UseSegment::Slf(None)], DUMMY_SP),
627 UseTree::from_path(rest.to_vec(), DUMMY_SP),
634 UseTree::from_path(a[len..].to_vec(), DUMMY_SP),
635 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
638 let mut new_path = b[..len].to_vec();
639 new_path.push(UseSegment::List(list));
643 fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
644 let similar_trees = trees
646 .filter(|tree| tree.share_prefix(&use_tree, merge_by));
647 if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
648 if let Some(tree) = similar_trees.min_by_key(|tree| tree.path.len()) {
649 if tree.path.len() == 1 {
653 } else if let Some(tree) = similar_trees.max_by_key(|tree| tree.path.len()) {
654 if tree.path.len() > 1 {
655 tree.merge(&use_tree, merge_by);
659 trees.push(use_tree);
663 impl PartialOrd for UseSegment {
664 fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
665 Some(self.cmp(other))
668 impl PartialOrd for UseTree {
669 fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
670 Some(self.cmp(other))
673 impl Ord for UseSegment {
674 fn cmp(&self, other: &UseSegment) -> Ordering {
675 use self::UseSegment::*;
677 fn is_upper_snake_case(s: &str) -> bool {
679 .all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
682 match (self, other) {
683 (&Slf(ref a), &Slf(ref b))
684 | (&Super(ref a), &Super(ref b))
685 | (&Crate(ref a), &Crate(ref b)) => a.cmp(b),
686 (&Glob, &Glob) => Ordering::Equal,
687 (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => {
688 // snake_case < CamelCase < UPPER_SNAKE_CASE
689 if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) {
690 return Ordering::Greater;
692 if ia.starts_with(char::is_lowercase) && ib.starts_with(char::is_uppercase) {
693 return Ordering::Less;
695 if is_upper_snake_case(ia) && !is_upper_snake_case(ib) {
696 return Ordering::Greater;
698 if !is_upper_snake_case(ia) && is_upper_snake_case(ib) {
699 return Ordering::Less;
701 let ident_ord = ia.cmp(ib);
702 if ident_ord != Ordering::Equal {
705 if aa.is_none() && ab.is_some() {
706 return Ordering::Less;
708 if aa.is_some() && ab.is_none() {
709 return Ordering::Greater;
713 (&List(ref a), &List(ref b)) => {
714 for (a, b) in a.iter().zip(b.iter()) {
716 if ord != Ordering::Equal {
721 a.len().cmp(&b.len())
723 (&Slf(_), _) => Ordering::Less,
724 (_, &Slf(_)) => Ordering::Greater,
725 (&Super(_), _) => Ordering::Less,
726 (_, &Super(_)) => Ordering::Greater,
727 (&Crate(_), _) => Ordering::Less,
728 (_, &Crate(_)) => Ordering::Greater,
729 (&Ident(..), _) => Ordering::Less,
730 (_, &Ident(..)) => Ordering::Greater,
731 (&Glob, _) => Ordering::Less,
732 (_, &Glob) => Ordering::Greater,
736 impl Ord for UseTree {
737 fn cmp(&self, other: &UseTree) -> Ordering {
738 for (a, b) in self.path.iter().zip(other.path.iter()) {
740 // The comparison without aliases is a hack to avoid situations like
741 // comparing `a::b` to `a as c` - where the latter should be ordered
742 // first since it is shorter.
743 if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
749 self.path.len().cmp(&other.path.len())
753 fn rewrite_nested_use_tree(
754 context: &RewriteContext<'_>,
755 use_tree_list: &[UseTree],
757 ) -> Option<String> {
758 let mut list_items = Vec::with_capacity(use_tree_list.len());
759 let nested_shape = match context.config.imports_indent() {
760 IndentStyle::Block => shape
761 .block_indent(context.config.tab_spaces())
762 .with_max_width(context.config)
764 IndentStyle::Visual => shape.visual_indent(0),
766 for use_tree in use_tree_list {
767 if let Some(mut list_item) = use_tree.list_item.clone() {
768 list_item.item = use_tree.rewrite(context, nested_shape);
769 list_items.push(list_item);
771 list_items.push(ListItem::from_str(use_tree.rewrite(context, nested_shape)?));
774 let has_nested_list = use_tree_list.iter().any(|use_segment| {
778 .map_or(false, |last_segment| match last_segment {
779 UseSegment::List(..) => true,
784 let remaining_width = if has_nested_list {
787 shape.width.saturating_sub(2)
790 let tactic = definitive_tactic(
792 context.config.imports_layout(),
797 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
798 && tactic != DefinitiveListTactic::Horizontal;
799 let trailing_separator = if ends_with_newline {
800 context.config.trailing_comma()
802 SeparatorTactic::Never
804 let fmt = ListFormatting::new(nested_shape, context.config)
806 .trailing_separator(trailing_separator)
807 .ends_with_newline(ends_with_newline)
808 .preserve_newline(true)
809 .nested(has_nested_list);
811 let list_str = write_list(&list_items, &fmt)?;
813 let result = if (list_str.contains('\n') || list_str.len() > remaining_width)
814 && context.config.imports_indent() == IndentStyle::Block
818 nested_shape.indent.to_string(context.config),
820 shape.indent.to_string(context.config)
823 format!("{{{}}}", list_str)
829 impl Rewrite for UseSegment {
830 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
832 UseSegment::Ident(ref ident, Some(ref rename)) => format!("{} as {}", ident, rename),
833 UseSegment::Ident(ref ident, None) => ident.clone(),
834 UseSegment::Slf(Some(ref rename)) => format!("self as {}", rename),
835 UseSegment::Slf(None) => "self".to_owned(),
836 UseSegment::Super(Some(ref rename)) => format!("super as {}", rename),
837 UseSegment::Super(None) => "super".to_owned(),
838 UseSegment::Crate(Some(ref rename)) => format!("crate as {}", rename),
839 UseSegment::Crate(None) => "crate".to_owned(),
840 UseSegment::Glob => "*".to_owned(),
841 UseSegment::List(ref use_tree_list) => rewrite_nested_use_tree(
845 shape.offset_left(1)?.sub_width(1)?,
851 impl Rewrite for UseTree {
852 // This does NOT format attributes and visibility or add a trailing `;`.
853 fn rewrite(&self, context: &RewriteContext<'_>, mut shape: Shape) -> Option<String> {
854 let mut result = String::with_capacity(256);
855 let mut iter = self.path.iter().peekable();
856 while let Some(ref segment) = iter.next() {
857 let segment_str = segment.rewrite(context, shape)?;
858 result.push_str(&segment_str);
859 if iter.peek().is_some() {
860 result.push_str("::");
862 shape = shape.offset_left(2 + segment_str.len())?;
869 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
870 pub(crate) enum SharedPrefix {
878 use rustc_span::DUMMY_SP;
880 // Parse the path part of an import. This parser is not robust and is only
881 // suitable for use in a test harness.
882 fn parse_use_tree(s: &str) -> UseTree {
883 use std::iter::Peekable;
888 input: Peekable<Chars<'a>>,
891 impl<'a> Parser<'a> {
893 self.input.next().unwrap();
896 fn eat(&mut self, c: char) {
897 assert!(self.input.next().unwrap() == c);
901 result: &mut Vec<UseSegment>,
903 alias_buf: &mut Option<String>,
906 let mut alias = None;
907 swap(alias_buf, &mut alias);
911 result.push(UseSegment::Slf(alias));
912 *buf = String::new();
916 result.push(UseSegment::Super(alias));
917 *buf = String::new();
921 result.push(UseSegment::Crate(alias));
922 *buf = String::new();
926 let mut name = String::new();
927 swap(buf, &mut name);
928 result.push(UseSegment::Ident(name, alias));
934 fn parse_in_list(&mut self) -> UseTree {
935 let mut result = vec![];
936 let mut buf = String::new();
937 let mut alias_buf = None;
938 while let Some(&c) = self.input.peek() {
941 assert!(buf.is_empty());
943 result.push(UseSegment::List(self.parse_list()));
947 assert!(buf.is_empty());
949 result.push(UseSegment::Glob);
954 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
957 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
971 alias_buf = Some(String::new());
975 if let Some(ref mut buf) = alias_buf {
983 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
993 fn parse_list(&mut self) -> Vec<UseTree> {
994 let mut result = vec![];
996 match self.input.peek().unwrap() {
997 ',' | ' ' => self.bump(),
1001 _ => result.push(self.parse_in_list()),
1007 let mut parser = Parser {
1008 input: s.chars().peekable(),
1010 parser.parse_in_list()
1013 macro_rules! parse_use_trees {
1014 ($($s:expr),* $(,)*) => {
1016 $(parse_use_tree($s),)*
1021 macro_rules! test_merge {
1022 ($by:ident, [$($input:expr),* $(,)*], [$($output:expr),* $(,)*]) => {
1024 merge_use_trees(parse_use_trees!($($input,)*), SharedPrefix::$by),
1025 parse_use_trees!($($output,)*),
1031 fn test_use_tree_merge_crate() {
1034 ["a::b::{c, d}", "a::b::{e, f}"],
1035 ["a::b::{c, d, e, f}"]
1037 test_merge!(Crate, ["a::b::c", "a::b"], ["a::{b, b::c}"]);
1038 test_merge!(Crate, ["a::b", "a::b"], ["a::b"]);
1039 test_merge!(Crate, ["a", "a::b", "a::b::c"], ["a::{self, b, b::c}"]);
1042 ["a", "a::b", "a::b::c", "a::b::c::d"],
1043 ["a::{self, b, b::{c, c::d}}"]
1047 ["a", "a::b", "a::b::c", "a::b"],
1048 ["a::{self, b, b::c}"]
1052 ["a::{b::{self, c}, d::e}", "a::d::f"],
1053 ["a::{b::{self, c}, d::{e, f}}"]
1057 ["a::d::f", "a::{b::{self, c}, d::e}"],
1058 ["a::{b::{self, c}, d::{e, f}}"]
1062 ["a::{c, d, b}", "a::{d, e, b, a, f}", "a::{f, g, c}"],
1063 ["a::{a, b, c, d, e, f, g}"]
1067 ["a::{self}", "b::{self as foo}"],
1068 ["a::{self}", "b::{self as foo}"]
1073 fn test_use_tree_merge_module() {
1076 ["foo::b", "foo::{a, c, d::e}"],
1077 ["foo::{a, b, c}", "foo::d::e"]
1082 ["foo::{a::b, a::c, d::e, d::f}"],
1083 ["foo::a::{b, c}", "foo::d::{e, f}"]
1088 fn test_use_tree_flatten() {
1090 parse_use_tree("a::b::{c, d, e, f}").flatten(),
1091 parse_use_trees!("a::b::c", "a::b::d", "a::b::e", "a::b::f",)
1095 parse_use_tree("a::b::{c::{d, e, f}, g, h::{i, j, k}}").flatten(),
1109 fn test_use_tree_normalize() {
1110 assert_eq!(parse_use_tree("a::self").normalize(), parse_use_tree("a"));
1112 parse_use_tree("a::self as foo").normalize(),
1113 parse_use_tree("a as foo")
1116 parse_use_tree("a::{self}").normalize(),
1117 parse_use_tree("a::{self}")
1119 assert_eq!(parse_use_tree("a::{b}").normalize(), parse_use_tree("a::b"));
1121 parse_use_tree("a::{b, c::self}").normalize(),
1122 parse_use_tree("a::{b, c}")
1125 parse_use_tree("a::{b as bar, c::self}").normalize(),
1126 parse_use_tree("a::{b as bar, c}")
1131 fn test_use_tree_ord() {
1132 assert!(parse_use_tree("a").normalize() < parse_use_tree("aa").normalize());
1133 assert!(parse_use_tree("a").normalize() < parse_use_tree("a::a").normalize());
1134 assert!(parse_use_tree("a").normalize() < parse_use_tree("*").normalize());
1135 assert!(parse_use_tree("a").normalize() < parse_use_tree("{a, b}").normalize());
1136 assert!(parse_use_tree("*").normalize() < parse_use_tree("{a, b}").normalize());
1139 parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, dddddddd}").normalize()
1140 < parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, ddddddddd}").normalize()
1143 parse_use_tree("serde::de::{Deserialize}").normalize()
1144 < parse_use_tree("serde_json").normalize()
1146 assert!(parse_use_tree("a::b::c").normalize() < parse_use_tree("a::b::*").normalize());
1148 parse_use_tree("foo::{Bar, Baz}").normalize()
1149 < parse_use_tree("{Bar, Baz}").normalize()
1153 parse_use_tree("foo::{qux as bar}").normalize()
1154 < parse_use_tree("foo::{self as bar}").normalize()
1157 parse_use_tree("foo::{qux as bar}").normalize()
1158 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1161 parse_use_tree("foo::{self as bar, baz}").normalize()
1162 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1165 assert!(parse_use_tree("foo").normalize() < parse_use_tree("Foo").normalize());
1166 assert!(parse_use_tree("foo").normalize() < parse_use_tree("foo::Bar").normalize());
1169 parse_use_tree("std::cmp::{d, c, b, a}").normalize()
1170 < parse_use_tree("std::cmp::{b, e, g, f}").normalize()