]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Indent fix
[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 lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
12 use utils::span_after;
13 use rewrite::{Rewrite, RewriteContext};
14 use config::Config;
15
16 use syntax::ast;
17 use syntax::parse::token;
18 use syntax::print::pprust;
19 use syntax::codemap::{CodeMap, Span};
20
21 // TODO (some day) remove unused imports, expand globs, compress many single 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: usize) -> Option<String> {
26         match self.node {
27             ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
28                 Some(rewrite_use_list(width,
29                                       offset,
30                                       path,
31                                       path_list,
32                                       self.span,
33                                       context.codemap,
34                                       context.config).unwrap_or("".to_owned()))
35             }
36             ast::ViewPath_::ViewPathGlob(_) => {
37                 // FIXME convert to list?
38                 None
39             }
40             ast::ViewPath_::ViewPathSimple(_,_) => {
41                 None
42             }
43         }
44     }
45 }
46
47 fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem) -> String {
48     if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
49         let name_str = token::get_ident(name).to_string();
50         if path_str.len() == 0 {
51             name_str
52         } else {
53             format!("{}::{}", path_str, name_str)
54         }
55     } else {
56         if path_str.len() != 0 {
57             path_str
58         } else {
59             // This catches the import: use {self}, which is a compiler error, so we just
60             // leave it alone.
61             "{self}".to_owned()
62         }
63     }
64 }
65
66 // Basically just pretty prints a multi-item import.
67 // Returns None when the import can be removed.
68 pub fn rewrite_use_list(width: usize,
69                         offset: usize,
70                         path: &ast::Path,
71                         path_list: &[ast::PathListItem],
72                         span: Span,
73                         codemap: &CodeMap,
74                         config: &Config)
75                         -> Option<String> {
76     let path_str = pprust::path_to_string(path);
77
78     match path_list.len() {
79         0 => return None,
80         1 => return Some(rewrite_single_use_list(path_str, path_list[0])),
81         _ => ()
82     }
83
84     // 2 = ::
85     let path_separation_w = if path_str.len() > 0 {
86         2
87     } else {
88         0
89     };
90     // 1 = {
91     let supp_indent = path_str.len() + path_separation_w + 1;
92     // 1 = }
93     let remaining_width = width.checked_sub(supp_indent + 1).unwrap_or(0);
94
95     let fmt = ListFormatting {
96         tactic: ListTactic::Mixed,
97         separator: ",",
98         trailing_separator: SeparatorTactic::Never,
99         indent: offset + supp_indent,
100         h_width: remaining_width,
101         // FIXME This is too conservative, and will not use all width
102         // available
103         // (loose 1 column (";"))
104         v_width: remaining_width,
105         ends_with_newline: true,
106     };
107
108     let mut items = itemize_list(codemap,
109                                  vec![ListItem::from_str("")], /* Dummy value, explanation
110                                                                 * below */
111                                  path_list.iter(),
112                                  ",",
113                                  "}",
114                                  |vpi| vpi.span.lo,
115                                  |vpi| vpi.span.hi,
116                                  |vpi| match vpi.node {
117                                      ast::PathListItem_::PathListIdent{ name, .. } => {
118                                          token::get_ident(name).to_string()
119                                      }
120                                      ast::PathListItem_::PathListMod{ .. } => {
121                                          "self".to_owned()
122                                      }
123                                  },
124                                  span_after(span, "{", codemap),
125                                  span.hi);
126
127     // We prefixed the item list with a dummy value so that we can
128     // potentially move "self" to the front of the vector without touching
129     // the rest of the items.
130     // FIXME: Make more efficient by using a linked list? That would
131     // require changes to the signatures of itemize_list and write_list.
132     let has_self = move_self_to_front(&mut items);
133     let first_index = if has_self {
134         0
135     } else {
136         1
137     };
138
139     if config.reorder_imports {
140         items[1..].sort_by(|a, b| a.item.cmp(&b.item));
141     }
142
143     let list = write_list(&items[first_index..], &fmt);
144
145     Some(if path_str.len() == 0 {
146             format!("{{{}}}", list)
147         } else {
148             format!("{}::{{{}}}", path_str, list)
149         })
150 }
151
152 // Returns true when self item was found.
153 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
154     match items.iter().position(|item| item.item == "self") {
155         Some(pos) => {
156             items[0] = items.remove(pos);
157             true
158         },
159         None => false
160     }
161 }