]> git.lizzy.rs Git - rust.git/blob - src/reorder.rs
Merge pull request #2576 from topecongiro/merge-imports
[rust.git] / src / reorder.rs
1 // Copyright 2018 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 //! Reorder items.
12 //!
13 //! `mod`, `extern crate` and `use` declarations are reorderd in alphabetical
14 //! order. Trait items are reordered in pre-determined order (associated types
15 //! and constants comes before methods).
16
17 // TODO(#2455): Reorder trait items.
18
19 use config::{lists::*, Config};
20 use syntax::{ast, attr, codemap::Span};
21
22 use attr::filter_inline_attrs;
23 use codemap::LineRangeUtils;
24 use comment::combine_strs_with_missing_comments;
25 use imports::UseTree;
26 use items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
27 use lists::{itemize_list, write_list, ListFormatting, ListItem};
28 use rewrite::{Rewrite, RewriteContext};
29 use shape::Shape;
30 use spanned::Spanned;
31 use utils::mk_sp;
32 use visitor::FmtVisitor;
33
34 use std::cmp::{Ord, Ordering};
35
36 /// Choose the ordering between the given two items.
37 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
38     match (&a.node, &b.node) {
39         (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
40             a.ident.name.as_str().cmp(&b.ident.name.as_str())
41         }
42         (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
43             // `extern crate foo as bar;`
44             //               ^^^ Comparing this.
45             let a_orig_name =
46                 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
47             let b_orig_name =
48                 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
49             let result = a_orig_name.cmp(&b_orig_name);
50             if result != Ordering::Equal {
51                 return result;
52             }
53
54             // `extern crate foo as bar;`
55             //                      ^^^ Comparing this.
56             match (a_name, b_name) {
57                 (Some(..), None) => Ordering::Greater,
58                 (None, Some(..)) => Ordering::Less,
59                 (None, None) => Ordering::Equal,
60                 (Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
61             }
62         }
63         _ => unreachable!(),
64     }
65 }
66
67 fn wrap_reorderable_items(
68     context: &RewriteContext,
69     list_items: &[ListItem],
70     shape: Shape,
71 ) -> Option<String> {
72     let fmt = ListFormatting {
73         tactic: DefinitiveListTactic::Vertical,
74         separator: "",
75         trailing_separator: SeparatorTactic::Never,
76         separator_place: SeparatorPlace::Back,
77         shape,
78         ends_with_newline: true,
79         preserve_newline: false,
80         config: context.config,
81     };
82
83     write_list(list_items, &fmt)
84 }
85
86 fn rewrite_reorderable_item(
87     context: &RewriteContext,
88     item: &ast::Item,
89     shape: Shape,
90 ) -> Option<String> {
91     let attrs = filter_inline_attrs(&item.attrs, item.span());
92     let attrs_str = attrs.rewrite(context, shape)?;
93
94     let missed_span = if attrs.is_empty() {
95         mk_sp(item.span.lo(), item.span.lo())
96     } else {
97         mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
98     };
99
100     let item_str = match item.node {
101         ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
102         ast::ItemKind::Mod(..) => rewrite_mod(item),
103         _ => return None,
104     };
105
106     combine_strs_with_missing_comments(context, &attrs_str, &item_str, missed_span, shape, false)
107 }
108
109 /// Rewrite a list of items with reordering. Every item in `items` must have
110 /// the same `ast::ItemKind`.
111 fn rewrite_reorderable_items(
112     context: &RewriteContext,
113     reorderable_items: &[&ast::Item],
114     shape: Shape,
115     span: Span,
116 ) -> Option<String> {
117     match reorderable_items[0].node {
118         // FIXME: Remove duplicated code.
119         ast::ItemKind::Use(..) => {
120             let normalized_items: Vec<_> = reorderable_items
121                 .iter()
122                 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
123                 .collect();
124
125             // 4 = "use ", 1 = ";"
126             let nested_shape = shape.offset_left(4)?.sub_width(1)?;
127             let list_items = itemize_list(
128                 context.snippet_provider,
129                 normalized_items.iter(),
130                 "",
131                 ";",
132                 |item| item.span.lo(),
133                 |item| item.span.hi(),
134                 |item| item.rewrite_top_level(context, nested_shape),
135                 span.lo(),
136                 span.hi(),
137                 false,
138             );
139
140             let mut item_pair_vec: Vec<_> = list_items.zip(&normalized_items).collect();
141             item_pair_vec.sort_by(|a, b| a.1.cmp(b.1));
142             let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
143
144             wrap_reorderable_items(context, &item_vec, nested_shape)
145         }
146         _ => {
147             let list_items = itemize_list(
148                 context.snippet_provider,
149                 reorderable_items.iter(),
150                 "",
151                 ";",
152                 |item| item.span().lo(),
153                 |item| item.span().hi(),
154                 |item| rewrite_reorderable_item(context, item, shape),
155                 span.lo(),
156                 span.hi(),
157                 false,
158             );
159
160             let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
161             item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
162             let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
163
164             wrap_reorderable_items(context, &item_vec, shape)
165         }
166     }
167 }
168
169 fn contains_macro_use_attr(item: &ast::Item) -> bool {
170     attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
171 }
172
173 /// A simplified version of `ast::ItemKind`.
174 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
175 enum ReorderableItemKind {
176     ExternCrate,
177     Mod,
178     Use,
179     /// An item that cannot be reordered. Either has an unreorderable item kind
180     /// or an `macro_use` attribute.
181     Other,
182 }
183
184 impl ReorderableItemKind {
185     pub fn from(item: &ast::Item) -> Self {
186         match item.node {
187             _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
188             ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
189             ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
190             ast::ItemKind::Use(..) => ReorderableItemKind::Use,
191             _ => ReorderableItemKind::Other,
192         }
193     }
194
195     pub fn is_same_item_kind(&self, item: &ast::Item) -> bool {
196         ReorderableItemKind::from(item) == *self
197     }
198
199     pub fn is_reorderable(&self, config: &Config) -> bool {
200         match *self {
201             ReorderableItemKind::ExternCrate => config.reorder_extern_crates(),
202             ReorderableItemKind::Mod => config.reorder_modules(),
203             ReorderableItemKind::Use => config.reorder_imports(),
204             ReorderableItemKind::Other => false,
205         }
206     }
207
208     pub fn in_group(&self, config: &Config) -> bool {
209         match *self {
210             ReorderableItemKind::ExternCrate => config.reorder_extern_crates_in_group(),
211             ReorderableItemKind::Mod => config.reorder_modules(),
212             ReorderableItemKind::Use => config.reorder_imports_in_group(),
213             ReorderableItemKind::Other => false,
214         }
215     }
216 }
217
218 impl<'b, 'a: 'b> FmtVisitor<'a> {
219     /// Format items with the same item kind and reorder them. If `in_group` is
220     /// `true`, then the items separated by an empty line will not be reordered
221     /// together.
222     fn walk_reorderable_items(
223         &mut self,
224         items: &[&ast::Item],
225         item_kind: ReorderableItemKind,
226         in_group: bool,
227     ) -> usize {
228         let mut last = self.codemap.lookup_line_range(items[0].span());
229         let item_length = items
230             .iter()
231             .take_while(|ppi| {
232                 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
233                     let current = self.codemap.lookup_line_range(ppi.span());
234                     let in_same_group = current.lo < last.hi + 2;
235                     last = current;
236                     in_same_group
237                 })
238             })
239             .count();
240         let items = &items[..item_length];
241
242         let at_least_one_in_file_lines = items
243             .iter()
244             .any(|item| !out_of_file_lines_range!(self, item.span));
245
246         if at_least_one_in_file_lines && !items.is_empty() {
247             let lo = items.first().unwrap().span().lo();
248             let hi = items.last().unwrap().span().hi();
249             let span = mk_sp(lo, hi);
250             let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
251             self.push_rewrite(span, rw);
252         } else {
253             for item in items {
254                 self.push_rewrite(item.span, None);
255             }
256         }
257
258         item_length
259     }
260
261     /// Visit and format the given items. Items are reordered If they are
262     /// consecutive and reorderable.
263     pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
264         while !items.is_empty() {
265             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
266             // subsequent items that have the same item kind to be reordered within
267             // `walk_reorderable_items`. Otherwise, just format the next item for output.
268             let item_kind = ReorderableItemKind::from(items[0]);
269             if item_kind.is_reorderable(self.config) {
270                 let visited_items_num =
271                     self.walk_reorderable_items(items, item_kind, item_kind.in_group(self.config));
272                 let (_, rest) = items.split_at(visited_items_num);
273                 items = rest;
274             } else {
275                 // Reaching here means items were not reordered. There must be at least
276                 // one item left in `items`, so calling `unwrap()` here is safe.
277                 let (item, rest) = items.split_first().unwrap();
278                 self.visit_item(item);
279                 items = rest;
280             }
281         }
282     }
283 }