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