]> git.lizzy.rs Git - rust.git/blob - src/reorder.rs
9908c402a43ca675ec6a623c3df817917d0e6ad7
[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 // FIXME(#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::{merge_use_trees, 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         nested: false,
81         config: context.config,
82     };
83
84     write_list(list_items, &fmt)
85 }
86
87 fn rewrite_reorderable_item(
88     context: &RewriteContext,
89     item: &ast::Item,
90     shape: Shape,
91 ) -> Option<String> {
92     let attrs = filter_inline_attrs(&item.attrs, item.span());
93     let attrs_str = attrs.rewrite(context, shape)?;
94
95     let missed_span = if attrs.is_empty() {
96         mk_sp(item.span.lo(), item.span.lo())
97     } else {
98         mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
99     };
100
101     let item_str = match item.node {
102         ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
103         ast::ItemKind::Mod(..) => rewrite_mod(context, item),
104         _ => return None,
105     };
106
107     combine_strs_with_missing_comments(context, &attrs_str, &item_str, missed_span, shape, false)
108 }
109
110 /// Rewrite a list of items with reordering. Every item in `items` must have
111 /// the same `ast::ItemKind`.
112 fn rewrite_reorderable_items(
113     context: &RewriteContext,
114     reorderable_items: &[&ast::Item],
115     shape: Shape,
116     span: Span,
117 ) -> Option<String> {
118     match reorderable_items[0].node {
119         // FIXME: Remove duplicated code.
120         ast::ItemKind::Use(..) => {
121             let mut normalized_items: Vec<_> = reorderable_items
122                 .iter()
123                 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
124                 .collect();
125             let cloned = normalized_items.clone();
126             // Add comments before merging.
127             let list_items = itemize_list(
128                 context.snippet_provider,
129                 cloned.iter(),
130                 "",
131                 ";",
132                 |item| item.span().lo(),
133                 |item| item.span().hi(),
134                 |_item| Some("".to_owned()),
135                 span.lo(),
136                 span.hi(),
137                 false,
138             );
139             for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
140                 item.list_item = Some(list_item.clone());
141             }
142             if context.config.merge_imports() {
143                 normalized_items = merge_use_trees(normalized_items);
144             }
145             normalized_items.sort();
146
147             // 4 = "use ", 1 = ";"
148             let nested_shape = shape.offset_left(4)?.sub_width(1)?;
149             let item_vec: Vec<_> = normalized_items
150                 .into_iter()
151                 .map(|use_tree| ListItem {
152                     item: use_tree.rewrite_top_level(context, nested_shape),
153                     ..use_tree.list_item.unwrap_or_else(ListItem::empty)
154                 })
155                 .collect();
156
157             wrap_reorderable_items(context, &item_vec, nested_shape)
158         }
159         _ => {
160             let list_items = itemize_list(
161                 context.snippet_provider,
162                 reorderable_items.iter(),
163                 "",
164                 ";",
165                 |item| item.span().lo(),
166                 |item| item.span().hi(),
167                 |item| rewrite_reorderable_item(context, item, shape),
168                 span.lo(),
169                 span.hi(),
170                 false,
171             );
172
173             let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
174             item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
175             let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
176
177             wrap_reorderable_items(context, &item_vec, shape)
178         }
179     }
180 }
181
182 fn contains_macro_use_attr(item: &ast::Item) -> bool {
183     attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
184 }
185
186 /// A simplified version of `ast::ItemKind`.
187 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
188 enum ReorderableItemKind {
189     ExternCrate,
190     Mod,
191     Use,
192     /// An item that cannot be reordered. Either has an unreorderable item kind
193     /// or an `macro_use` attribute.
194     Other,
195 }
196
197 impl ReorderableItemKind {
198     fn from(item: &ast::Item) -> Self {
199         match item.node {
200             _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
201             ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
202             ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
203             ast::ItemKind::Use(..) => ReorderableItemKind::Use,
204             _ => ReorderableItemKind::Other,
205         }
206     }
207
208     fn is_same_item_kind(&self, item: &ast::Item) -> bool {
209         ReorderableItemKind::from(item) == *self
210     }
211
212     fn is_reorderable(&self, config: &Config) -> bool {
213         match *self {
214             ReorderableItemKind::ExternCrate => config.reorder_imports(),
215             ReorderableItemKind::Mod => config.reorder_modules(),
216             ReorderableItemKind::Use => config.reorder_imports(),
217             ReorderableItemKind::Other => false,
218         }
219     }
220
221     fn in_group(&self) -> bool {
222         match *self {
223             ReorderableItemKind::ExternCrate
224             | ReorderableItemKind::Mod
225             | ReorderableItemKind::Use => true,
226             ReorderableItemKind::Other => false,
227         }
228     }
229 }
230
231 impl<'b, 'a: 'b> FmtVisitor<'a> {
232     /// Format items with the same item kind and reorder them. If `in_group` is
233     /// `true`, then the items separated by an empty line will not be reordered
234     /// together.
235     fn walk_reorderable_items(
236         &mut self,
237         items: &[&ast::Item],
238         item_kind: ReorderableItemKind,
239         in_group: bool,
240     ) -> usize {
241         let mut last = self.codemap.lookup_line_range(items[0].span());
242         let item_length = items
243             .iter()
244             .take_while(|ppi| {
245                 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
246                     let current = self.codemap.lookup_line_range(ppi.span());
247                     let in_same_group = current.lo < last.hi + 2;
248                     last = current;
249                     in_same_group
250                 })
251             })
252             .count();
253         let items = &items[..item_length];
254
255         let at_least_one_in_file_lines = items
256             .iter()
257             .any(|item| !out_of_file_lines_range!(self, item.span));
258
259         if at_least_one_in_file_lines && !items.is_empty() {
260             let lo = items.first().unwrap().span().lo();
261             let hi = items.last().unwrap().span().hi();
262             let span = mk_sp(lo, hi);
263             let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
264             self.push_rewrite(span, rw);
265         } else {
266             for item in items {
267                 self.push_rewrite(item.span, None);
268             }
269         }
270
271         item_length
272     }
273
274     /// Visit and format the given items. Items are reordered If they are
275     /// consecutive and reorderable.
276     pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
277         while !items.is_empty() {
278             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
279             // subsequent items that have the same item kind to be reordered within
280             // `walk_reorderable_items`. Otherwise, just format the next item for output.
281             let item_kind = ReorderableItemKind::from(items[0]);
282             if item_kind.is_reorderable(self.config) {
283                 let visited_items_num =
284                     self.walk_reorderable_items(items, item_kind, item_kind.in_group());
285                 let (_, rest) = items.split_at(visited_items_num);
286                 items = rest;
287             } else {
288                 // Reaching here means items were not reordered. There must be at least
289                 // one item left in `items`, so calling `unwrap()` here is safe.
290                 let (item, rest) = items.split_first().unwrap();
291                 self.visit_item(item);
292                 items = rest;
293             }
294         }
295     }
296 }