]> git.lizzy.rs Git - rust.git/blob - src/imports.rs
Format if-else expressions
[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 {
64             2
65         } else {
66             0
67         };
68         // 5 = "use " + {
69         let indent = path_str.len() + 5 + path_separation_w + vis.len();
70
71         // 2 = } + ;
72         let used_width = indent + 2;
73
74         // Break as early as possible when we've blown our budget.
75         let remaining_line_budget = one_line_budget.checked_sub(used_width).unwrap_or(0);
76         let remaining_multi_budget = multi_line_budget.checked_sub(used_width).unwrap_or(0);
77
78         let fmt = ListFormatting {
79             tactic: ListTactic::Mixed,
80             separator: ",",
81             trailing_separator: SeparatorTactic::Never,
82             indent: block_indent + indent,
83             h_width: remaining_line_budget,
84             v_width: remaining_multi_budget,
85             ends_with_newline: true,
86         };
87
88         let mut items = itemize_list(self.codemap,
89                                      vec![ListItem::from_str("")], /* Dummy value, explanation
90                                                                     * below */
91                                      path_list.iter(),
92                                      ",",
93                                      "}",
94                                      |vpi| vpi.span.lo,
95                                      |vpi| vpi.span.hi,
96                                      |vpi| match vpi.node {
97                                          ast::PathListItem_::PathListIdent{ name, .. } => {
98                                              token::get_ident(name).to_string()
99                                          }
100                                          ast::PathListItem_::PathListMod{ .. } => {
101                                              "self".to_owned()
102                                          }
103                                      },
104                                      span_after(span, "{", self.codemap),
105                                      span.hi);
106
107         // We prefixed the item list with a dummy value so that we can
108         // potentially move "self" to the front of the vector without touching
109         // the rest of the items.
110         // FIXME: Make more efficient by using a linked list? That would
111         // require changes to the signatures of itemize_list and write_list.
112         let has_self = move_self_to_front(&mut items);
113         let first_index = if has_self {
114             0
115         } else {
116             1
117         };
118
119         if self.config.reorder_imports {
120             items[1..].sort_by(|a, b| a.item.cmp(&b.item));
121         }
122
123         let list = write_list(&items[first_index..], &fmt);
124
125         Some(if path_str.len() == 0 {
126             format!("{}use {{{}}};", vis, list)
127         } else {
128             format!("{}use {}::{{{}}};", vis, path_str, list)
129         })
130     }
131 }
132
133 // Returns true when self item was found.
134 fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
135     match items.iter().position(|item| item.item == "self") {
136         Some(pos) => {
137             items[0] = items.remove(pos);
138             true
139         },
140         None => false
141     }
142 }