]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Merge pull request #1016 from rust-lang-nursery/try-double-indent
[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 codemap::SpanUtils;
13 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, definitive_tactic};
14 use types::rewrite_path;
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::PathListItemKind::Ident { 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::PathListItemKind::Ident { name, .. } => name.to_string(),
78         ast::PathListItemKind::Mod { .. } => "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::PathListItemKind::Ident { rename: Some(rename), .. } |
87         ast::PathListItemKind::Mod { 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() { 2 } else { 0 };
115     // 1 = {
116     let supp_indent = path_str.len() + path_separation_w + 1;
117     // 1 = }
118     let remaining_width = width.checked_sub(supp_indent + 1).unwrap_or(0);
119
120     let mut items = {
121         // Dummy value, see explanation below.
122         let mut items = vec![ListItem::from_str("")];
123         let iter = itemize_list(context.codemap,
124                                 path_list.iter(),
125                                 "}",
126                                 |vpi| vpi.span.lo,
127                                 |vpi| vpi.span.hi,
128                                 rewrite_path_item,
129                                 context.codemap.span_after(span, "{"),
130                                 span.hi);
131         items.extend(iter);
132         items
133     };
134
135     // We prefixed the item list with a dummy value so that we can
136     // potentially move "self" to the front of the vector without touching
137     // the rest of the items.
138     let has_self = move_self_to_front(&mut items);
139     let first_index = if has_self { 0 } else { 1 };
140
141     if context.config.reorder_imports {
142         items[1..].sort_by(|a, b| a.item.cmp(&b.item));
143     }
144
145     let tactic = definitive_tactic(&items[first_index..],
146                                    ::lists::ListTactic::Mixed,
147                                    remaining_width);
148     let fmt = ListFormatting {
149         tactic: tactic,
150         separator: ",",
151         trailing_separator: SeparatorTactic::Never,
152         indent: offset + supp_indent,
153         // FIXME This is too conservative, and will not use all width
154         // available
155         // (loose 1 column (";"))
156         width: remaining_width,
157         ends_with_newline: false,
158         config: context.config,
159     };
160     let list_str = try_opt!(write_list(&items[first_index..], &fmt));
161
162     Some(if path_str.is_empty() {
163         format!("{{{}}}", list_str)
164     } else {
165         format!("{}::{{{}}}", path_str, list_str)
166     })
167 }
168
169 // Returns true when self item was found.
170 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
171     match items.iter().position(|item| item.item.as_ref().map(|x| &x[..]) == Some("self")) {
172         Some(pos) => {
173             items[0] = items.remove(pos);
174             true
175         }
176         None => false,
177     }
178 }