]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Merge pull request #1968 from topecongiro/issue-1967
[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 {Shape, 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 types::{rewrite_path, PathContext};
24 use utils::{format_visibility, mk_sp};
25 use visitor::{rewrite_extern_crate, FmtVisitor};
26
27 fn path_of(a: &ast::ViewPath_) -> &ast::Path {
28     match *a {
29         ast::ViewPath_::ViewPathSimple(_, ref p) |
30         ast::ViewPath_::ViewPathGlob(ref p) |
31         ast::ViewPath_::ViewPathList(ref p, _) => p,
32     }
33 }
34
35 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
36     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
37 }
38
39 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
40     for segment in a.segments.iter().zip(b.segments.iter()) {
41         let ord = compare_path_segments(segment.0, segment.1);
42         if ord != Ordering::Equal {
43             return ord;
44         }
45     }
46     a.segments.len().cmp(&b.segments.len())
47 }
48
49 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
50     let a_name_str = &*a.node.name.name.as_str();
51     let b_name_str = &*b.node.name.name.as_str();
52     let name_ordering = if a_name_str == "self" {
53         if b_name_str == "self" {
54             Ordering::Equal
55         } else {
56             Ordering::Less
57         }
58     } else if b_name_str == "self" {
59         Ordering::Greater
60     } else {
61         a_name_str.cmp(b_name_str)
62     };
63     if name_ordering == Ordering::Equal {
64         match a.node.rename {
65             Some(a_rename) => match b.node.rename {
66                 Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
67                 None => Ordering::Greater,
68             },
69             None => Ordering::Less,
70         }
71     } else {
72         name_ordering
73     }
74 }
75
76 fn compare_path_list_item_lists(
77     a_items: &Vec<ast::PathListItem>,
78     b_items: &Vec<ast::PathListItem>,
79 ) -> Ordering {
80     let mut a = a_items.clone();
81     let mut b = b_items.clone();
82     a.sort_by(|a, b| compare_path_list_items(a, b));
83     b.sort_by(|a, b| compare_path_list_items(a, b));
84     for comparison_pair in a.iter().zip(b.iter()) {
85         let ord = compare_path_list_items(comparison_pair.0, comparison_pair.1);
86         if ord != Ordering::Equal {
87             return ord;
88         }
89     }
90     a.len().cmp(&b.len())
91 }
92
93 fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
94     use syntax::ast::ViewPath_::*;
95     match (a, b) {
96         (&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
97         (&ViewPathSimple(..), _) => Ordering::Less,
98         (&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
99         (&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
100         (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
101         (&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
102             compare_path_list_item_lists(a_items, b_items)
103         }
104         (&ViewPathList(..), _) => Ordering::Greater,
105     }
106 }
107
108 fn compare_view_paths(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
109     match compare_paths(path_of(a), path_of(b)) {
110         Ordering::Equal => compare_view_path_types(a, b),
111         cmp => cmp,
112     }
113 }
114
115 fn compare_use_items(context: &RewriteContext, a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
116     match (&a.node, &b.node) {
117         (&ast::ItemKind::Use(ref a_vp), &ast::ItemKind::Use(ref b_vp)) => {
118             Some(compare_view_paths(&a_vp.node, &b_vp.node))
119         }
120         (&ast::ItemKind::ExternCrate(..), &ast::ItemKind::ExternCrate(..)) => {
121             Some(context.snippet(a.span).cmp(&context.snippet(b.span)))
122         }
123         _ => None,
124     }
125 }
126
127 // TODO (some day) remove unused imports, expand globs, compress many single
128 // imports into a list import.
129
130 fn rewrite_view_path_prefix(
131     path: &ast::Path,
132     context: &RewriteContext,
133     shape: Shape,
134 ) -> Option<String> {
135     let path_str = if path.segments.last().unwrap().identifier.to_string() == "self"
136         && path.segments.len() > 1
137     {
138         let path = &ast::Path {
139             span: path.span,
140             segments: path.segments[..path.segments.len() - 1].to_owned(),
141         };
142         try_opt!(rewrite_path(
143             context,
144             PathContext::Import,
145             None,
146             path,
147             shape,
148         ))
149     } else {
150         try_opt!(rewrite_path(
151             context,
152             PathContext::Import,
153             None,
154             path,
155             shape,
156         ))
157     };
158     Some(path_str)
159 }
160
161 impl Rewrite for ast::ViewPath {
162     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
163         match self.node {
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 // Rewrite `use foo;` WITHOUT attributes.
190 fn rewrite_import(
191     context: &RewriteContext,
192     vis: &ast::Visibility,
193     vp: &ast::ViewPath,
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| match vp.node {
203             // If we have an empty path list with no attributes, we erase it
204             ast::ViewPath_::ViewPathList(_, ref path_list)
205                 if path_list.is_empty() && attrs.is_empty() =>
206             {
207                 Some("".into())
208             }
209             _ => vp.rewrite(context, shape),
210         });
211     match rw {
212         Some(ref s) if !s.is_empty() => Some(format!("{}use {};", vis, s)),
213         _ => rw,
214     }
215 }
216
217 fn rewrite_imports(
218     context: &RewriteContext,
219     use_items: &[&ast::Item],
220     shape: Shape,
221     span: Span,
222 ) -> Option<String> {
223     let items = itemize_list(
224         context.codemap,
225         use_items.iter(),
226         "",
227         |item| item.span().lo(),
228         |item| item.span().hi(),
229         |item| {
230             let attrs_str = try_opt!(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 vp) => {
240                     try_opt!(rewrite_import(context, &item.vis, vp, &item.attrs, shape))
241                 }
242                 ast::ItemKind::ExternCrate(..) => try_opt!(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, vp: &ast::ViewPath) {
291         let span = item.span;
292         let shape = self.shape();
293         let rw = rewrite_import(&self.get_context(), &item.vis, vp, &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.buffer.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_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
319     let mut item_str = vpi.node.name.to_string();
320     if item_str == "self" {
321         item_str = "".to_owned();
322     }
323     let path_item_str = if path_str.is_empty() {
324         if item_str.is_empty() {
325             "self".to_owned()
326         } else {
327             item_str
328         }
329     } else if item_str.is_empty() {
330         path_str
331     } else {
332         format!("{}::{}", path_str, item_str)
333     };
334     append_alias(path_item_str, vpi)
335 }
336
337 fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
338     Some(append_alias(vpi.node.name.to_string(), vpi))
339 }
340
341 fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
342     match vpi.node.rename {
343         Some(rename) => format!("{} as {}", path_item_str, rename),
344         None => path_item_str,
345     }
346 }
347
348 #[derive(Eq, PartialEq)]
349 enum ImportItem<'a> {
350     // `self` or `self as a`
351     SelfImport(&'a str),
352     // name_one, name_two, ...
353     SnakeCase(&'a str),
354     // NameOne, NameTwo, ...
355     CamelCase(&'a str),
356     // NAME_ONE, NAME_TWO, ...
357     AllCaps(&'a str),
358     // Failed to format the import item
359     Invalid,
360 }
361
362 impl<'a> ImportItem<'a> {
363     fn from_str(s: &str) -> ImportItem {
364         if s == "self" || s.starts_with("self as") {
365             ImportItem::SelfImport(s)
366         } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
367             ImportItem::SnakeCase(s)
368         } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
369             ImportItem::AllCaps(s)
370         } else {
371             ImportItem::CamelCase(s)
372         }
373     }
374
375     fn from_opt_str(s: Option<&String>) -> ImportItem {
376         s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
377     }
378
379     fn to_str(&self) -> Option<&str> {
380         match *self {
381             ImportItem::SelfImport(s) |
382             ImportItem::SnakeCase(s) |
383             ImportItem::CamelCase(s) |
384             ImportItem::AllCaps(s) => Some(s),
385             ImportItem::Invalid => None,
386         }
387     }
388
389     fn to_u32(&self) -> u32 {
390         match *self {
391             ImportItem::SelfImport(..) => 0,
392             ImportItem::SnakeCase(..) => 1,
393             ImportItem::CamelCase(..) => 2,
394             ImportItem::AllCaps(..) => 3,
395             ImportItem::Invalid => 4,
396         }
397     }
398 }
399
400 impl<'a> PartialOrd for ImportItem<'a> {
401     fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
402         Some(self.cmp(other))
403     }
404 }
405
406 impl<'a> Ord for ImportItem<'a> {
407     fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
408         let res = self.to_u32().cmp(&other.to_u32());
409         if res != Ordering::Equal {
410             return res;
411         }
412         self.to_str().map_or(Ordering::Greater, |self_str| {
413             other
414                 .to_str()
415                 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
416         })
417     }
418 }
419
420 // Pretty prints a multi-item import.
421 // If the path list is empty, it leaves the braces empty.
422 fn rewrite_use_list(
423     shape: Shape,
424     path: &ast::Path,
425     path_list: &[ast::PathListItem],
426     span: Span,
427     context: &RewriteContext,
428 ) -> Option<String> {
429     // Returns a different option to distinguish `::foo` and `foo`
430     let path_str = try_opt!(rewrite_path(
431         context,
432         PathContext::Import,
433         None,
434         path,
435         shape,
436     ));
437
438     match path_list.len() {
439         0 => {
440             return rewrite_path(context, PathContext::Import, None, path, shape)
441                 .map(|path_str| format!("{}::{{}}", path_str));
442         }
443         1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
444         _ => (),
445     }
446
447     let path_str = if path_str.is_empty() {
448         path_str
449     } else {
450         format!("{}::", path_str)
451     };
452
453     // 2 = "{}"
454     let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
455
456     let mut items = {
457         // Dummy value, see explanation below.
458         let mut items = vec![ListItem::from_str("")];
459         let iter = itemize_list(
460             context.codemap,
461             path_list.iter(),
462             "}",
463             |vpi| vpi.span.lo(),
464             |vpi| vpi.span.hi(),
465             rewrite_path_item,
466             context.codemap.span_after(span, "{"),
467             span.hi(),
468             false,
469         );
470         items.extend(iter);
471         items
472     };
473
474     // We prefixed the item list with a dummy value so that we can
475     // potentially move "self" to the front of the vector without touching
476     // the rest of the items.
477     let has_self = move_self_to_front(&mut items);
478     let first_index = if has_self { 0 } else { 1 };
479
480     if context.config.reorder_imported_names() {
481         items[1..].sort_by(|a, b| {
482             let a = ImportItem::from_opt_str(a.item.as_ref());
483             let b = ImportItem::from_opt_str(b.item.as_ref());
484             a.cmp(&b)
485         });
486     }
487
488     let tactic = definitive_tactic(
489         &items[first_index..],
490         context.config.imports_layout(),
491         Separator::Comma,
492         remaining_width,
493     );
494
495     let nested_indent = match context.config.imports_indent() {
496         IndentStyle::Block => shape.indent.block_indent(context.config),
497         // 1 = `{`
498         IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
499     };
500
501     let nested_shape = match context.config.imports_indent() {
502         IndentStyle::Block => Shape::indented(nested_indent, context.config),
503         IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
504     };
505
506     let ends_with_newline = context.config.imports_indent() == IndentStyle::Block
507         && tactic != DefinitiveListTactic::Horizontal;
508
509     let fmt = ListFormatting {
510         tactic: tactic,
511         separator: ",",
512         trailing_separator: if ends_with_newline {
513             context.config.trailing_comma()
514         } else {
515             SeparatorTactic::Never
516         },
517         separator_place: SeparatorPlace::Back,
518         shape: nested_shape,
519         ends_with_newline: ends_with_newline,
520         preserve_newline: true,
521         config: context.config,
522     };
523     let list_str = try_opt!(write_list(&items[first_index..], &fmt));
524
525     let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
526     {
527         format!(
528             "{}{{\n{}{}\n{}}}",
529             path_str,
530             nested_shape.indent.to_string(context.config),
531             list_str,
532             shape.indent.to_string(context.config)
533         )
534     } else {
535         format!("{}{{{}}}", path_str, list_str)
536     };
537     Some(result)
538 }
539
540 // Returns true when self item was found.
541 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
542     match items
543         .iter()
544         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
545     {
546         Some(pos) => {
547             items[0] = items.remove(pos);
548             true
549         }
550         None => false,
551     }
552 }