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