]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Formatting
[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 lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
12 use utils::span_after;
13 use rewrite::{Rewrite, RewriteContext};
14
15 use syntax::ast;
16 use syntax::codemap::Span;
17
18 // TODO (some day) remove unused imports, expand globs, compress many single
19 // imports into a list import.
20
21 impl Rewrite for ast::ViewPath {
22     // Returns an empty string when the ViewPath is empty (like foo::bar::{})
23     fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
24         match self.node {
25             ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
26                 Some(rewrite_use_list(width,
27                                       offset,
28                                       path,
29                                       path_list,
30                                       self.span,
31                                       context).unwrap_or("".to_owned()))
32             }
33             ast::ViewPath_::ViewPathGlob(_) => {
34                 // FIXME convert to list?
35                 None
36             }
37             ast::ViewPath_::ViewPathSimple(ident, ref path) => {
38                 let ident_str = ident.to_string();
39                 // 4 = " as ".len()
40                 let path_str = try_opt!(path.rewrite(context, width - ident_str.len() - 4, offset));
41
42                 Some(if path.segments.last().unwrap().identifier == ident {
43                         path_str
44                     } else {
45                         format!("{} as {}", path_str, ident_str)
46                     })
47             }
48         }
49     }
50 }
51
52 fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem) -> String {
53     if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
54         if path_str.len() == 0 {
55             name.to_string()
56         } else {
57             format!("{}::{}", path_str, name)
58         }
59     } else {
60         if path_str.len() != 0 {
61             path_str
62         } else {
63             // This catches the import: use {self}, which is a compiler error, so we just
64             // leave it alone.
65             "{self}".to_owned()
66         }
67     }
68 }
69
70 // Basically just pretty prints a multi-item import.
71 // Returns None when the import can be removed.
72 pub fn rewrite_use_list(width: usize,
73                         offset: usize,
74                         path: &ast::Path,
75                         path_list: &[ast::PathListItem],
76                         span: Span,
77                         context: &RewriteContext)
78                         -> Option<String> {
79     // 1 = {}
80     let path_str = try_opt!(path.rewrite(context, width - 1, offset));
81
82     match path_list.len() {
83         0 => return None,
84         1 => return Some(rewrite_single_use_list(path_str, path_list[0])),
85         _ => (),
86     }
87
88     // 2 = ::
89     let path_separation_w = if path_str.len() > 0 {
90         2
91     } else {
92         0
93     };
94     // 1 = {
95     let supp_indent = path_str.len() + path_separation_w + 1;
96     // 1 = }
97     let remaining_width = width.checked_sub(supp_indent + 1).unwrap_or(0);
98
99     let fmt = ListFormatting {
100         tactic: ListTactic::Mixed,
101         separator: ",",
102         trailing_separator: SeparatorTactic::Never,
103         indent: offset + supp_indent,
104         h_width: remaining_width,
105         // FIXME This is too conservative, and will not use all width
106         // available
107         // (loose 1 column (";"))
108         v_width: remaining_width,
109         ends_with_newline: false,
110     };
111
112     let mut items = {
113         // Dummy value, see explanation below.
114         let mut items = vec![ListItem::from_str("")];
115         let iter = itemize_list(context.codemap,
116                                 path_list.iter(),
117                                 "}",
118                                 |vpi| vpi.span.lo,
119                                 |vpi| vpi.span.hi,
120                                 |vpi| match vpi.node {
121                                      ast::PathListItem_::PathListIdent{ name, .. } => {
122                                          name.to_string()
123                                      }
124                                      ast::PathListItem_::PathListMod{ .. } => {
125                                          "self".to_owned()
126                                      }
127                                 },
128                                 span_after(span, "{", context.codemap),
129                                 span.hi);
130         items.extend(iter);
131         items
132     };
133
134     // We prefixed the item list with a dummy value so that we can
135     // potentially move "self" to the front of the vector without touching
136     // the rest of the items.
137     // FIXME: Make more efficient by using a linked list? That would require
138     // changes to the signatures of write_list.
139     let has_self = move_self_to_front(&mut items);
140     let first_index = if has_self {
141         0
142     } else {
143         1
144     };
145
146     if context.config.reorder_imports {
147         items[1..].sort_by(|a, b| a.item.cmp(&b.item));
148     }
149
150     let list = write_list(&items[first_index..], &fmt);
151
152     Some(if path_str.len() == 0 {
153             format!("{{{}}}", list)
154         } else {
155             format!("{}::{{{}}}", path_str, list)
156         })
157 }
158
159 // Returns true when self item was found.
160 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
161     match items.iter().position(|item| item.item == "self") {
162         Some(pos) => {
163             items[0] = items.remove(pos);
164             true
165         }
166         None => false,
167     }
168 }