]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/reorder.rs
Auto merge of #106959 - tmiasko:opt-funclets, r=davidtwco
[rust.git] / src / tools / rustfmt / 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 rustc_ast::ast;
12 use rustc_span::{symbol::sym, Span};
13
14 use crate::config::{Config, GroupImportsTactic};
15 use crate::imports::{normalize_use_trees_with_granularity, UseSegmentKind, UseTree};
16 use crate::items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
17 use crate::lists::{itemize_list, write_list, ListFormatting, ListItem};
18 use crate::rewrite::RewriteContext;
19 use crate::shape::Shape;
20 use crate::source_map::LineRangeUtils;
21 use crate::spanned::Spanned;
22 use crate::utils::{contains_skip, mk_sp};
23 use crate::visitor::FmtVisitor;
24
25 /// Choose the ordering between the given two items.
26 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
27     match (&a.kind, &b.kind) {
28         (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
29             a.ident.as_str().cmp(b.ident.as_str())
30         }
31         (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
32             // `extern crate foo as bar;`
33             //               ^^^ Comparing this.
34             let a_orig_name = a_name.unwrap_or(a.ident.name);
35             let b_orig_name = b_name.unwrap_or(b.ident.name);
36             let result = a_orig_name.as_str().cmp(b_orig_name.as_str());
37             if result != Ordering::Equal {
38                 return result;
39             }
40
41             // `extern crate foo as bar;`
42             //                      ^^^ Comparing this.
43             match (a_name, b_name) {
44                 (Some(..), None) => Ordering::Greater,
45                 (None, Some(..)) => Ordering::Less,
46                 (None, None) => Ordering::Equal,
47                 (Some(..), Some(..)) => a.ident.as_str().cmp(b.ident.as_str()),
48             }
49         }
50         _ => unreachable!(),
51     }
52 }
53
54 fn wrap_reorderable_items(
55     context: &RewriteContext<'_>,
56     list_items: &[ListItem],
57     shape: Shape,
58 ) -> Option<String> {
59     let fmt = ListFormatting::new(shape, context.config)
60         .separator("")
61         .align_comments(false);
62     write_list(list_items, &fmt)
63 }
64
65 fn rewrite_reorderable_item(
66     context: &RewriteContext<'_>,
67     item: &ast::Item,
68     shape: Shape,
69 ) -> Option<String> {
70     match item.kind {
71         ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item, shape),
72         ast::ItemKind::Mod(..) => rewrite_mod(context, item, shape),
73         _ => None,
74     }
75 }
76
77 /// Rewrite a list of items with reordering and/or regrouping. Every item
78 /// in `items` must have the same `ast::ItemKind`. Whether reordering, regrouping,
79 /// or both are done is determined from the `context`.
80 fn rewrite_reorderable_or_regroupable_items(
81     context: &RewriteContext<'_>,
82     reorderable_items: &[&ast::Item],
83     shape: Shape,
84     span: Span,
85 ) -> Option<String> {
86     match reorderable_items[0].kind {
87         // FIXME: Remove duplicated code.
88         ast::ItemKind::Use(..) => {
89             let mut normalized_items: Vec<_> = reorderable_items
90                 .iter()
91                 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
92                 .collect();
93             let cloned = normalized_items.clone();
94             // Add comments before merging.
95             let list_items = itemize_list(
96                 context.snippet_provider,
97                 cloned.iter(),
98                 "",
99                 ";",
100                 |item| item.span().lo(),
101                 |item| item.span().hi(),
102                 |_item| Some("".to_owned()),
103                 span.lo(),
104                 span.hi(),
105                 false,
106             );
107             for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
108                 item.list_item = Some(list_item.clone());
109             }
110             normalized_items = normalize_use_trees_with_granularity(
111                 normalized_items,
112                 context.config.imports_granularity(),
113             );
114
115             let mut regrouped_items = match context.config.group_imports() {
116                 GroupImportsTactic::Preserve | GroupImportsTactic::One => {
117                     vec![normalized_items]
118                 }
119                 GroupImportsTactic::StdExternalCrate => group_imports(normalized_items),
120             };
121
122             if context.config.reorder_imports() {
123                 regrouped_items.iter_mut().for_each(|items| items.sort())
124             }
125
126             // 4 = "use ", 1 = ";"
127             let nested_shape = shape.offset_left(4)?.sub_width(1)?;
128             let item_vec: Vec<_> = regrouped_items
129                 .into_iter()
130                 .filter(|use_group| !use_group.is_empty())
131                 .map(|use_group| {
132                     let item_vec: Vec<_> = use_group
133                         .into_iter()
134                         .map(|use_tree| ListItem {
135                             item: use_tree.rewrite_top_level(context, nested_shape),
136                             ..use_tree.list_item.unwrap_or_else(ListItem::empty)
137                         })
138                         .collect();
139                     wrap_reorderable_items(context, &item_vec, nested_shape)
140                 })
141                 .collect::<Option<Vec<_>>>()?;
142
143             let join_string = format!("\n\n{}", shape.indent.to_string(context.config));
144             Some(item_vec.join(&join_string))
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     crate::attr::contains_name(&item.attrs, sym::macro_use)
171 }
172
173 /// Divides imports into three groups, corresponding to standard, external
174 /// and local imports. Sorts each subgroup.
175 fn group_imports(uts: Vec<UseTree>) -> Vec<Vec<UseTree>> {
176     let mut std_imports = Vec::new();
177     let mut external_imports = Vec::new();
178     let mut local_imports = Vec::new();
179
180     for ut in uts.into_iter() {
181         if ut.path.is_empty() {
182             external_imports.push(ut);
183             continue;
184         }
185         match &ut.path[0].kind {
186             UseSegmentKind::Ident(id, _) => match id.as_ref() {
187                 "std" | "alloc" | "core" => std_imports.push(ut),
188                 _ => external_imports.push(ut),
189             },
190             UseSegmentKind::Slf(_) | UseSegmentKind::Super(_) | UseSegmentKind::Crate(_) => {
191                 local_imports.push(ut)
192             }
193             // These are probably illegal here
194             UseSegmentKind::Glob | UseSegmentKind::List(_) => external_imports.push(ut),
195         }
196     }
197
198     vec![std_imports, external_imports, local_imports]
199 }
200
201 /// A simplified version of `ast::ItemKind`.
202 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
203 enum ReorderableItemKind {
204     ExternCrate,
205     Mod,
206     Use,
207     /// An item that cannot be reordered. Either has an unreorderable item kind
208     /// or an `macro_use` attribute.
209     Other,
210 }
211
212 impl ReorderableItemKind {
213     fn from(item: &ast::Item) -> Self {
214         match item.kind {
215             _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
216                 ReorderableItemKind::Other
217             }
218             ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
219             ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
220             ast::ItemKind::Use(..) => ReorderableItemKind::Use,
221             _ => ReorderableItemKind::Other,
222         }
223     }
224
225     fn is_same_item_kind(self, item: &ast::Item) -> bool {
226         ReorderableItemKind::from(item) == self
227     }
228
229     fn is_reorderable(self, config: &Config) -> bool {
230         match self {
231             ReorderableItemKind::ExternCrate => config.reorder_imports(),
232             ReorderableItemKind::Mod => config.reorder_modules(),
233             ReorderableItemKind::Use => config.reorder_imports(),
234             ReorderableItemKind::Other => false,
235         }
236     }
237
238     fn is_regroupable(self, config: &Config) -> bool {
239         match self {
240             ReorderableItemKind::ExternCrate
241             | ReorderableItemKind::Mod
242             | ReorderableItemKind::Other => false,
243             ReorderableItemKind::Use => config.group_imports() != GroupImportsTactic::Preserve,
244         }
245     }
246
247     fn in_group(self, config: &Config) -> bool {
248         match self {
249             ReorderableItemKind::ExternCrate | ReorderableItemKind::Mod => true,
250             ReorderableItemKind::Use => config.group_imports() == GroupImportsTactic::Preserve,
251             ReorderableItemKind::Other => false,
252         }
253     }
254 }
255
256 impl<'b, 'a: 'b> FmtVisitor<'a> {
257     /// Format items with the same item kind and reorder them, regroup them, or
258     /// both. If `in_group` is `true`, then the items separated by an empty line
259     /// will not be reordered together.
260     fn walk_reorderable_or_regroupable_items(
261         &mut self,
262         items: &[&ast::Item],
263         item_kind: ReorderableItemKind,
264         in_group: bool,
265     ) -> usize {
266         let mut last = self.parse_sess.lookup_line_range(items[0].span());
267         let item_length = items
268             .iter()
269             .take_while(|ppi| {
270                 item_kind.is_same_item_kind(&***ppi)
271                     && (!in_group || {
272                         let current = self.parse_sess.lookup_line_range(ppi.span());
273                         let in_same_group = current.lo < last.hi + 2;
274                         last = current;
275                         in_same_group
276                     })
277             })
278             .count();
279         let items = &items[..item_length];
280
281         let at_least_one_in_file_lines = items
282             .iter()
283             .any(|item| !out_of_file_lines_range!(self, item.span));
284
285         if at_least_one_in_file_lines && !items.is_empty() {
286             let lo = items.first().unwrap().span().lo();
287             let hi = items.last().unwrap().span().hi();
288             let span = mk_sp(lo, hi);
289             let rw = rewrite_reorderable_or_regroupable_items(
290                 &self.get_context(),
291                 items,
292                 self.shape(),
293                 span,
294             );
295             self.push_rewrite(span, rw);
296         } else {
297             for item in items {
298                 self.push_rewrite(item.span, None);
299             }
300         }
301
302         item_length
303     }
304
305     /// Visits and format the given items. Items are reordered If they are
306     /// consecutive and reorderable.
307     pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
308         while !items.is_empty() {
309             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
310             // subsequent items that have the same item kind to be reordered within
311             // `walk_reorderable_items`. Otherwise, just format the next item for output.
312             let item_kind = ReorderableItemKind::from(items[0]);
313             if item_kind.is_reorderable(self.config) || item_kind.is_regroupable(self.config) {
314                 let visited_items_num = self.walk_reorderable_or_regroupable_items(
315                     items,
316                     item_kind,
317                     item_kind.in_group(self.config),
318                 );
319                 let (_, rest) = items.split_at(visited_items_num);
320                 items = rest;
321             } else {
322                 // Reaching here means items were not reordered. There must be at least
323                 // one item left in `items`, so calling `unwrap()` here is safe.
324                 let (item, rest) = items.split_first().unwrap();
325                 self.visit_item(item);
326                 items = rest;
327             }
328         }
329     }
330 }