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