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