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