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