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