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