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