]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Fix #1858 - "Don't erase a use with attributes attached"
[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::{self, Ordering};
12
13 use syntax::{ast, ptr};
14 use syntax::codemap::{BytePos, Span};
15
16 use Shape;
17 use codemap::SpanUtils;
18 use config::IndentStyle;
19 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
20             ListItem, Separator, SeparatorTactic};
21 use rewrite::{Rewrite, RewriteContext};
22 use types::{rewrite_path, PathContext};
23 use utils;
24 use visitor::FmtVisitor;
25
26 fn path_of(a: &ast::ViewPath_) -> &ast::Path {
27     match *a {
28         ast::ViewPath_::ViewPathSimple(_, ref p) => p,
29         ast::ViewPath_::ViewPathGlob(ref p) => p,
30         ast::ViewPath_::ViewPathList(ref p, _) => p,
31     }
32 }
33
34 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
35     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
36 }
37
38 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
39     for segment in a.segments.iter().zip(b.segments.iter()) {
40         let ord = compare_path_segments(segment.0, segment.1);
41         if ord != Ordering::Equal {
42             return ord;
43         }
44     }
45     a.segments.len().cmp(&b.segments.len())
46 }
47
48 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
49     let a_name_str = &*a.node.name.name.as_str();
50     let b_name_str = &*b.node.name.name.as_str();
51     let name_ordering = if a_name_str == "self" {
52         if b_name_str == "self" {
53             Ordering::Equal
54         } else {
55             Ordering::Less
56         }
57     } else {
58         if b_name_str == "self" {
59             Ordering::Greater
60         } else {
61             a_name_str.cmp(&b_name_str)
62         }
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(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         _ => None,
122     }
123 }
124
125 // TODO (some day) remove unused imports, expand globs, compress many single
126 // imports into a list import.
127
128 fn rewrite_view_path_prefix(
129     path: &ast::Path,
130     context: &RewriteContext,
131     shape: Shape,
132 ) -> Option<String> {
133     let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
134         path.segments.len() > 1
135     {
136         let path = &ast::Path {
137             span: path.span.clone(),
138             segments: path.segments[..path.segments.len() - 1].to_owned(),
139         };
140         try_opt!(rewrite_path(
141             context,
142             PathContext::Import,
143             None,
144             path,
145             shape,
146         ))
147     } else {
148         try_opt!(rewrite_path(
149             context,
150             PathContext::Import,
151             None,
152             path,
153             shape,
154         ))
155     };
156     Some(path_str)
157 }
158
159 impl Rewrite for ast::ViewPath {
160     // Returns an empty string when the ViewPath is empty (like foo::bar::{})
161     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
162         match self.node {
163             ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => {
164                 Some(String::new())
165             }
166             ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
167                 rewrite_use_list(shape, path, path_list, self.span, context)
168             }
169             ast::ViewPath_::ViewPathGlob(ref path) => {
170                 // 4 = "::*".len()
171                 let prefix_shape = try_opt!(shape.sub_width(3));
172                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
173                 Some(format!("{}::*", path_str))
174             }
175             ast::ViewPath_::ViewPathSimple(ident, ref path) => {
176                 let ident_str = ident.to_string();
177                 // 4 = " as ".len()
178                 let prefix_shape = try_opt!(shape.sub_width(ident_str.len() + 4));
179                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
180
181                 Some(if path.segments.last().unwrap().identifier == ident {
182                     path_str
183                 } else {
184                     format!("{} as {}", path_str, ident_str)
185                 })
186             }
187         }
188     }
189 }
190
191 impl<'a> FmtVisitor<'a> {
192     pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
193         // Find the location immediately before the first use item in the run. This must not lie
194         // before the current `self.last_pos`
195         let pos_before_first_use_item = use_items
196             .first()
197             .map(|p_i| {
198                 cmp::max(
199                     self.last_pos,
200                     p_i.attrs
201                         .iter()
202                         .map(|attr| attr.span.lo)
203                         .min()
204                         .unwrap_or(p_i.span.lo),
205                 )
206             })
207             .unwrap_or(self.last_pos);
208         // Construct a list of pairs, each containing a `use` item and the start of span before
209         // that `use` item.
210         let mut last_pos_of_prev_use_item = pos_before_first_use_item;
211         let mut ordered_use_items = use_items
212             .iter()
213             .map(|p_i| {
214                 let new_item = (&*p_i, last_pos_of_prev_use_item);
215                 last_pos_of_prev_use_item = p_i.span.hi;
216                 new_item
217             })
218             .collect::<Vec<_>>();
219         let pos_after_last_use_item = last_pos_of_prev_use_item;
220         // Order the imports by view-path & other import path properties
221         ordered_use_items.sort_by(|a, b| compare_use_items(a.0, b.0).unwrap());
222         // First, output the span before the first import
223         let prev_span_str = self.snippet(utils::mk_sp(self.last_pos, pos_before_first_use_item));
224         // Look for purely trailing space at the start of the prefix snippet before a linefeed, or
225         // a prefix that's entirely horizontal whitespace.
226         let prefix_span_start = match prev_span_str.find('\n') {
227             Some(offset) if prev_span_str[..offset].trim().is_empty() => {
228                 self.last_pos + BytePos(offset as u32)
229             }
230             None if prev_span_str.trim().is_empty() => pos_before_first_use_item,
231             _ => self.last_pos,
232         };
233         // Look for indent (the line part preceding the use is all whitespace) and excise that
234         // from the prefix
235         let span_end = match prev_span_str.rfind('\n') {
236             Some(offset) if prev_span_str[offset..].trim().is_empty() => {
237                 self.last_pos + BytePos(offset as u32)
238             }
239             _ => pos_before_first_use_item,
240         };
241
242         self.last_pos = prefix_span_start;
243         self.format_missing(span_end);
244         for ordered in ordered_use_items {
245             // Fake out the formatter by setting `self.last_pos` to the appropriate location before
246             // each item before visiting it.
247             self.last_pos = ordered.1;
248             self.visit_item(ordered.0);
249         }
250         self.last_pos = pos_after_last_use_item;
251     }
252
253     pub fn format_import(
254         &mut self,
255         vis: &ast::Visibility,
256         vp: &ast::ViewPath,
257         span: Span,
258         attrs: &[ast::Attribute],
259     ) {
260         let vis = utils::format_visibility(vis);
261         // 4 = `use `, 1 = `;`
262         let rw = Shape::indented(self.block_indent, self.config)
263             .offset_left(vis.len() + 4)
264             .and_then(|shape| shape.sub_width(1))
265             .and_then(|shape| match vp.node {
266                 // If we have an empty path with attributes attached, we want to skip erasing it
267                 ast::ViewPath_::ViewPathList(ref path, ref path_list)
268                     if path_list.is_empty() && !attrs.is_empty() =>
269                 {
270                     rewrite_path(&self.get_context(), PathContext::Import, None, path, shape)
271                         .map(|path_str| format!("{}::{{}}", path_str))
272                 }
273                 _ => vp.rewrite(&self.get_context(), shape),
274             });
275         match rw {
276             Some(ref s) if s.is_empty() => {
277                 // Format up to last newline
278                 let prev_span = utils::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                 let s = format!("{}use {};", vis, s);
288                 self.format_missing_with_indent(source!(self, span).lo);
289                 self.buffer.push_str(&s);
290                 self.last_pos = source!(self, span).hi;
291             }
292             None => {
293                 self.format_missing_with_indent(source!(self, span).lo);
294                 self.format_missing(source!(self, span).hi);
295             }
296         }
297     }
298 }
299
300 fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
301     let mut item_str = vpi.node.name.to_string();
302     if item_str == "self" {
303         item_str = "".to_owned();
304     }
305     let path_item_str = if path_str.is_empty() {
306         if item_str.is_empty() {
307             "self".to_owned()
308         } else {
309             item_str
310         }
311     } else if item_str.is_empty() {
312         path_str
313     } else {
314         format!("{}::{}", path_str, item_str)
315     };
316     append_alias(path_item_str, vpi)
317 }
318
319 fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
320     Some(append_alias(vpi.node.name.to_string(), vpi))
321 }
322
323 fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
324     match vpi.node.rename {
325         Some(rename) => format!("{} as {}", path_item_str, rename),
326         None => path_item_str,
327     }
328 }
329
330 #[derive(Eq, PartialEq)]
331 enum ImportItem<'a> {
332     // `self` or `self as a`
333     SelfImport(&'a str),
334     // name_one, name_two, ...
335     SnakeCase(&'a str),
336     // NameOne, NameTwo, ...
337     CamelCase(&'a str),
338     // NAME_ONE, NAME_TWO, ...
339     AllCaps(&'a str),
340     // Failed to format the import item
341     Invalid,
342 }
343
344 impl<'a> ImportItem<'a> {
345     fn from_str(s: &str) -> ImportItem {
346         if s == "self" || s.starts_with("self as") {
347             ImportItem::SelfImport(s)
348         } else if s.chars().all(|c| c.is_lowercase() || c == '_' || c == ' ') {
349             ImportItem::SnakeCase(s)
350         } else if s.chars().all(|c| c.is_uppercase() || c == '_' || c == ' ') {
351             ImportItem::AllCaps(s)
352         } else {
353             ImportItem::CamelCase(s)
354         }
355     }
356
357     fn from_opt_str(s: Option<&String>) -> ImportItem {
358         s.map_or(ImportItem::Invalid, |s| ImportItem::from_str(s))
359     }
360
361     fn to_str(&self) -> Option<&str> {
362         match *self {
363             ImportItem::SelfImport(s) |
364             ImportItem::SnakeCase(s) |
365             ImportItem::CamelCase(s) |
366             ImportItem::AllCaps(s) => Some(s),
367             ImportItem::Invalid => None,
368         }
369     }
370
371     fn to_u32(&self) -> u32 {
372         match *self {
373             ImportItem::SelfImport(..) => 0,
374             ImportItem::SnakeCase(..) => 1,
375             ImportItem::CamelCase(..) => 2,
376             ImportItem::AllCaps(..) => 3,
377             ImportItem::Invalid => 4,
378         }
379     }
380 }
381
382 impl<'a> PartialOrd for ImportItem<'a> {
383     fn partial_cmp(&self, other: &ImportItem<'a>) -> Option<Ordering> {
384         Some(self.cmp(other))
385     }
386 }
387
388 impl<'a> Ord for ImportItem<'a> {
389     fn cmp(&self, other: &ImportItem<'a>) -> Ordering {
390         let res = self.to_u32().cmp(&other.to_u32());
391         if res != Ordering::Equal {
392             return res;
393         }
394         self.to_str().map_or(Ordering::Greater, |self_str| {
395             other
396                 .to_str()
397                 .map_or(Ordering::Less, |other_str| self_str.cmp(other_str))
398         })
399     }
400 }
401
402 // Pretty prints a multi-item import.
403 // Assumes that path_list.len() > 0.
404 fn rewrite_use_list(
405     shape: Shape,
406     path: &ast::Path,
407     path_list: &[ast::PathListItem],
408     span: Span,
409     context: &RewriteContext,
410 ) -> Option<String> {
411     // Returns a different option to distinguish `::foo` and `foo`
412     let path_str = try_opt!(rewrite_path(
413         context,
414         PathContext::Import,
415         None,
416         path,
417         shape,
418     ));
419
420     match path_list.len() {
421         0 => unreachable!(),
422         1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
423         _ => (),
424     }
425
426     let path_str = if path_str.is_empty() {
427         path_str
428     } else {
429         format!("{}::", path_str)
430     };
431
432     // 2 = "{}"
433     let remaining_width = shape.width.checked_sub(path_str.len() + 2).unwrap_or(0);
434
435     let mut items = {
436         // Dummy value, see explanation below.
437         let mut items = vec![ListItem::from_str("")];
438         let iter = itemize_list(
439             context.codemap,
440             path_list.iter(),
441             "}",
442             |vpi| vpi.span.lo,
443             |vpi| vpi.span.hi,
444             rewrite_path_item,
445             context.codemap.span_after(span, "{"),
446             span.hi,
447         );
448         items.extend(iter);
449         items
450     };
451
452     // We prefixed the item list with a dummy value so that we can
453     // potentially move "self" to the front of the vector without touching
454     // the rest of the items.
455     let has_self = move_self_to_front(&mut items);
456     let first_index = if has_self { 0 } else { 1 };
457
458     if context.config.reorder_imported_names() {
459         items[1..].sort_by(|a, b| {
460             let a = ImportItem::from_opt_str(a.item.as_ref());
461             let b = ImportItem::from_opt_str(b.item.as_ref());
462             a.cmp(&b)
463         });
464     }
465
466     let tactic = definitive_tactic(
467         &items[first_index..],
468         context.config.imports_layout(),
469         Separator::Comma,
470         remaining_width,
471     );
472
473     let nested_indent = match context.config.imports_indent() {
474         IndentStyle::Block => shape.indent.block_indent(context.config),
475         // 1 = `{`
476         IndentStyle::Visual => shape.visual_indent(path_str.len() + 1).indent,
477     };
478
479     let nested_shape = match context.config.imports_indent() {
480         IndentStyle::Block => Shape::indented(nested_indent, context.config),
481         IndentStyle::Visual => Shape::legacy(remaining_width, nested_indent),
482     };
483
484     let ends_with_newline = context.config.imports_indent() == IndentStyle::Block &&
485         tactic != DefinitiveListTactic::Horizontal;
486
487     let fmt = ListFormatting {
488         tactic: tactic,
489         separator: ",",
490         trailing_separator: if ends_with_newline {
491             context.config.trailing_comma()
492         } else {
493             SeparatorTactic::Never
494         },
495         shape: nested_shape,
496         ends_with_newline: ends_with_newline,
497         preserve_newline: true,
498         config: context.config,
499     };
500     let list_str = try_opt!(write_list(&items[first_index..], &fmt));
501
502     let result = if list_str.contains('\n') && context.config.imports_indent() == IndentStyle::Block
503     {
504         format!(
505             "{}{{\n{}{}\n{}}}",
506             path_str,
507             nested_shape.indent.to_string(context.config),
508             list_str,
509             shape.indent.to_string(context.config)
510         )
511     } else {
512         format!("{}{{{}}}", path_str, list_str)
513     };
514     Some(result)
515 }
516
517 // Returns true when self item was found.
518 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
519     match items
520         .iter()
521         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self"))
522     {
523         Some(pos) => {
524             items[0] = items.remove(pos);
525             true
526         }
527         None => false,
528     }
529 }