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