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