]> git.lizzy.rs Git - rust.git/blob - src/reorder.rs
Merge pull request #2499 from davidalber/add-rust-code-of-conduct
[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 constatns comes before methods).
16
17 // TODO(#2455): Reorder trait items.
18
19 use config::{Config, lists::*};
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::{path_to_imported_ident, rewrite_import};
26 use items::{rewrite_extern_crate, rewrite_mod};
27 use lists::{itemize_list, write_list, ListFormatting};
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::Ordering;
35
36 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
37     a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
38 }
39
40 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
41     for segment in a.segments.iter().zip(b.segments.iter()) {
42         let ord = compare_path_segments(segment.0, segment.1);
43         if ord != Ordering::Equal {
44             return ord;
45         }
46     }
47     a.segments.len().cmp(&b.segments.len())
48 }
49
50 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
51     use ast::UseTreeKind::*;
52
53     // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
54     // fully added
55     if !nested {
56         let paths_cmp = compare_paths(&a.prefix, &b.prefix);
57         if paths_cmp != Ordering::Equal {
58             return paths_cmp;
59         }
60     }
61
62     match (&a.kind, &b.kind) {
63         (&Simple(ident_a), &Simple(ident_b)) => {
64             let name_a = &*path_to_imported_ident(&a.prefix).name.as_str();
65             let name_b = &*path_to_imported_ident(&b.prefix).name.as_str();
66             let name_ordering = if name_a == "self" {
67                 if name_b == "self" {
68                     Ordering::Equal
69                 } else {
70                     Ordering::Less
71                 }
72             } else if name_b == "self" {
73                 Ordering::Greater
74             } else {
75                 name_a.cmp(name_b)
76             };
77             if name_ordering == Ordering::Equal {
78                 if ident_a.name.as_str() != name_a {
79                     if ident_b.name.as_str() != name_b {
80                         ident_a.name.as_str().cmp(&ident_b.name.as_str())
81                     } else {
82                         Ordering::Greater
83                     }
84                 } else {
85                     Ordering::Less
86                 }
87             } else {
88                 name_ordering
89             }
90         }
91         (&Glob, &Glob) => Ordering::Equal,
92         (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
93         (&Nested(ref a_items), &Nested(ref b_items)) => {
94             let mut a = a_items
95                 .iter()
96                 .map(|&(ref tree, _)| tree.clone())
97                 .collect::<Vec<_>>();
98             let mut b = b_items
99                 .iter()
100                 .map(|&(ref tree, _)| tree.clone())
101                 .collect::<Vec<_>>();
102             a.sort_by(|a, b| compare_use_trees(a, b, true));
103             b.sort_by(|a, b| compare_use_trees(a, b, true));
104             for comparison_pair in a.iter().zip(b.iter()) {
105                 let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
106                 if ord != Ordering::Equal {
107                     return ord;
108                 }
109             }
110             a.len().cmp(&b.len())
111         }
112         (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
113     }
114 }
115
116 /// Choose the ordering between the given two items.
117 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
118     match (&a.node, &b.node) {
119         (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
120             a.ident.name.as_str().cmp(&b.ident.name.as_str())
121         }
122         (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
123             compare_use_trees(a_tree, b_tree, false)
124         }
125         (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
126             // `extern crate foo as bar;`
127             //               ^^^ Comparing this.
128             let a_orig_name =
129                 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
130             let b_orig_name =
131                 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
132             let result = a_orig_name.cmp(&b_orig_name);
133             if result != Ordering::Equal {
134                 return result;
135             }
136
137             // `extern crate foo as bar;`
138             //                      ^^^ Comparing this.
139             match (a_name, b_name) {
140                 (Some(..), None) => Ordering::Greater,
141                 (None, Some(..)) => Ordering::Less,
142                 (None, None) => Ordering::Equal,
143                 (Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
144             }
145         }
146         _ => unreachable!(),
147     }
148 }
149
150 /// Rewrite a list of items with reordering. Every item in `items` must have
151 /// the same `ast::ItemKind`.
152 // TODO (some day) remove unused imports, expand globs, compress many single
153 // imports into a list import.
154 fn rewrite_reorderable_items(
155     context: &RewriteContext,
156     reorderable_items: &[&ast::Item],
157     shape: Shape,
158     span: Span,
159 ) -> Option<String> {
160     let 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| {
168             let attrs = filter_inline_attrs(&item.attrs, item.span());
169             let attrs_str = attrs.rewrite(context, shape)?;
170
171             let missed_span = if attrs.is_empty() {
172                 mk_sp(item.span.lo(), item.span.lo())
173             } else {
174                 mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
175             };
176
177             let item_str = match item.node {
178                 ast::ItemKind::Use(ref tree) => {
179                     rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
180                 }
181                 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
182                 ast::ItemKind::Mod(..) => rewrite_mod(item),
183                 _ => return None,
184             };
185
186             combine_strs_with_missing_comments(
187                 context,
188                 &attrs_str,
189                 &item_str,
190                 missed_span,
191                 shape,
192                 false,
193             )
194         },
195         span.lo(),
196         span.hi(),
197         false,
198     );
199     let mut item_pair_vec: Vec<_> = items.zip(reorderable_items.iter()).collect();
200     item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
201     let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
202
203     let fmt = ListFormatting {
204         tactic: DefinitiveListTactic::Vertical,
205         separator: "",
206         trailing_separator: SeparatorTactic::Never,
207         separator_place: SeparatorPlace::Back,
208         shape,
209         ends_with_newline: true,
210         preserve_newline: false,
211         config: context.config,
212     };
213
214     write_list(&item_vec, &fmt)
215 }
216
217 fn contains_macro_use_attr(item: &ast::Item) -> bool {
218     attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
219 }
220
221 /// A simplified version of `ast::ItemKind`.
222 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
223 enum ReorderableItemKind {
224     ExternCrate,
225     Mod,
226     Use,
227     /// An item that cannot be reordered. Either has an unreorderable item kind
228     /// or an `macro_use` attribute.
229     Other,
230 }
231
232 impl ReorderableItemKind {
233     pub fn from(item: &ast::Item) -> Self {
234         match item.node {
235             _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
236             ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
237             ast::ItemKind::Mod(..) => ReorderableItemKind::Mod,
238             ast::ItemKind::Use(..) => ReorderableItemKind::Use,
239             _ => ReorderableItemKind::Other,
240         }
241     }
242
243     pub fn is_same_item_kind(&self, item: &ast::Item) -> bool {
244         ReorderableItemKind::from(item) == *self
245     }
246
247     pub fn is_reorderable(&self, config: &Config) -> bool {
248         match *self {
249             ReorderableItemKind::ExternCrate => config.reorder_extern_crates(),
250             ReorderableItemKind::Mod => config.reorder_modules(),
251             ReorderableItemKind::Use => config.reorder_imports(),
252             ReorderableItemKind::Other => false,
253         }
254     }
255
256     pub fn in_group(&self, config: &Config) -> bool {
257         match *self {
258             ReorderableItemKind::ExternCrate => config.reorder_extern_crates_in_group(),
259             ReorderableItemKind::Mod => config.reorder_modules(),
260             ReorderableItemKind::Use => config.reorder_imports_in_group(),
261             ReorderableItemKind::Other => false,
262         }
263     }
264 }
265
266 impl<'b, 'a: 'b> FmtVisitor<'a> {
267     /// Format items with the same item kind and reorder them. If `in_group` is
268     /// `true`, then the items separated by an empty line will not be reordered
269     /// together.
270     fn walk_reorderable_items(
271         &mut self,
272         items: &[&ast::Item],
273         item_kind: ReorderableItemKind,
274         in_group: bool,
275     ) -> usize {
276         let mut last = self.codemap.lookup_line_range(items[0].span());
277         let item_length = items
278             .iter()
279             .take_while(|ppi| {
280                 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
281                     let current = self.codemap.lookup_line_range(ppi.span());
282                     let in_same_group = current.lo < last.hi + 2;
283                     last = current;
284                     in_same_group
285                 })
286             })
287             .count();
288         let items = &items[..item_length];
289
290         let at_least_one_in_file_lines = items
291             .iter()
292             .any(|item| !out_of_file_lines_range!(self, item.span));
293
294         if at_least_one_in_file_lines && !items.is_empty() {
295             let lo = items.first().unwrap().span().lo();
296             let hi = items.last().unwrap().span().hi();
297             let span = mk_sp(lo, hi);
298             let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
299             self.push_rewrite(span, rw);
300         } else {
301             for item in items {
302                 self.push_rewrite(item.span, None);
303             }
304         }
305
306         item_length
307     }
308
309     /// Visit and format the given items. Items are reordered If they are
310     /// consecutive and reorderable.
311     pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
312         while !items.is_empty() {
313             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
314             // subsequent items that have the same item kind to be reordered within
315             // `walk_reorderable_items`. Otherwise, just format the next item for output.
316             let item_kind = ReorderableItemKind::from(items[0]);
317             if item_kind.is_reorderable(self.config) {
318                 let visited_items_num =
319                     self.walk_reorderable_items(items, item_kind, item_kind.in_group(self.config));
320                 let (_, rest) = items.split_at(visited_items_num);
321                 items = rest;
322             } else {
323                 // Reaching here means items were not reordered. There must be at least
324                 // one item left in `items`, so calling `unwrap()` here is safe.
325                 let (item, rest) = items.split_first().unwrap();
326                 self.visit_item(item);
327                 items = rest;
328             }
329         }
330     }
331 }