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