]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Merge pull request #2265 from topecongiro/issue-2262
[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 syntax::ast;
14 use syntax::codemap::{BytePos, Span};
15
16 use spanned::Spanned;
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, DefinitiveListTactic, ListFormatting,
21             ListItem, Separator, SeparatorPlace, SeparatorTactic};
22 use rewrite::{Rewrite, RewriteContext};
23 use shape::Shape;
24 use types::{rewrite_path, PathContext};
25 use utils::{format_visibility, mk_sp};
26 use visitor::{rewrite_extern_crate, FmtVisitor};
27
28 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
29     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
30 }
31
32 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
33     for segment in a.segments.iter().zip(b.segments.iter()) {
34         let ord = compare_path_segments(segment.0, segment.1);
35         if ord != Ordering::Equal {
36             return ord;
37         }
38     }
39     a.segments.len().cmp(&b.segments.len())
40 }
41
42 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
43     use ast::UseTreeKind::*;
44
45     // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
46     // fully added
47     if !nested {
48         let paths_cmp = compare_paths(&a.prefix, &b.prefix);
49         if paths_cmp != Ordering::Equal {
50             return paths_cmp;
51         }
52     }
53
54     match (&a.kind, &b.kind) {
55         (&Simple(ident_a), &Simple(ident_b)) => {
56             let name_a = &*path_to_imported_ident(&a.prefix).name.as_str();
57             let name_b = &*path_to_imported_ident(&b.prefix).name.as_str();
58             let name_ordering = if name_a == "self" {
59                 if name_b == "self" {
60                     Ordering::Equal
61                 } else {
62                     Ordering::Less
63                 }
64             } else if name_b == "self" {
65                 Ordering::Greater
66             } else {
67                 name_a.cmp(name_b)
68             };
69             if name_ordering == Ordering::Equal {
70                 if ident_a.name.as_str() != name_a {
71                     if ident_b.name.as_str() != name_b {
72                         ident_a.name.as_str().cmp(&ident_b.name.as_str())
73                     } else {
74                         Ordering::Greater
75                     }
76                 } else {
77                     Ordering::Less
78                 }
79             } else {
80                 name_ordering
81             }
82         }
83         (&Glob, &Glob) => Ordering::Equal,
84         (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
85         (&Nested(ref a_items), &Nested(ref b_items)) => {
86             let mut a = a_items
87                 .iter()
88                 .map(|&(ref tree, _)| tree.clone())
89                 .collect::<Vec<_>>();
90             let mut b = b_items
91                 .iter()
92                 .map(|&(ref tree, _)| tree.clone())
93                 .collect::<Vec<_>>();
94             a.sort_by(|a, b| compare_use_trees(a, b, true));
95             b.sort_by(|a, b| compare_use_trees(a, b, true));
96             for comparison_pair in a.iter().zip(b.iter()) {
97                 let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
98                 if ord != Ordering::Equal {
99                     return ord;
100                 }
101             }
102             a.len().cmp(&b.len())
103         }
104         (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
105     }
106 }
107
108 fn compare_use_items(context: &RewriteContext, a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
109     match (&a.node, &b.node) {
110         (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
111             Some(compare_use_trees(&a_tree, &b_tree, false))
112         }
113         (&ast::ItemKind::ExternCrate(..), &ast::ItemKind::ExternCrate(..)) => {
114             Some(context.snippet(a.span).cmp(&context.snippet(b.span)))
115         }
116         _ => None,
117     }
118 }
119
120 // TODO (some day) remove unused imports, expand globs, compress many single
121 // imports into a list import.
122
123 fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
124     if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
125         let path = &ast::Path {
126             span: path.span,
127             segments: path.segments[..path.segments.len() - 1].to_owned(),
128         };
129         rewrite_path(context, PathContext::Import, None, path, shape)
130     } else {
131         rewrite_path(context, PathContext::Import, None, path, shape)
132     }
133 }
134
135 impl Rewrite for ast::UseTree {
136     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
137         match self.kind {
138             ast::UseTreeKind::Nested(ref items) => {
139                 rewrite_nested_use_tree(shape, &self.prefix, items, self.span, context)
140             }
141             ast::UseTreeKind::Glob => {
142                 let prefix_shape = shape.sub_width(3)?;
143
144                 if self.prefix.segments.len() > 0 {
145                     let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)?;
146                     Some(format!("{}::*", path_str))
147                 } else {
148                     Some("*".to_owned())
149                 }
150             }
151             ast::UseTreeKind::Simple(ident) => {
152                 let ident_str = ident.to_string();
153
154                 // 4 = " as ".len()
155                 let is_same_name_bind = path_to_imported_ident(&self.prefix) == ident;
156                 let prefix_shape = if is_same_name_bind {
157                     shape
158                 } else {
159                     shape.sub_width(ident_str.len() + 4)?
160                 };
161                 let path_str = rewrite_prefix(&self.prefix, context, prefix_shape)
162                     .unwrap_or_else(|| context.snippet(self.prefix.span).to_owned());
163
164                 if is_same_name_bind {
165                     Some(path_str)
166                 } else {
167                     Some(format!("{} as {}", path_str, ident_str))
168                 }
169             }
170         }
171     }
172 }
173
174 fn is_unused_import(tree: &ast::UseTree, attrs: &[ast::Attribute]) -> bool {
175     attrs.is_empty() && is_unused_import_inner(tree)
176 }
177
178 fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
179     match tree.kind {
180         ast::UseTreeKind::Nested(ref items) => match items.len() {
181             0 => true,
182             1 => is_unused_import_inner(&items[0].0),
183             _ => false,
184         },
185         _ => false,
186     }
187 }
188
189 // Rewrite `use foo;` WITHOUT attributes.
190 fn rewrite_import(
191     context: &RewriteContext,
192     vis: &ast::Visibility,
193     tree: &ast::UseTree,
194     attrs: &[ast::Attribute],
195     shape: Shape,
196 ) -> Option<String> {
197     let vis = format_visibility(vis);
198     // 4 = `use `, 1 = `;`
199     let rw = shape
200         .offset_left(vis.len() + 4)
201         .and_then(|shape| shape.sub_width(1))
202         .and_then(|shape| {
203             // If we have an empty nested group with no attributes, we erase it
204             if is_unused_import(tree, attrs) {
205                 Some("".to_owned())
206             } else {
207                 tree.rewrite(context, shape)
208             }
209         });
210     match rw {
211         Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
212         _ => rw,
213     }
214 }
215
216 fn rewrite_imports(
217     context: &RewriteContext,
218     use_items: &[&ast::Item],
219     shape: Shape,
220     span: Span,
221 ) -> Option<String> {
222     let items = itemize_list(
223         context.codemap,
224         use_items.iter(),
225         "",
226         ";",
227         |item| item.span().lo(),
228         |item| item.span().hi(),
229         |item| {
230             let attrs_str = item.attrs.rewrite(context, shape)?;
231
232             let missed_span = if item.attrs.is_empty() {
233                 mk_sp(item.span.lo(), item.span.lo())
234             } else {
235                 mk_sp(item.attrs.last().unwrap().span.hi(), item.span.lo())
236             };
237
238             let item_str = match item.node {
239                 ast::ItemKind::Use(ref tree) => {
240                     rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
241                 }
242                 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
243                 _ => return None,
244             };
245
246             combine_strs_with_missing_comments(
247                 context,
248                 &attrs_str,
249                 &item_str,
250                 missed_span,
251                 shape,
252                 false,
253             )
254         },
255         span.lo(),
256         span.hi(),
257         false,
258     );
259     let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
260     item_pair_vec.sort_by(|a, b| compare_use_items(context, a.1, b.1).unwrap());
261     let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
262
263     let fmt = ListFormatting {
264         tactic: DefinitiveListTactic::Vertical,
265         separator: "",
266         trailing_separator: SeparatorTactic::Never,
267         separator_place: SeparatorPlace::Back,
268         shape: shape,
269         ends_with_newline: true,
270         preserve_newline: false,
271         config: context.config,
272     };
273
274     write_list(&item_vec, &fmt)
275 }
276
277 impl<'a> FmtVisitor<'a> {
278     pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
279         if use_items.is_empty() {
280             return;
281         }
282
283         let lo = use_items.first().unwrap().span().lo();
284         let hi = use_items.last().unwrap().span().hi();
285         let span = mk_sp(lo, hi);
286         let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
287         self.push_rewrite(span, rw);
288     }
289
290     pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
291         let span = item.span;
292         let shape = self.shape();
293         let rw = rewrite_import(&self.get_context(), &item.vis, tree, &item.attrs, shape);
294         match rw {
295             Some(ref s) if s.is_empty() => {
296                 // Format up to last newline
297                 let prev_span = mk_sp(self.last_pos, source!(self, span).lo());
298                 let span_end = match self.snippet(prev_span).rfind('\n') {
299                     Some(offset) => self.last_pos + BytePos(offset as u32),
300                     None => source!(self, span).lo(),
301                 };
302                 self.format_missing(span_end);
303                 self.last_pos = source!(self, span).hi();
304             }
305             Some(ref s) => {
306                 self.format_missing_with_indent(source!(self, span).lo());
307                 self.push_str(s);
308                 self.last_pos = source!(self, span).hi();
309             }
310             None => {
311                 self.format_missing_with_indent(source!(self, span).lo());
312                 self.format_missing(source!(self, span).hi());
313             }
314         }
315     }
316 }
317
318 fn rewrite_nested_use_tree_single(
319     context: &RewriteContext,
320     path_str: &str,
321     tree: &ast::UseTree,
322     shape: Shape,
323 ) -> Option<String> {
324     match tree.kind {
325         ast::UseTreeKind::Simple(rename) => {
326             let ident = path_to_imported_ident(&tree.prefix);
327             let mut item_str = rewrite_prefix(&tree.prefix, context, shape)?;
328             if item_str == "self" {
329                 item_str = "".to_owned();
330             }
331
332             let path_item_str = if path_str.is_empty() {
333                 if item_str.is_empty() {
334                     "self".to_owned()
335                 } else {
336                     item_str
337                 }
338             } else if item_str.is_empty() {
339                 path_str.to_owned()
340             } else {
341                 format!("{}::{}", path_str, item_str)
342             };
343
344             Some(if ident == rename {
345                 path_item_str
346             } else {
347                 format!("{} as {}", path_item_str, rename)
348             })
349         }
350         ast::UseTreeKind::Glob | ast::UseTreeKind::Nested(..) => {
351             // 2 = "::"
352             let nested_shape = shape.offset_left(path_str.len() + 2)?;
353             tree.rewrite(context, nested_shape)
354                 .map(|item| format!("{}::{}", path_str, item))
355         }
356     }
357 }
358
359 #[derive(Eq, PartialEq)]
360 enum ImportItem<'a> {
361     // `self` or `self as a`
362     SelfImport(&'a str),
363     // name_one, name_two, ...
364     SnakeCase(&'a str),
365     // NameOne, NameTwo, ...
366     CamelCase(&'a str),
367     // NAME_ONE, NAME_TWO, ...
368     AllCaps(&'a str),
369     // Failed to format the import item
370     Invalid,
371 }
372
373 impl<'a> ImportItem<'a> {
374     fn from_str(s: &str) -> ImportItem {
375         if s == "self" || s.starts_with("self as") {
376             ImportItem::SelfImport(s)
377         } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
378             ImportItem::SnakeCase(s)
379         } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
380             ImportItem::AllCaps(s)
381         } else {
382             ImportItem::CamelCase(s)
383         }
384     }
385
386     fn from_opt_str(s: Option<&String>) -> ImportItem {
387         s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
388     }
389
390     fn to_str(&self) -> Option<&str> {
391         match *self {
392             ImportItem::SelfImport(s)
393             | ImportItem::SnakeCase(s)
394             | ImportItem::CamelCase(s)
395             | ImportItem::AllCaps(s) => Some(s),
396             ImportItem::Invalid => None,
397         }
398     }
399
400     fn to_u32(&self) -> u32 {
401         match *self {
402             ImportItem::SelfImport(..) => 0,
403             ImportItem::SnakeCase(..) => 1,
404             ImportItem::CamelCase(..) => 2,
405             ImportItem::AllCaps(..) => 3,
406             ImportItem::Invalid => 4,
407         }
408     }
409 }
410
411 impl<'a> PartialOrd for ImportItem<'a> {
412     fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
413         Some(self.cmp(other))
414     }
415 }
416
417 impl<'a> Ord for ImportItem<'a> {
418     fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
419         let res = self.to_u32().cmp(&other.to_u32());
420         if res != Ordering::Equal {
421             return res;
422         }
423         self.to_str().map_or(Ordering::Greater, |self_str| {
424             other
425                 .to_str()
426                 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
427         })
428     }
429 }
430
431 // Pretty prints a multi-item import.
432 // If the path list is empty, it leaves the braces empty.
433 fn rewrite_nested_use_tree(
434     shape: Shape,
435     path: &ast::Path,
436     trees: &[(ast::UseTree, ast::NodeId)],
437     span: Span,
438     context: &RewriteContext,
439 ) -> Option<String> {
440     // Returns a different option to distinguish `::foo` and `foo`
441     let path_str = rewrite_path(context, PathContext::Import, None, path, shape)?;
442
443     match trees.len() {
444         0 => {
445             let shape = shape.offset_left(path_str.len() + 3)?;
446             return rewrite_path(context, PathContext::Import, None, path, shape)
447                 .map(|path_str| format!("{}::{{}}", path_str));
448         }
449         1 => {
450             return rewrite_nested_use_tree_single(context, &path_str, &trees[0].0, shape);
451         }
452         _ => (),
453     }
454
455     let path_str = if path_str.is_empty() {
456         path_str
457     } else {
458         format!("{}::", path_str)
459     };
460
461     // 2 = "{}"
462     let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
463     let nested_indent = match context.config.imports_indent() {
464         IndentStyle::Block => shape.indent.block_indent(context.config),
465         // 1 = `{`
466         IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
467     };
468
469     let nested_shape = match context.config.imports_indent() {
470         IndentStyle::Block => Shape::indented(nested_indent, context.config).sub_width(1)?,
471         IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
472     };
473
474     let mut items = {
475         // Dummy value, see explanation below.
476         let mut items = vec![ListItem::from_str("")];
477         let iter = itemize_list(
478             context.codemap,
479             trees.iter().map(|ref tree| &tree.0),
480             "}",
481             ",",
482             |tree| tree.span.lo(),
483             |tree| tree.span.hi(),
484             |tree| tree.rewrite(context, nested_shape),
485             context.codemap.span_after(span, "{"),
486             span.hi(),
487             false,
488         );
489         items.extend(iter);
490         items
491     };
492
493     // We prefixed the item list with a dummy value so that we can
494     // potentially move "self" to the front of the vector without touching
495     // the rest of the items.
496     let has_self = move_self_to_front(&mut items);
497     let first_index = if has_self { 0 } else { 1 };
498
499     if context.config.reorder_imported_names() {
500         items[1..].sort_by(|a, b| {
501             let a = ImportItem::from_opt_str(a.item.as_ref());
502             let b = ImportItem::from_opt_str(b.item.as_ref());
503             a.cmp(&b)
504         });
505     }
506
507     let tactic = definitive_tactic(
508         &items[first_index..],
509         context.config.imports_layout(),
510         Separator::Comma,
511         remaining_width,
512     );
513
514     let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
515         && tactic != DefinitiveListTactic::Horizontal;
516
517     let fmt = ListFormatting {
518         tactic: tactic,
519         separator: ",",
520         trailing_separator: if ends_with_newline {
521             context.config.trailing_comma()
522         } else {
523             SeparatorTactic::Never
524         },
525         separator_place: SeparatorPlace::Back,
526         shape: nested_shape,
527         ends_with_newline: ends_with_newline,
528         preserve_newline: true,
529         config: context.config,
530     };
531     let list_str = write_list(&items[first_index..], &fmt)?;
532
533     let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
534     {
535         format!(
536             "{}{{\n{}{}\n{}}}",
537             path_str,
538             nested_shape.indent.to_string(context.config),
539             list_str,
540             shape.indent.to_string(context.config)
541         )
542     } else {
543         format!("{}{{{}}}", path_str, list_str)
544     };
545     Some(result)
546 }
547
548 // Returns true when self item was found.
549 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
550     match items
551         .iter()
552         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
553     {
554         Some(pos) => {
555             items[0] = items.remove(pos);
556             true
557         }
558         None => false,
559     }
560 }
561
562 fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
563     path.segments.last().unwrap().identifier
564 }