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