]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Merge pull request #1786 from euclio/globs
[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 Shape;
12 use utils;
13 use syntax::codemap::{BytePos, Span};
14 use codemap::SpanUtils;
15 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, definitive_tactic};
16 use types::{rewrite_path, PathContext};
17 use rewrite::{Rewrite, RewriteContext};
18 use visitor::FmtVisitor;
19 use std::cmp::{self, Ordering};
20
21 use syntax::{ast, ptr};
22
23 fn path_of(a: &ast::ViewPath_) -> &ast::Path {
24     match *a {
25         ast::ViewPath_::ViewPathSimple(_, ref p) => p,
26         ast::ViewPath_::ViewPathGlob(ref p) => p,
27         ast::ViewPath_::ViewPathList(ref p, _) => p,
28     }
29 }
30
31 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
32     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
33 }
34
35 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
36     for segment in a.segments.iter().zip(b.segments.iter()) {
37         let ord = compare_path_segments(segment.0, segment.1);
38         if ord != Ordering::Equal {
39             return ord;
40         }
41     }
42     a.segments.len().cmp(&b.segments.len())
43 }
44
45 fn compare_path_list_items(a: &ast::PathListItem, b: &ast::PathListItem) -> Ordering {
46     let a_name_str = &*a.node.name.name.as_str();
47     let b_name_str = &*b.node.name.name.as_str();
48     let name_ordering = if a_name_str == "self" {
49         if b_name_str == "self" {
50             Ordering::Equal
51         } else {
52             Ordering::Less
53         }
54     } else {
55         if b_name_str == "self" {
56             Ordering::Greater
57         } else {
58             a_name_str.cmp(&b_name_str)
59         }
60     };
61     if name_ordering == Ordering::Equal {
62         match a.node.rename {
63             Some(a_rename) => match b.node.rename {
64                 Some(b_rename) => a_rename.name.as_str().cmp(&b_rename.name.as_str()),
65                 None => Ordering::Greater,
66             },
67             None => Ordering::Less,
68         }
69     } else {
70         name_ordering
71     }
72 }
73
74 fn compare_path_list_item_lists(
75     a_items: &Vec<ast::PathListItem>,
76     b_items: &Vec<ast::PathListItem>,
77 ) -> Ordering {
78     let mut a = a_items.clone();
79     let mut b = b_items.clone();
80     a.sort_by(|a, b| compare_path_list_items(a, b));
81     b.sort_by(|a, b| compare_path_list_items(a, b));
82     for comparison_pair in a.iter().zip(b.iter()) {
83         let ord = compare_path_list_items(comparison_pair.0, comparison_pair.1);
84         if ord != Ordering::Equal {
85             return ord;
86         }
87     }
88     a.len().cmp(&b.len())
89 }
90
91 fn compare_view_path_types(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
92     use syntax::ast::ViewPath_::*;
93     match (a, b) {
94         (&ViewPathSimple(..), &ViewPathSimple(..)) => Ordering::Equal,
95         (&ViewPathSimple(..), _) => Ordering::Less,
96         (&ViewPathGlob(_), &ViewPathSimple(..)) => Ordering::Greater,
97         (&ViewPathGlob(_), &ViewPathGlob(_)) => Ordering::Equal,
98         (&ViewPathGlob(_), &ViewPathList(..)) => Ordering::Less,
99         (&ViewPathList(_, ref a_items), &ViewPathList(_, ref b_items)) => {
100             compare_path_list_item_lists(a_items, b_items)
101         }
102         (&ViewPathList(..), _) => Ordering::Greater,
103     }
104 }
105
106 fn compare_view_paths(a: &ast::ViewPath_, b: &ast::ViewPath_) -> Ordering {
107     match compare_paths(path_of(a), path_of(b)) {
108         Ordering::Equal => compare_view_path_types(a, b),
109         cmp => cmp,
110     }
111 }
112
113 fn compare_use_items(a: &ast::Item, b: &ast::Item) -> Option<Ordering> {
114     match (&a.node, &b.node) {
115         (&ast::ItemKind::Use(ref a_vp), &ast::ItemKind::Use(ref b_vp)) => {
116             Some(compare_view_paths(&a_vp.node, &b_vp.node))
117         }
118         _ => None,
119     }
120 }
121
122 // TODO (some day) remove unused imports, expand globs, compress many single
123 // imports into a list import.
124
125 fn rewrite_view_path_prefix(
126     path: &ast::Path,
127     context: &RewriteContext,
128     shape: Shape,
129 ) -> Option<String> {
130     let path_str = if path.segments.last().unwrap().identifier.to_string() == "self" &&
131         path.segments.len() > 1
132     {
133         let path = &ast::Path {
134             span: path.span.clone(),
135             segments: path.segments[..path.segments.len() - 1].to_owned(),
136         };
137         try_opt!(rewrite_path(
138             context,
139             PathContext::Import,
140             None,
141             path,
142             shape,
143         ))
144     } else {
145         try_opt!(rewrite_path(
146             context,
147             PathContext::Import,
148             None,
149             path,
150             shape,
151         ))
152     };
153     Some(path_str)
154 }
155
156 impl Rewrite for ast::ViewPath {
157     // Returns an empty string when the ViewPath is empty (like foo::bar::{})
158     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
159         match self.node {
160             ast::ViewPath_::ViewPathList(_, ref path_list) if path_list.is_empty() => {
161                 Some(String::new())
162             }
163             ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
164                 rewrite_use_list(shape, path, path_list, self.span, context)
165             }
166             ast::ViewPath_::ViewPathGlob(ref path) => {
167                 // 4 = "::*".len()
168                 let prefix_shape = try_opt!(shape.sub_width(3));
169                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
170                 Some(format!("{}::*", path_str))
171             }
172             ast::ViewPath_::ViewPathSimple(ident, ref path) => {
173                 let ident_str = ident.to_string();
174                 // 4 = " as ".len()
175                 let prefix_shape = try_opt!(shape.sub_width(ident_str.len() + 4));
176                 let path_str = try_opt!(rewrite_view_path_prefix(path, context, prefix_shape));
177
178                 Some(if path.segments.last().unwrap().identifier == ident {
179                     path_str
180                 } else {
181                     format!("{} as {}", path_str, ident_str)
182                 })
183             }
184         }
185     }
186 }
187
188 impl<'a> FmtVisitor<'a> {
189     pub fn format_imports(&mut self, use_items: &[ptr::P<ast::Item>]) {
190         // Find the location immediately before the first use item in the run. This must not lie
191         // before the current `self.last_pos`
192         let pos_before_first_use_item = use_items
193             .first()
194             .map(|p_i| {
195                 cmp::max(
196                     self.last_pos,
197                     p_i.attrs
198                         .iter()
199                         .map(|attr| attr.span.lo)
200                         .min()
201                         .unwrap_or(p_i.span.lo),
202                 )
203             })
204             .unwrap_or(self.last_pos);
205         // Construct a list of pairs, each containing a `use` item and the start of span before
206         // that `use` item.
207         let mut last_pos_of_prev_use_item = pos_before_first_use_item;
208         let mut ordered_use_items = use_items
209             .iter()
210             .map(|p_i| {
211                 let new_item = (&*p_i, last_pos_of_prev_use_item);
212                 last_pos_of_prev_use_item = p_i.span.hi;
213                 new_item
214             })
215             .collect::<Vec<_>>();
216         let pos_after_last_use_item = last_pos_of_prev_use_item;
217         // Order the imports by view-path & other import path properties
218         ordered_use_items.sort_by(|a, b| compare_use_items(a.0, b.0).unwrap());
219         // First, output the span before the first import
220         let prev_span_str = self.snippet(utils::mk_sp(self.last_pos, pos_before_first_use_item));
221         // Look for purely trailing space at the start of the prefix snippet before a linefeed, or
222         // a prefix that's entirely horizontal whitespace.
223         let prefix_span_start = match prev_span_str.find('\n') {
224             Some(offset) if prev_span_str[..offset].trim().is_empty() => {
225                 self.last_pos + BytePos(offset as u32)
226             }
227             None if prev_span_str.trim().is_empty() => pos_before_first_use_item,
228             _ => self.last_pos,
229         };
230         // Look for indent (the line part preceding the use is all whitespace) and excise that
231         // from the prefix
232         let span_end = match prev_span_str.rfind('\n') {
233             Some(offset) if prev_span_str[offset..].trim().is_empty() => {
234                 self.last_pos + BytePos(offset as u32)
235             }
236             _ => pos_before_first_use_item,
237         };
238
239         self.last_pos = prefix_span_start;
240         self.format_missing(span_end);
241         for ordered in ordered_use_items {
242             // Fake out the formatter by setting `self.last_pos` to the appropriate location before
243             // each item before visiting it.
244             self.last_pos = ordered.1;
245             self.visit_item(ordered.0);
246         }
247         self.last_pos = pos_after_last_use_item;
248     }
249
250     pub fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
251         let vis = utils::format_visibility(vis);
252         let mut offset = self.block_indent;
253         offset.alignment += vis.len() + "use ".len();
254         // 1 = ";"
255         match vp.rewrite(
256             &self.get_context(),
257             Shape::legacy(self.config.max_width() - offset.width() - 1, offset),
258         ) {
259             Some(ref s) if s.is_empty() => {
260                 // Format up to last newline
261                 let prev_span = utils::mk_sp(self.last_pos, source!(self, span).lo);
262                 let span_end = match self.snippet(prev_span).rfind('\n') {
263                     Some(offset) => self.last_pos + BytePos(offset as u32),
264                     None => source!(self, span).lo,
265                 };
266                 self.format_missing(span_end);
267                 self.last_pos = source!(self, span).hi;
268             }
269             Some(ref s) => {
270                 let s = format!("{}use {};", vis, s);
271                 self.format_missing_with_indent(source!(self, span).lo);
272                 self.buffer.push_str(&s);
273                 self.last_pos = source!(self, span).hi;
274             }
275             None => {
276                 self.format_missing_with_indent(source!(self, span).lo);
277                 self.format_missing(source!(self, span).hi);
278             }
279         }
280     }
281 }
282
283 fn rewrite_single_use_list(path_str: String, vpi: &ast::PathListItem) -> String {
284     let mut item_str = vpi.node.name.to_string();
285     if item_str == "self" {
286         item_str = "".to_owned();
287     }
288     let path_item_str = if path_str.is_empty() {
289         if item_str.is_empty() {
290             "self".to_owned()
291         } else {
292             item_str
293         }
294     } else if item_str.is_empty() {
295         path_str
296     } else {
297         format!("{}::{}", path_str, item_str)
298     };
299     append_alias(path_item_str, vpi)
300 }
301
302 fn rewrite_path_item(vpi: &&ast::PathListItem) -> Option<String> {
303     Some(append_alias(vpi.node.name.to_string(), vpi))
304 }
305
306 fn append_alias(path_item_str: String, vpi: &ast::PathListItem) -> String {
307     match vpi.node.rename {
308         Some(rename) => format!("{} as {}", path_item_str, rename),
309         None => path_item_str,
310     }
311 }
312
313 // Pretty prints a multi-item import.
314 // Assumes that path_list.len() > 0.
315 pub fn rewrite_use_list(
316     shape: Shape,
317     path: &ast::Path,
318     path_list: &[ast::PathListItem],
319     span: Span,
320     context: &RewriteContext,
321 ) -> Option<String> {
322     // Returns a different option to distinguish `::foo` and `foo`
323     let path_str = try_opt!(rewrite_path(
324         context,
325         PathContext::Import,
326         None,
327         path,
328         shape,
329     ));
330
331     match path_list.len() {
332         0 => unreachable!(),
333         1 => return Some(rewrite_single_use_list(path_str, &path_list[0])),
334         _ => (),
335     }
336
337     let colons_offset = if path_str.is_empty() { 0 } else { 2 };
338
339     // 2 = "{}"
340     let remaining_width = shape
341         .width
342         .checked_sub(path_str.len() + 2 + colons_offset)
343         .unwrap_or(0);
344
345     let mut items = {
346         // Dummy value, see explanation below.
347         let mut items = vec![ListItem::from_str("")];
348         let iter = itemize_list(
349             context.codemap,
350             path_list.iter(),
351             "}",
352             |vpi| vpi.span.lo,
353             |vpi| vpi.span.hi,
354             rewrite_path_item,
355             context.codemap.span_after(span, "{"),
356             span.hi,
357         );
358         items.extend(iter);
359         items
360     };
361
362     // We prefixed the item list with a dummy value so that we can
363     // potentially move "self" to the front of the vector without touching
364     // the rest of the items.
365     let has_self = move_self_to_front(&mut items);
366     let first_index = if has_self { 0 } else { 1 };
367
368     if context.config.reorder_imported_names() {
369         items[1..].sort_by(|a, b| a.item.cmp(&b.item));
370     }
371
372
373     let tactic = definitive_tactic(
374         &items[first_index..],
375         ::lists::ListTactic::Mixed,
376         remaining_width,
377     );
378
379     let fmt = ListFormatting {
380         tactic: tactic,
381         separator: ",",
382         trailing_separator: SeparatorTactic::Never,
383         // Add one to the indent to account for "{"
384         shape: Shape::legacy(
385             remaining_width,
386             shape.indent + path_str.len() + colons_offset + 1,
387         ),
388         ends_with_newline: false,
389         config: context.config,
390     };
391     let list_str = try_opt!(write_list(&items[first_index..], &fmt));
392
393     Some(if path_str.is_empty() {
394         format!("{{{}}}", list_str)
395     } else {
396         format!("{}::{{{}}}", path_str, list_str)
397     })
398 }
399
400 // Returns true when self item was found.
401 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
402     match items
403         .iter()
404         .position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self")) {
405         Some(pos) => {
406             items[0] = items.remove(pos);
407             true
408         }
409         None => false,
410     }
411 }