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