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