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