]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
1973115cd435046baac35eddb18f2a6fb1837b71
[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 visitor::FmtVisitor;
12 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
13 use utils::{span_after, format_visibility};
14
15 use syntax::ast;
16 use syntax::parse::token;
17 use syntax::print::pprust;
18 use syntax::codemap::Span;
19
20 // TODO (some day) remove unused imports, expand globs, compress many single imports into a list import
21
22 fn rewrite_single_use_list(path_str: String, vpi: ast::PathListItem, vis: &str) -> String {
23     if let ast::PathListItem_::PathListIdent{ name, .. } = vpi.node {
24         let name_str = token::get_ident(name).to_string();
25         if path_str.len() == 0 {
26             format!("{}use {};", vis, name_str)
27         } else {
28             format!("{}use {}::{};", vis, path_str, name_str)
29         }
30     } else {
31         if path_str.len() != 0 {
32             format!("{}use {};", vis, path_str)
33         } else {
34             // This catches the import: use {self}, which is a compiler error, so we just
35             // leave it alone.
36             format!("{}use {{self}};", vis)
37         }
38     }
39 }
40
41 impl<'a> FmtVisitor<'a> {
42     // Basically just pretty prints a multi-item import.
43     // Returns None when the import can be removed.
44     pub fn rewrite_use_list(&self,
45                             block_indent: usize,
46                             one_line_budget: usize, // excluding indentation
47                             multi_line_budget: usize,
48                             path: &ast::Path,
49                             path_list: &[ast::PathListItem],
50                             visibility: ast::Visibility,
51                             span: Span)
52                             -> Option<String> {
53         let path_str = pprust::path_to_string(path);
54         let vis = format_visibility(visibility);
55
56         match path_list.len() {
57             0 => return None,
58             1 => return Some(rewrite_single_use_list(path_str, path_list[0], vis)),
59             _ => ()
60         }
61
62         // 2 = ::
63         let path_separation_w = if path_str.len() > 0 { 2 } else { 0 };
64         // 5 = "use " + {
65         let indent = path_str.len() + 5 + path_separation_w + vis.len();
66
67         // 2 = } + ;
68         let used_width = indent + 2;
69
70         // Break as early as possible when we've blown our budget.
71         let remaining_line_budget = one_line_budget.checked_sub(used_width).unwrap_or(0);
72         let remaining_multi_budget = multi_line_budget.checked_sub(used_width).unwrap_or(0);
73
74         let fmt = ListFormatting {
75             tactic: ListTactic::Mixed,
76             separator: ",",
77             trailing_separator: SeparatorTactic::Never,
78             indent: block_indent + indent,
79             h_width: remaining_line_budget,
80             v_width: remaining_multi_budget,
81             ends_with_newline: true,
82         };
83
84         let mut items = itemize_list(self.codemap,
85                                      vec![ListItem::from_str("")], /* Dummy value, explanation
86                                                                     * below */
87                                      path_list.iter(),
88                                      ",",
89                                      "}",
90                                      |vpi| vpi.span.lo,
91                                      |vpi| vpi.span.hi,
92                                      |vpi| match vpi.node {
93                                          ast::PathListItem_::PathListIdent{ name, .. } => {
94                                              token::get_ident(name).to_string()
95                                          }
96                                          ast::PathListItem_::PathListMod{ .. } => {
97                                              "self".to_owned()
98                                          }
99                                      },
100                                      span_after(span, "{", self.codemap),
101                                      span.hi);
102
103         // We prefixed the item list with a dummy value so that we can
104         // potentially move "self" to the front of the vector without touching
105         // the rest of the items.
106         // FIXME: Make more efficient by using a linked list? That would
107         // require changes to the signatures of itemize_list and write_list.
108         let has_self = move_self_to_front(&mut items);
109         let first_index = if has_self { 0 } else { 1 };
110
111         if self.config.reorder_imports {
112             items[1..].sort_by(|a, b| a.item.cmp(&b.item));
113         }
114
115         let list = write_list(&items[first_index..], &fmt);
116
117         Some(if path_str.len() == 0 {
118             format!("{}use {{{}}};", vis, list)
119         } else {
120             format!("{}use {}::{{{}}};", vis, path_str, list)
121         })
122     }
123 }
124
125 // Returns true when self item was found.
126 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
127     match items.iter().position(|item| item.item == "self") {
128         Some(pos) => {
129             items[0] = items.remove(pos);
130             true
131         },
132         None => false
133     }
134 }