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 // Check if self == other with their aliases removed.
142 fn equal_except_alias(&self, other: &Self) -> bool {
143 match (self, other) {
144 (UseSegment::Ident(ref s1, _), UseSegment::Ident(ref s2, _)) => s1 == s2,
145 (UseSegment::Slf(_), UseSegment::Slf(_))
146 | (UseSegment::Super(_), UseSegment::Super(_))
147 | (UseSegment::Crate(_), UseSegment::Crate(_))
148 | (UseSegment::Glob, UseSegment::Glob) => true,
149 (UseSegment::List(ref list1), UseSegment::List(ref list2)) => list1 == list2,
154 fn get_alias(&self) -> Option<&str> {
156 UseSegment::Ident(_, a)
158 | UseSegment::Super(a)
159 | UseSegment::Crate(a) => a.as_deref(),
164 fn from_path_segment(
165 context: &RewriteContext<'_>,
166 path_seg: &ast::PathSegment,
168 ) -> Option<UseSegment> {
169 let name = rewrite_ident(context, path_seg.ident);
170 if name.is_empty() || name == "{{root}}" {
174 "self" => UseSegment::Slf(None),
175 "super" => UseSegment::Super(None),
176 "crate" => UseSegment::Crate(None),
178 let mod_sep = if modsep { "::" } else { "" };
179 UseSegment::Ident(format!("{}{}", mod_sep, name), None)
185 pub(crate) fn merge_use_trees(use_trees: Vec<UseTree>, merge_by: SharedPrefix) -> Vec<UseTree> {
186 let mut result = Vec::with_capacity(use_trees.len());
187 for use_tree in use_trees {
188 if use_tree.has_comment() || use_tree.attrs.is_some() {
189 result.push(use_tree);
193 for flattened in use_tree.flatten() {
194 if let Some(tree) = result
196 .find(|tree| tree.share_prefix(&flattened, merge_by))
198 tree.merge(&flattened, merge_by);
200 result.push(flattened);
207 pub(crate) fn flatten_use_trees(use_trees: Vec<UseTree>) -> Vec<UseTree> {
210 .flat_map(UseTree::flatten)
212 // If a path ends in `::self`, rewrite it to `::{self}`.
213 if let Some(UseSegment::Slf(..)) = tree.path.last() {
214 let self_segment = tree.path.pop().unwrap();
215 tree.path.push(UseSegment::List(vec![UseTree::from_path(
225 impl fmt::Debug for UseTree {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 fmt::Display::fmt(self, f)
231 impl fmt::Debug for UseSegment {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 fmt::Display::fmt(self, f)
237 impl fmt::Display for UseSegment {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 UseSegment::Glob => write!(f, "*"),
241 UseSegment::Ident(ref s, _) => write!(f, "{}", s),
242 UseSegment::Slf(..) => write!(f, "self"),
243 UseSegment::Super(..) => write!(f, "super"),
244 UseSegment::Crate(..) => write!(f, "crate"),
245 UseSegment::List(ref list) => {
247 for (i, item) in list.iter().enumerate() {
251 write!(f, "{}", item)?;
258 impl fmt::Display for UseTree {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 for (i, segment) in self.path.iter().enumerate() {
264 write!(f, "{}", segment)?;
271 // Rewrite use tree with `use ` and a trailing `;`.
272 pub(crate) fn rewrite_top_level(
274 context: &RewriteContext<'_>,
276 ) -> Option<String> {
277 let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
278 crate::utils::format_visibility(context, vis)
281 .rewrite(context, shape.offset_left(vis.len())?)
286 format!("{}use {};", vis, s)
290 Some(ref attrs) if !attrs.is_empty() => {
291 let attr_str = attrs.rewrite(context, shape)?;
292 let lo = attrs.last().as_ref()?.span.hi();
293 let hi = self.span.lo();
294 let span = mk_sp(lo, hi);
296 let allow_extend = if attrs.len() == 1 {
297 let line_len = attr_str.len() + 1 + use_str.len();
298 !attrs.first().unwrap().is_doc_comment()
299 && context.config.inline_attribute_width() >= line_len
304 combine_strs_with_missing_comments(
317 // FIXME: Use correct span?
318 // The given span is essentially incorrect, since we are reconstructing
319 // use-statements. This should not be a problem, though, since we have
320 // already tried to extract comment and observed that there are no comment
321 // around the given use item, and the span will not be used afterward.
322 fn from_path(path: Vec<UseSegment>, span: Span) -> UseTree {
332 pub(crate) fn from_ast_with_normalization(
333 context: &RewriteContext<'_>,
335 ) -> Option<UseTree> {
337 ast::ItemKind::Use(ref use_tree) => Some(
342 Some(item.vis.clone()),
343 Some(item.span.lo()),
344 if item.attrs.is_empty() {
347 Some(item.attrs.clone())
357 context: &RewriteContext<'_>,
359 list_item: Option<ListItem>,
360 visibility: Option<ast::Visibility>,
361 opt_lo: Option<BytePos>,
362 attrs: Option<Vec<ast::Attribute>>,
364 let span = if let Some(lo) = opt_lo {
365 mk_sp(lo, a.span.hi())
369 let mut result = UseTree {
378 context.config.edition() >= Edition::Edition2018 && a.prefix.is_global();
380 let mut modsep = leading_modsep;
382 for p in &a.prefix.segments {
383 if let Some(use_segment) = UseSegment::from_path_segment(context, p, modsep) {
384 result.path.push(use_segment);
390 UseTreeKind::Glob => {
391 // in case of a global path and the glob starts at the root, e.g., "::*"
392 if a.prefix.segments.len() == 1 && leading_modsep {
393 result.path.push(UseSegment::Ident("".to_owned(), None));
395 result.path.push(UseSegment::Glob);
397 UseTreeKind::Nested(ref list) => {
398 // Extract comments between nested use items.
399 // This needs to be done before sorting use items.
400 let items = itemize_list(
401 context.snippet_provider,
402 list.iter().map(|(tree, _)| tree),
405 |tree| tree.span.lo(),
406 |tree| tree.span.hi(),
407 |_| Some("".to_owned()), // We only need comments for now.
408 context.snippet_provider.span_after(a.span, "{"),
413 // in case of a global path and the nested list starts at the root,
414 // e.g., "::{foo, bar}"
415 if a.prefix.segments.len() == 1 && leading_modsep {
416 result.path.push(UseSegment::Ident("".to_owned(), None));
418 result.path.push(UseSegment::List(
421 .map(|(t, list_item)| {
422 Self::from_ast(context, &t.0, Some(list_item), None, None, None)
427 UseTreeKind::Simple(ref rename, ..) => {
428 // If the path has leading double colons and is composed of only 2 segments, then we
429 // bypass the call to path_to_imported_ident which would get only the ident and
430 // lose the path root, e.g., `that` in `::that`.
431 // The span of `a.prefix` contains the leading colons.
432 let name = if a.prefix.segments.len() == 2 && leading_modsep {
433 context.snippet(a.prefix.span).to_owned()
435 rewrite_ident(context, path_to_imported_ident(&a.prefix)).to_owned()
437 let alias = rename.and_then(|ident| {
438 if ident.name == sym::underscore_imports {
441 } else if ident == path_to_imported_ident(&a.prefix) {
444 Some(rewrite_ident(context, ident).to_owned())
447 let segment = match name.as_ref() {
448 "self" => UseSegment::Slf(alias),
449 "super" => UseSegment::Super(alias),
450 "crate" => UseSegment::Crate(alias),
451 _ => UseSegment::Ident(name, alias),
454 // `name` is already in result.
456 result.path.push(segment);
462 // Do the adjustments that rustfmt does elsewhere to use paths.
463 pub(crate) fn normalize(mut self) -> UseTree {
464 let mut last = self.path.pop().expect("Empty use tree?");
465 // Hack around borrow checker.
466 let mut normalize_sole_list = false;
467 let mut aliased_self = false;
469 // Remove foo::{} or self without attributes.
471 _ if self.attrs.is_some() => (),
472 UseSegment::List(ref list) if list.is_empty() => {
476 UseSegment::Slf(None) if self.path.is_empty() && self.visibility.is_some() => {
483 // Normalise foo::self -> foo.
484 if let UseSegment::Slf(None) = last {
485 if !self.path.is_empty() {
490 // Normalise foo::self as bar -> foo as bar.
491 if let UseSegment::Slf(_) = last {
492 if let Some(UseSegment::Ident(_, None)) = self.path.last() {
497 let mut done = false;
499 match self.path.last_mut() {
500 Some(UseSegment::Ident(_, ref mut old_rename)) => {
501 assert!(old_rename.is_none());
502 if let UseSegment::Slf(Some(rename)) = last.clone() {
503 *old_rename = Some(rename);
515 // Normalise foo::{bar} -> foo::bar
516 if let UseSegment::List(ref list) = last {
517 if list.len() == 1 && list[0].to_string() != "self" {
518 normalize_sole_list = true;
522 if normalize_sole_list {
524 UseSegment::List(list) => {
525 for seg in &list[0].path {
526 self.path.push(seg.clone());
528 return self.normalize();
534 // Recursively normalize elements of a list use (including sorting the list).
535 if let UseSegment::List(list) = last {
536 let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
538 last = UseSegment::List(list);
541 self.path.push(last);
545 fn has_comment(&self) -> bool {
546 self.list_item.as_ref().map_or(false, ListItem::has_comment)
549 fn same_visibility(&self, other: &UseTree) -> bool {
550 match (&self.visibility, &other.visibility) {
552 Some(ast::Visibility {
553 kind: ast::VisibilityKind::Inherited,
560 Some(ast::Visibility {
561 kind: ast::VisibilityKind::Inherited,
565 | (None, None) => true,
566 (Some(ref a), Some(ref b)) => is_same_visibility(a, b),
571 fn share_prefix(&self, other: &UseTree, shared_prefix: SharedPrefix) -> bool {
572 if self.path.is_empty()
573 || other.path.is_empty()
574 || self.attrs.is_some()
575 || !self.same_visibility(other)
579 match shared_prefix {
580 SharedPrefix::Crate => self.path[0] == other.path[0],
581 SharedPrefix::Module => {
582 self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
584 SharedPrefix::One => true,
589 fn flatten(self) -> Vec<UseTree> {
590 if self.path.is_empty() {
593 match self.path.clone().last().unwrap() {
594 UseSegment::List(list) => {
595 if list.len() == 1 && list[0].path.len() == 1 {
596 if let UseSegment::Slf(..) = list[0].path[0] {
600 let prefix = &self.path[..self.path.len() - 1];
601 let mut result = vec![];
602 for nested_use_tree in list {
603 for flattend in &mut nested_use_tree.clone().flatten() {
604 let mut new_path = prefix.to_vec();
605 new_path.append(&mut flattend.path);
606 result.push(UseTree {
610 visibility: self.visibility.clone(),
622 fn merge(&mut self, other: &UseTree, merge_by: SharedPrefix) {
624 for (a, b) in self.path.iter().zip(other.path.iter()) {
625 if a.equal_except_alias(b) {
631 if let Some(new_path) = merge_rest(&self.path, &other.path, prefix, merge_by) {
632 self.path = new_path;
633 self.span = self.span.to(other.span);
642 merge_by: SharedPrefix,
643 ) -> Option<Vec<UseSegment>> {
644 if a.len() == len && b.len() == len {
647 if a.len() != len && b.len() != len {
648 if let UseSegment::List(ref list) = a[len] {
649 let mut list = list.clone();
650 merge_use_trees_inner(
652 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
655 let mut new_path = b[..len].to_vec();
656 new_path.push(UseSegment::List(list));
657 return Some(new_path);
660 let (common, rest) = if a.len() == len {
665 let mut list = vec![UseTree::from_path(
666 vec![UseSegment::Slf(common.get_alias().map(ToString::to_string))],
670 [UseSegment::List(rest_list)] => list.extend(rest_list.clone()),
671 _ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)),
673 return Some(vec![b[0].clone(), UseSegment::List(list)]);
678 UseTree::from_path(a[len..].to_vec(), DUMMY_SP),
679 UseTree::from_path(b[len..].to_vec(), DUMMY_SP),
682 let mut new_path = b[..len].to_vec();
683 new_path.push(UseSegment::List(list));
687 fn merge_use_trees_inner(trees: &mut Vec<UseTree>, use_tree: UseTree, merge_by: SharedPrefix) {
688 struct SimilarTree<'a> {
691 tree: &'a mut UseTree,
694 let similar_trees = trees.iter_mut().filter_map(|tree| {
695 if tree.share_prefix(&use_tree, merge_by) {
696 // In the case of `SharedPrefix::One`, `similarity` is used for deciding with which
697 // tree `use_tree` should be merge.
698 // In other cases `similarity` won't be used, so set it to `0` as a dummy value.
699 let similarity = if merge_by == SharedPrefix::One {
703 .take_while(|(a, b)| a.equal_except_alias(b))
709 let path_len = tree.path.len();
720 if use_tree.path.len() == 1 && merge_by == SharedPrefix::Crate {
721 if let Some(tree) = similar_trees.min_by_key(|tree| tree.path_len) {
722 if tree.path_len == 1 {
726 } else if merge_by == SharedPrefix::One {
727 if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.similarity) {
728 if sim_tree.similarity > 0 {
729 sim_tree.tree.merge(&use_tree, merge_by);
733 } else if let Some(sim_tree) = similar_trees.max_by_key(|tree| tree.path_len) {
734 if sim_tree.path_len > 1 {
735 sim_tree.tree.merge(&use_tree, merge_by);
739 trees.push(use_tree);
743 impl PartialOrd for UseSegment {
744 fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
745 Some(self.cmp(other))
748 impl PartialOrd for UseTree {
749 fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
750 Some(self.cmp(other))
753 impl Ord for UseSegment {
754 fn cmp(&self, other: &UseSegment) -> Ordering {
755 use self::UseSegment::*;
757 fn is_upper_snake_case(s: &str) -> bool {
759 .all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
762 match (self, other) {
763 (&Slf(ref a), &Slf(ref b))
764 | (&Super(ref a), &Super(ref b))
765 | (&Crate(ref a), &Crate(ref b)) => a.cmp(b),
766 (&Glob, &Glob) => Ordering::Equal,
767 (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => {
768 // snake_case < CamelCase < UPPER_SNAKE_CASE
769 if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) {
770 return Ordering::Greater;
772 if ia.starts_with(char::is_lowercase) && ib.starts_with(char::is_uppercase) {
773 return Ordering::Less;
775 if is_upper_snake_case(ia) && !is_upper_snake_case(ib) {
776 return Ordering::Greater;
778 if !is_upper_snake_case(ia) && is_upper_snake_case(ib) {
779 return Ordering::Less;
781 let ident_ord = ia.cmp(ib);
782 if ident_ord != Ordering::Equal {
785 if aa.is_none() && ab.is_some() {
786 return Ordering::Less;
788 if aa.is_some() && ab.is_none() {
789 return Ordering::Greater;
793 (&List(ref a), &List(ref b)) => {
794 for (a, b) in a.iter().zip(b.iter()) {
796 if ord != Ordering::Equal {
801 a.len().cmp(&b.len())
803 (&Slf(_), _) => Ordering::Less,
804 (_, &Slf(_)) => Ordering::Greater,
805 (&Super(_), _) => Ordering::Less,
806 (_, &Super(_)) => Ordering::Greater,
807 (&Crate(_), _) => Ordering::Less,
808 (_, &Crate(_)) => Ordering::Greater,
809 (&Ident(..), _) => Ordering::Less,
810 (_, &Ident(..)) => Ordering::Greater,
811 (&Glob, _) => Ordering::Less,
812 (_, &Glob) => Ordering::Greater,
816 impl Ord for UseTree {
817 fn cmp(&self, other: &UseTree) -> Ordering {
818 for (a, b) in self.path.iter().zip(other.path.iter()) {
820 // The comparison without aliases is a hack to avoid situations like
821 // comparing `a::b` to `a as c` - where the latter should be ordered
822 // first since it is shorter.
823 if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
829 self.path.len().cmp(&other.path.len())
833 fn rewrite_nested_use_tree(
834 context: &RewriteContext<'_>,
835 use_tree_list: &[UseTree],
837 ) -> Option<String> {
838 let mut list_items = Vec::with_capacity(use_tree_list.len());
839 let nested_shape = match context.config.imports_indent() {
840 IndentStyle::Block => shape
841 .block_indent(context.config.tab_spaces())
842 .with_max_width(context.config)
844 IndentStyle::Visual => shape.visual_indent(0),
846 for use_tree in use_tree_list {
847 if let Some(mut list_item) = use_tree.list_item.clone() {
848 list_item.item = use_tree.rewrite(context, nested_shape);
849 list_items.push(list_item);
851 list_items.push(ListItem::from_str(use_tree.rewrite(context, nested_shape)?));
854 let has_nested_list = use_tree_list.iter().any(|use_segment| {
855 use_segment.path.last().map_or(false, |last_segment| {
856 matches!(last_segment, UseSegment::List(..))
860 let remaining_width = if has_nested_list {
863 shape.width.saturating_sub(2)
866 let tactic = definitive_tactic(
868 context.config.imports_layout(),
873 let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
874 && tactic != DefinitiveListTactic::Horizontal;
875 let trailing_separator = if ends_with_newline {
876 context.config.trailing_comma()
878 SeparatorTactic::Never
880 let fmt = ListFormatting::new(nested_shape, context.config)
882 .trailing_separator(trailing_separator)
883 .ends_with_newline(ends_with_newline)
884 .preserve_newline(true)
885 .nested(has_nested_list);
887 let list_str = write_list(&list_items, &fmt)?;
889 let result = if (list_str.contains('\n') || list_str.len() > remaining_width)
890 && context.config.imports_indent() == IndentStyle::Block
894 nested_shape.indent.to_string(context.config),
896 shape.indent.to_string(context.config)
899 format!("{{{}}}", list_str)
905 impl Rewrite for UseSegment {
906 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
908 UseSegment::Ident(ref ident, Some(ref rename)) => format!("{} as {}", ident, rename),
909 UseSegment::Ident(ref ident, None) => ident.clone(),
910 UseSegment::Slf(Some(ref rename)) => format!("self as {}", rename),
911 UseSegment::Slf(None) => "self".to_owned(),
912 UseSegment::Super(Some(ref rename)) => format!("super as {}", rename),
913 UseSegment::Super(None) => "super".to_owned(),
914 UseSegment::Crate(Some(ref rename)) => format!("crate as {}", rename),
915 UseSegment::Crate(None) => "crate".to_owned(),
916 UseSegment::Glob => "*".to_owned(),
917 UseSegment::List(ref use_tree_list) => rewrite_nested_use_tree(
921 shape.offset_left(1)?.sub_width(1)?,
927 impl Rewrite for UseTree {
928 // This does NOT format attributes and visibility or add a trailing `;`.
929 fn rewrite(&self, context: &RewriteContext<'_>, mut shape: Shape) -> Option<String> {
930 let mut result = String::with_capacity(256);
931 let mut iter = self.path.iter().peekable();
932 while let Some(segment) = iter.next() {
933 let segment_str = segment.rewrite(context, shape)?;
934 result.push_str(&segment_str);
935 if iter.peek().is_some() {
936 result.push_str("::");
938 shape = shape.offset_left(2 + segment_str.len())?;
945 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
946 pub(crate) enum SharedPrefix {
955 use rustc_span::DUMMY_SP;
957 // Parse the path part of an import. This parser is not robust and is only
958 // suitable for use in a test harness.
959 fn parse_use_tree(s: &str) -> UseTree {
960 use std::iter::Peekable;
965 input: Peekable<Chars<'a>>,
968 impl<'a> Parser<'a> {
970 self.input.next().unwrap();
973 fn eat(&mut self, c: char) {
974 assert_eq!(self.input.next().unwrap(), c);
978 result: &mut Vec<UseSegment>,
980 alias_buf: &mut Option<String>,
983 let mut alias = None;
984 swap(alias_buf, &mut alias);
988 result.push(UseSegment::Slf(alias));
989 *buf = String::new();
993 result.push(UseSegment::Super(alias));
994 *buf = String::new();
998 result.push(UseSegment::Crate(alias));
999 *buf = String::new();
1003 let mut name = String::new();
1004 swap(buf, &mut name);
1005 result.push(UseSegment::Ident(name, alias));
1011 fn parse_in_list(&mut self) -> UseTree {
1012 let mut result = vec![];
1013 let mut buf = String::new();
1014 let mut alias_buf = None;
1015 while let Some(&c) = self.input.peek() {
1018 assert!(buf.is_empty());
1020 result.push(UseSegment::List(self.parse_list()));
1024 assert!(buf.is_empty());
1026 result.push(UseSegment::Glob);
1031 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
1034 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
1048 alias_buf = Some(String::new());
1052 if let Some(ref mut buf) = alias_buf {
1060 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
1070 fn parse_list(&mut self) -> Vec<UseTree> {
1071 let mut result = vec![];
1073 match self.input.peek().unwrap() {
1074 ',' | ' ' => self.bump(),
1078 _ => result.push(self.parse_in_list()),
1084 let mut parser = Parser {
1085 input: s.chars().peekable(),
1087 parser.parse_in_list()
1090 macro_rules! parse_use_trees {
1091 ($($s:expr),* $(,)*) => {
1093 $(parse_use_tree($s),)*
1098 macro_rules! test_merge {
1099 ($by:ident, [$($input:expr),* $(,)*], [$($output:expr),* $(,)*]) => {
1101 merge_use_trees(parse_use_trees!($($input,)*), SharedPrefix::$by),
1102 parse_use_trees!($($output,)*),
1108 fn test_use_tree_merge_crate() {
1111 ["a::b::{c, d}", "a::b::{e, f}"],
1112 ["a::b::{c, d, e, f}"]
1114 test_merge!(Crate, ["a::b::c", "a::b"], ["a::{b, b::c}"]);
1115 test_merge!(Crate, ["a::b", "a::b"], ["a::b"]);
1116 test_merge!(Crate, ["a", "a::b", "a::b::c"], ["a::{self, b, b::c}"]);
1119 ["a", "a::b", "a::b::c", "a::b::c::d"],
1120 ["a::{self, b, b::{c, c::d}}"]
1124 ["a", "a::b", "a::b::c", "a::b"],
1125 ["a::{self, b, b::c}"]
1129 ["a::{b::{self, c}, d::e}", "a::d::f"],
1130 ["a::{b::{self, c}, d::{e, f}}"]
1134 ["a::d::f", "a::{b::{self, c}, d::e}"],
1135 ["a::{b::{self, c}, d::{e, f}}"]
1139 ["a::{c, d, b}", "a::{d, e, b, a, f}", "a::{f, g, c}"],
1140 ["a::{a, b, c, d, e, f, g}"]
1144 ["a::{self}", "b::{self as foo}"],
1145 ["a::{self}", "b::{self as foo}"]
1150 fn test_use_tree_merge_module() {
1153 ["foo::b", "foo::{a, c, d::e}"],
1154 ["foo::{a, b, c}", "foo::d::e"]
1159 ["foo::{a::b, a::c, d::e, d::f}"],
1160 ["foo::a::{b, c}", "foo::d::{e, f}"]
1165 fn test_use_tree_merge_one() {
1166 test_merge!(One, ["a", "b"], ["{a, b}"]);
1168 test_merge!(One, ["a::{aa, ab}", "b", "a"], ["{a::{self, aa, ab}, b}"]);
1170 test_merge!(One, ["a as x", "b as y"], ["{a as x, b as y}"]);
1174 ["a::{aa as xa, ab}", "b", "a"],
1175 ["{a::{self, aa as xa, ab}, b}"]
1180 ["a", "a::{aa, ab::{aba, abb}}"],
1181 ["a::{self, aa, ab::{aba, abb}}"]
1184 test_merge!(One, ["a", "b::{ba, *}"], ["{a, b::{ba, *}}"]);
1186 test_merge!(One, ["a", "b", "a::aa"], ["{a::{self, aa}, b}"]);
1190 ["a::aa::aaa", "a::ac::aca", "a::aa::*"],
1191 ["a::{aa::{aaa, *}, ac::aca}"]
1196 ["a", "b::{ba, bb}", "a::{aa::*, ab::aba}"],
1197 ["{a::{self, aa::*, ab::aba}, b::{ba, bb}}"]
1202 ["b", "a::ac::{aca, acb}", "a::{aa::*, ab}"],
1203 ["{a::{aa::*, ab, ac::{aca, acb}}, b}"]
1208 fn test_flatten_use_trees() {
1210 flatten_use_trees(parse_use_trees!["foo::{a::{b, c}, d::e}"]),
1211 parse_use_trees!["foo::a::b", "foo::a::c", "foo::d::e"]
1215 flatten_use_trees(parse_use_trees!["foo::{self, a, b::{c, d}, e::*}"]),
1227 fn test_use_tree_flatten() {
1229 parse_use_tree("a::b::{c, d, e, f}").flatten(),
1230 parse_use_trees!("a::b::c", "a::b::d", "a::b::e", "a::b::f",)
1234 parse_use_tree("a::b::{c::{d, e, f}, g, h::{i, j, k}}").flatten(),
1248 fn test_use_tree_normalize() {
1249 assert_eq!(parse_use_tree("a::self").normalize(), parse_use_tree("a"));
1251 parse_use_tree("a::self as foo").normalize(),
1252 parse_use_tree("a as foo")
1255 parse_use_tree("a::{self}").normalize(),
1256 parse_use_tree("a::{self}")
1258 assert_eq!(parse_use_tree("a::{b}").normalize(), parse_use_tree("a::b"));
1260 parse_use_tree("a::{b, c::self}").normalize(),
1261 parse_use_tree("a::{b, c}")
1264 parse_use_tree("a::{b as bar, c::self}").normalize(),
1265 parse_use_tree("a::{b as bar, c}")
1270 fn test_use_tree_ord() {
1271 assert!(parse_use_tree("a").normalize() < parse_use_tree("aa").normalize());
1272 assert!(parse_use_tree("a").normalize() < parse_use_tree("a::a").normalize());
1273 assert!(parse_use_tree("a").normalize() < parse_use_tree("*").normalize());
1274 assert!(parse_use_tree("a").normalize() < parse_use_tree("{a, b}").normalize());
1275 assert!(parse_use_tree("*").normalize() < parse_use_tree("{a, b}").normalize());
1278 parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, dddddddd}").normalize()
1279 < parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, ddddddddd}").normalize()
1282 parse_use_tree("serde::de::{Deserialize}").normalize()
1283 < parse_use_tree("serde_json").normalize()
1285 assert!(parse_use_tree("a::b::c").normalize() < parse_use_tree("a::b::*").normalize());
1287 parse_use_tree("foo::{Bar, Baz}").normalize()
1288 < parse_use_tree("{Bar, Baz}").normalize()
1292 parse_use_tree("foo::{qux as bar}").normalize()
1293 < parse_use_tree("foo::{self as bar}").normalize()
1296 parse_use_tree("foo::{qux as bar}").normalize()
1297 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1300 parse_use_tree("foo::{self as bar, baz}").normalize()
1301 < parse_use_tree("foo::{baz, qux as bar}").normalize()
1304 assert!(parse_use_tree("foo").normalize() < parse_use_tree("Foo").normalize());
1305 assert!(parse_use_tree("foo").normalize() < parse_use_tree("foo::Bar").normalize());
1308 parse_use_tree("std::cmp::{d, c, b, a}").normalize()
1309 < parse_use_tree("std::cmp::{b, e, g, f}").normalize()