]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Sort imports in alphabetical and consistent order
[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::{self, Ordering};
12
13 use syntax::{ast, ptr};
14 use syntax::codemap::{BytePos, Span};
15
16 use Shape;
17 use codemap::SpanUtils;
18 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, SeparatorTactic};
19 use rewrite::{Rewrite, RewriteContext};
20 use types::{rewrite_path, PathContext};
21 use utils;
22 use visitor::FmtVisitor;
23
24 fn path_of(a: &ast::ViewPath_) -> &ast::Path {
25     match *a {
26         ast::ViewPath_::ViewPathSimple(_, ref p) => p,
27         ast::ViewPath_::ViewPathGlob(ref p) => p,
28         ast::ViewPath_::ViewPathList(ref p, _) => p,
29     }
30 }
31
32 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
33     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
34 }
35
36 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
37     for segment in a.segments.iter().zip(b.segments.iter()) {
38         let ord = compare_path_segments(segment.0, segment.1);
39         if ord != Ordering::Equal {
40             return ord;
41         }
42     }
43     a.segments.len().cmp(&b.segments.len())
44 }
45
46 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
47     let a_name_str = &*a.node.name.name.as_str();
48     let b_name_str = &*b.node.name.name.as_str();
49     let name_ordering = if a_name_str == "self" {
50         if b_name_str == "self" {
51             Ordering::Equal
52         } else {
53             Ordering::Less
54         }
55     } else {
56         if b_name_str == "self" {
57             Ordering::Greater
58         } else {
59             a_name_str.cmp(&b_name_str)
60         }
61     };
62     if name_ordering == Ordering::Equal {
63         match a.node.rename {
64             Some(a_rename) => match b.node.rename {
65                 Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
66                 None => Ordering::Greater,
67             },
68             None => Ordering::Less,
69         }
70     } else {
71         name_ordering
72     }
73 }
74
75 fn compare_path_list_item_lists(
76     a_items: &Vec<ast::PathListItem>,
77     b_items: &Vec<ast::PathListItem>,
78 ) -> Ordering {
79     let mut a = a_items.clone();
80     let mut b = b_items.clone();
81     a.sort_by(|a, b| compare_path_list_items(a, b));
82     b.sort_by(|a, b| compare_path_list_items(a, b));
83     for comparison_pair in a.iter().zip(b.iter()) {
84         let ord = compare_path_list_items(comparison_pair.0, comparison_pair.1);
85         if ord != Ordering::Equal {
86             return ord;
87         }
88     }
89     a.len().cmp(&b.len())
90 }
91
92 fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
93     use syntax::ast::ViewPath_::*;
94     match (a, b) {
95         (&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
96         (&ViewPathSimple(..), _) => Ordering::Less,
97         (&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
98         (&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
99         (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
100         (&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
101             compare_path_list_item_lists(a_items, b_items)
102         }
103         (&ViewPathList(..), _) => Ordering::Greater,
104     }
105 }
106
107 fn compare_view_paths(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
108     match compare_paths(path_of(a), path_of(b)) {
109         Ordering::Equal => compare_view_path_types(a, b),
110         cmp => cmp,
111     }
112 }
113
114 fn compare_use_items(a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
115     match (&a.node, &b.node) {
116         (&ast::ItemKind::Use(ref a_vp), &ast::ItemKind::Use(ref b_vp)) => {
117             Some(compare_view_paths(&a_vp.node, &b_vp.node))
118         }
119         _ => None,
120     }
121 }
122
123 // TODO (some day) remove unused imports, expand globs, compress many single
124 // imports into a list import.
125
126 fn rewrite_view_path_prefix(
127     path: &ast::Path,
128     context: &RewriteContext,
129     shape: Shape,
130 ) -> Option<String> {
131     let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
132         path.segments.len() > 1
133     {
134         let path = &ast::Path {
135             span: path.span.clone(),
136             segments: path.segments[..path.segments.len() - 1].to_owned(),
137         };
138         try_opt!(rewrite_path(
139             context,
140             PathContext::Import,
141             None,
142             path,
143             shape,
144         ))
145     } else {
146         try_opt!(rewrite_path(
147             context,
148             PathContext::Import,
149             None,
150             path,
151             shape,
152         ))
153     };
154     Some(path_str)
155 }
156
157 impl Rewrite for ast::ViewPath {
158     // Returns an empty string when the ViewPath is empty (like foo::bar::{})
159     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
160         match self.node {
161             ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => {
162                 Some(String::new())
163             }
164             ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
165                 rewrite_use_list(shape, path, path_list, self.span, context)
166             }
167             ast::ViewPath_::ViewPathGlob(ref path) => {
168                 // 4 = "::*".len()
169                 let prefix_shape = try_opt!(shape.sub_width(3));
170                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
171                 Some(format!("{}::*", path_str))
172             }
173             ast::ViewPath_::ViewPathSimple(ident, ref path) => {
174                 let ident_str = ident.to_string();
175                 // 4 = " as ".len()
176                 let prefix_shape = try_opt!(shape.sub_width(ident_str.len() + 4));
177                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
178
179                 Some(if path.segments.last().unwrap().identifier == ident {
180                     path_str
181                 } else {
182                     format!("{} as {}", path_str, ident_str)
183                 })
184             }
185         }
186     }
187 }
188
189 impl<'a> FmtVisitor<'a> {
190     pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
191         // Find the location immediately before the first use item in the run. This must not lie
192         // before the current `self.last_pos`
193         let pos_before_first_use_item = use_items
194             .first()
195             .map(|p_i| {
196                 cmp::max(
197                     self.last_pos,
198                     p_i.attrs
199                         .iter()
200                         .map(|attr| attr.span.lo)
201                         .min()
202                         .unwrap_or(p_i.span.lo),
203                 )
204             })
205             .unwrap_or(self.last_pos);
206         // Construct a list of pairs, each containing a `use` item and the start of span before
207         // that `use` item.
208         let mut last_pos_of_prev_use_item = pos_before_first_use_item;
209         let mut ordered_use_items = use_items
210             .iter()
211             .map(|p_i| {
212                 let new_item = (&*p_i, last_pos_of_prev_use_item);
213                 last_pos_of_prev_use_item = p_i.span.hi;
214                 new_item
215             })
216             .collect::<Vec<_>>();
217         let pos_after_last_use_item = last_pos_of_prev_use_item;
218         // Order the imports by view-path & other import path properties
219         ordered_use_items.sort_by(|a, b| compare_use_items(a.0, b.0).unwrap());
220         // First, output the span before the first import
221         let prev_span_str = self.snippet(utils::mk_sp(self.last_pos, pos_before_first_use_item));
222         // Look for purely trailing space at the start of the prefix snippet before a linefeed, or
223         // a prefix that's entirely horizontal whitespace.
224         let prefix_span_start = match prev_span_str.find('\n') {
225             Some(offset) if prev_span_str[..offset].trim().is_empty() => {
226                 self.last_pos + BytePos(offset as u32)
227             }
228             None if prev_span_str.trim().is_empty() => pos_before_first_use_item,
229             _ => self.last_pos,
230         };
231         // Look for indent (the line part preceding the use is all whitespace) and excise that
232         // from the prefix
233         let span_end = match prev_span_str.rfind('\n') {
234             Some(offset) if prev_span_str[offset..].trim().is_empty() => {
235                 self.last_pos + BytePos(offset as u32)
236             }
237             _ => pos_before_first_use_item,
238         };
239
240         self.last_pos = prefix_span_start;
241         self.format_missing(span_end);
242         for ordered in ordered_use_items {
243             // Fake out the formatter by setting `self.last_pos` to the appropriate location before
244             // each item before visiting it.
245             self.last_pos = ordered.1;
246             self.visit_item(ordered.0);
247         }
248         self.last_pos = pos_after_last_use_item;
249     }
250
251     pub fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
252         let vis = utils::format_visibility(vis);
253         let mut offset = self.block_indent;
254         offset.alignment += vis.len() + "use ".len();
255         // 1 = ";"
256         match vp.rewrite(
257             &self.get_context(),
258             Shape::legacy(self.config.max_width() - offset.width() - 1, offset),
259         ) {
260             Some(ref s) if s.is_empty() => {
261                 // Format up to last newline
262                 let prev_span = utils::mk_sp(self.last_pos, source!(self, span).lo);
263                 let span_end = match self.snippet(prev_span).rfind('\n') {
264                     Some(offset) => self.last_pos + BytePos(offset as u32),
265                     None => source!(self, span).lo,
266                 };
267                 self.format_missing(span_end);
268                 self.last_pos = source!(self, span).hi;
269             }
270             Some(ref s) => {
271                 let s = format!("{}use {};", vis, s);
272                 self.format_missing_with_indent(source!(self, span).lo);
273                 self.buffer.push_str(&s);
274                 self.last_pos = source!(self, span).hi;
275             }
276             None => {
277                 self.format_missing_with_indent(source!(self, span).lo);
278                 self.format_missing(source!(self, span).hi);
279             }
280         }
281     }
282 }
283
284 fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
285     let mut item_str = vpi.node.name.to_string();
286     if item_str == "self" {
287         item_str = "".to_owned();
288     }
289     let path_item_str = if path_str.is_empty() {
290         if item_str.is_empty() {
291             "self".to_owned()
292         } else {
293             item_str
294         }
295     } else if item_str.is_empty() {
296         path_str
297     } else {
298         format!("{}::{}", path_str, item_str)
299     };
300     append_alias(path_item_str, vpi)
301 }
302
303 fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
304     Some(append_alias(vpi.node.name.to_string(), vpi))
305 }
306
307 fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
308     match vpi.node.rename {
309         Some(rename) => format!("{} as {}", path_item_str, rename),
310         None => path_item_str,
311     }
312 }
313
314 #[derive(Eq, PartialEq)]
315 enum ImportItem<'a> {
316     // `self` or `self as a`
317     SelfImport(&'a str),
318     // name_one, name_two, ...
319     SnakeCase(&'a str),
320     // NameOne, NameTwo, ...
321     CamelCase(&'a str),
322     // NAME_ONE, NAME_TWO, ...
323     AllCaps(&'a str),
324     // Failed to format the import item
325     Invalid,
326 }
327
328 impl<'a> ImportItem<'a> {
329     fn from_str(s: &str) -> ImportItem {
330         if s == "self" || s.starts_with("self as") {
331             ImportItem::SelfImport(s)
332         } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
333             ImportItem::SnakeCase(s)
334         } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
335             ImportItem::AllCaps(s)
336         } else {
337             ImportItem::CamelCase(s)
338         }
339     }
340
341     fn from_opt_str(s: Option<&String>) -> ImportItem {
342         s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
343     }
344
345     fn to_str(&self) -> Option<&str> {
346         match *self {
347             ImportItem::SelfImport(s) |
348             ImportItem::SnakeCase(s) |
349             ImportItem::CamelCase(s) |
350             ImportItem::AllCaps(s) => Some(s),
351             ImportItem::Invalid => None,
352         }
353     }
354
355     fn to_u32(&self) -> u32 {
356         match *self {
357             ImportItem::SelfImport(..) => 0,
358             ImportItem::SnakeCase(..) => 1,
359             ImportItem::CamelCase(..) => 2,
360             ImportItem::AllCaps(..) => 3,
361             ImportItem::Invalid => 4,
362         }
363     }
364 }
365
366 impl<'a> PartialOrd for ImportItem<'a> {
367     fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
368         Some(self.cmp(other))
369     }
370 }
371
372 impl<'a> Ord for ImportItem<'a> {
373     fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
374         let res = self.to_u32().cmp(&other.to_u32());
375         if res != Ordering::Equal {
376             return res;
377         }
378         self.to_str().map_or(Ordering::Greater, |self_str| {
379             other
380                 .to_str()
381                 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
382         })
383     }
384 }
385
386 // Pretty prints a multi-item import.
387 // Assumes that path_list.len() > 0.
388 pub fn rewrite_use_list(
389     shape: Shape,
390     path: &ast::Path,
391     path_list: &[ast::PathListItem],
392     span: Span,
393     context: &RewriteContext,
394 ) -> Option<String> {
395     // Returns a different option to distinguish `::foo` and `foo`
396     let path_str = try_opt!(rewrite_path(
397         context,
398         PathContext::Import,
399         None,
400         path,
401         shape,
402     ));
403
404     match path_list.len() {
405         0 => unreachable!(),
406         1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
407         _ => (),
408     }
409
410     let colons_offset = if path_str.is_empty() { 0 } else { 2 };
411
412     // 2 = "{}"
413     let remaining_width = shape
414         .width
415         .checked_sub(path_str.len() + 2 + colons_offset)
416         .unwrap_or(0);
417
418     let mut items = {
419         // Dummy value, see explanation below.
420         let mut items = vec![ListItem::from_str("")];
421         let iter = itemize_list(
422             context.codemap,
423             path_list.iter(),
424             "}",
425             |vpi| vpi.span.lo,
426             |vpi| vpi.span.hi,
427             rewrite_path_item,
428             context.codemap.span_after(span, "{"),
429             span.hi,
430         );
431         items.extend(iter);
432         items
433     };
434
435     // We prefixed the item list with a dummy value so that we can
436     // potentially move "self" to the front of the vector without touching
437     // the rest of the items.
438     let has_self = move_self_to_front(&mut items);
439     let first_index = if has_self { 0 } else { 1 };
440
441     if context.config.reorder_imported_names() {
442         items[1..].sort_by(|a, b| {
443             let a = ImportItem::from_opt_str(a.item.as_ref());
444             let b = ImportItem::from_opt_str(b.item.as_ref());
445             a.cmp(&b)
446         });
447     }
448
449
450     let tactic = definitive_tactic(
451         &items[first_index..],
452         ::lists::ListTactic::Mixed,
453         remaining_width,
454     );
455
456     let fmt = ListFormatting {
457         tactic: tactic,
458         separator: ",",
459         trailing_separator: SeparatorTactic::Never,
460         // Add one to the indent to account for "{"
461         shape: Shape::legacy(
462             remaining_width,
463             shape.indent + path_str.len() + colons_offset + 1,
464         ),
465         ends_with_newline: false,
466         config: context.config,
467     };
468     let list_str = try_opt!(write_list(&items[first_index..], &fmt));
469
470     Some(if path_str.is_empty() {
471         format!("{{{}}}", list_str)
472     } else {
473         format!("{}::{{{}}}", path_str, list_str)
474     })
475 }
476
477 // Returns true when self item was found.
478 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
479     match items
480         .iter()
481         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self")) {
482         Some(pos) => {
483             items[0] = items.remove(pos);
484             true
485         }
486         None => false,
487     }
488 }