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