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).
7 // FIXME(#2455): Reorder trait items.
9 use std::cmp::{Ord, Ordering};
11 use rustc_span::{symbol::sym, Span};
12 use syntax::{ast, attr};
14 use crate::config::Config;
15 use crate::imports::{merge_use_trees, 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;
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())
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.map_or_else(|| a.ident.as_str(), rustc_span::Symbol::as_str);
35 let b_orig_name = b_name.map_or_else(|| b.ident.as_str(), rustc_span::Symbol::as_str);
36 let result = a_orig_name.cmp(&b_orig_name);
37 if result != Ordering::Equal {
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()),
54 fn wrap_reorderable_items(
55 context: &RewriteContext<'_>,
56 list_items: &[ListItem],
59 let fmt = ListFormatting::new(shape, context.config)
61 .align_comments(false);
62 write_list(list_items, &fmt)
65 fn rewrite_reorderable_item(
66 context: &RewriteContext<'_>,
71 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item, shape),
72 ast::ItemKind::Mod(..) => rewrite_mod(context, item, shape),
77 /// Rewrite a list of items with reordering. Every item in `items` must have
78 /// the same `ast::ItemKind`.
79 fn rewrite_reorderable_items(
80 context: &RewriteContext<'_>,
81 reorderable_items: &[&ast::Item],
85 match reorderable_items[0].kind {
86 // FIXME: Remove duplicated code.
87 ast::ItemKind::Use(..) => {
88 let mut normalized_items: Vec<_> = reorderable_items
90 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
92 let cloned = normalized_items.clone();
93 // Add comments before merging.
94 let list_items = itemize_list(
95 context.snippet_provider,
99 |item| item.span().lo(),
100 |item| item.span().hi(),
101 |_item| Some("".to_owned()),
106 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
107 item.list_item = Some(list_item.clone());
109 if context.config.merge_imports() {
110 normalized_items = merge_use_trees(normalized_items);
112 normalized_items.sort();
114 // 4 = "use ", 1 = ";"
115 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
116 let item_vec: Vec<_> = normalized_items
118 .map(|use_tree| ListItem {
119 item: use_tree.rewrite_top_level(context, nested_shape),
120 ..use_tree.list_item.unwrap_or_else(ListItem::empty)
124 wrap_reorderable_items(context, &item_vec, nested_shape)
127 let list_items = itemize_list(
128 context.snippet_provider,
129 reorderable_items.iter(),
132 |item| item.span().lo(),
133 |item| item.span().hi(),
134 |item| rewrite_reorderable_item(context, item, shape),
140 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
141 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
142 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
144 wrap_reorderable_items(context, &item_vec, shape)
149 fn contains_macro_use_attr(item: &ast::Item) -> bool {
150 attr::contains_name(&item.attrs, sym::macro_use)
153 /// A simplified version of `ast::ItemKind`.
154 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
155 enum ReorderableItemKind {
159 /// An item that cannot be reordered. Either has an unreorderable item kind
160 /// or an `macro_use` attribute.
164 impl ReorderableItemKind {
165 fn from(item: &ast::Item) -> Self {
167 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
168 ReorderableItemKind::Other
170 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
171 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
172 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
173 _ => ReorderableItemKind::Other,
177 fn is_same_item_kind(self, item: &ast::Item) -> bool {
178 ReorderableItemKind::from(item) == self
181 fn is_reorderable(self, config: &Config) -> bool {
183 ReorderableItemKind::ExternCrate => config.reorder_imports(),
184 ReorderableItemKind::Mod => config.reorder_modules(),
185 ReorderableItemKind::Use => config.reorder_imports(),
186 ReorderableItemKind::Other => false,
190 fn in_group(self) -> bool {
192 ReorderableItemKind::ExternCrate
193 | ReorderableItemKind::Mod
194 | ReorderableItemKind::Use => true,
195 ReorderableItemKind::Other => false,
200 impl<'b, 'a: 'b> FmtVisitor<'a> {
201 /// Format items with the same item kind and reorder them. If `in_group` is
202 /// `true`, then the items separated by an empty line will not be reordered
204 fn walk_reorderable_items(
206 items: &[&ast::Item],
207 item_kind: ReorderableItemKind,
210 let mut last = self.source_map.lookup_line_range(items[0].span());
211 let item_length = items
214 item_kind.is_same_item_kind(&***ppi)
216 let current = self.source_map.lookup_line_range(ppi.span());
217 let in_same_group = current.lo < last.hi + 2;
223 let items = &items[..item_length];
225 let at_least_one_in_file_lines = items
227 .any(|item| !out_of_file_lines_range!(self, item.span));
229 if at_least_one_in_file_lines && !items.is_empty() {
230 let lo = items.first().unwrap().span().lo();
231 let hi = items.last().unwrap().span().hi();
232 let span = mk_sp(lo, hi);
233 let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
234 self.push_rewrite(span, rw);
237 self.push_rewrite(item.span, None);
244 /// Visits and format the given items. Items are reordered If they are
245 /// consecutive and reorderable.
246 pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
247 while !items.is_empty() {
248 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
249 // subsequent items that have the same item kind to be reordered within
250 // `walk_reorderable_items`. Otherwise, just format the next item for output.
251 let item_kind = ReorderableItemKind::from(items[0]);
252 if item_kind.is_reorderable(self.config) {
253 let visited_items_num =
254 self.walk_reorderable_items(items, item_kind, item_kind.in_group());
255 let (_, rest) = items.split_at(visited_items_num);
258 // Reaching here means items were not reordered. There must be at least
259 // one item left in `items`, so calling `unwrap()` here is safe.
260 let (item, rest) = items.split_first().unwrap();
261 self.visit_item(item);