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