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