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 syntax::{ast, attr, source_map::Span, symbol::sym};
13 use crate::attr::filter_inline_attrs;
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.node, &b.node) {
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.
35 a_name.map_or_else(|| a.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
37 b_name.map_or_else(|| b.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
38 let result = a_orig_name.cmp(&b_orig_name);
39 if result != Ordering::Equal {
43 // `extern crate foo as bar;`
44 // ^^^ Comparing this.
45 match (a_name, b_name) {
46 (Some(..), None) => Ordering::Greater,
47 (None, Some(..)) => Ordering::Less,
48 (None, None) => Ordering::Equal,
49 (Some(..), Some(..)) => a.ident.as_str().cmp(&b.ident.as_str()),
56 fn wrap_reorderable_items(
57 context: &RewriteContext<'_>,
58 list_items: &[ListItem],
61 let fmt = ListFormatting::new(shape, context.config)
63 .align_comments(false);
64 write_list(list_items, &fmt)
67 fn rewrite_reorderable_item(
68 context: &RewriteContext<'_>,
73 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item, shape),
74 ast::ItemKind::Mod(..) => rewrite_mod(context, item, shape),
79 /// Rewrite a list of items with reordering. Every item in `items` must have
80 /// the same `ast::ItemKind`.
81 fn rewrite_reorderable_items(
82 context: &RewriteContext<'_>,
83 reorderable_items: &[&ast::Item],
87 match reorderable_items[0].node {
88 // FIXME: Remove duplicated code.
89 ast::ItemKind::Use(..) => {
90 let mut normalized_items: Vec<_> = reorderable_items
92 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
94 let cloned = normalized_items.clone();
95 // Add comments before merging.
96 let list_items = itemize_list(
97 context.snippet_provider,
101 |item| item.span().lo(),
102 |item| item.span().hi(),
103 |_item| Some("".to_owned()),
108 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
109 item.list_item = Some(list_item.clone());
111 if context.config.merge_imports() {
112 normalized_items = merge_use_trees(normalized_items);
114 normalized_items.sort();
116 // 4 = "use ", 1 = ";"
117 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
118 let item_vec: Vec<_> = normalized_items
120 .map(|use_tree| ListItem {
121 item: use_tree.rewrite_top_level(context, nested_shape),
122 ..use_tree.list_item.unwrap_or_else(ListItem::empty)
126 wrap_reorderable_items(context, &item_vec, nested_shape)
129 let list_items = itemize_list(
130 context.snippet_provider,
131 reorderable_items.iter(),
134 |item| item.span().lo(),
135 |item| item.span().hi(),
136 |item| rewrite_reorderable_item(context, item, shape),
142 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
143 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
144 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
146 wrap_reorderable_items(context, &item_vec, shape)
151 fn contains_macro_use_attr(item: &ast::Item) -> bool {
153 &filter_inline_attrs(&item.attrs, item.span()),
158 /// A simplified version of `ast::ItemKind`.
159 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
160 enum ReorderableItemKind {
164 /// An item that cannot be reordered. Either has an unreorderable item kind
165 /// or an `macro_use` attribute.
169 impl ReorderableItemKind {
170 fn from(item: &ast::Item) -> Self {
172 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
173 ReorderableItemKind::Other
175 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
176 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
177 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
178 _ => ReorderableItemKind::Other,
182 fn is_same_item_kind(self, item: &ast::Item) -> bool {
183 ReorderableItemKind::from(item) == self
186 fn is_reorderable(self, config: &Config) -> bool {
188 ReorderableItemKind::ExternCrate => config.reorder_imports(),
189 ReorderableItemKind::Mod => config.reorder_modules(),
190 ReorderableItemKind::Use => config.reorder_imports(),
191 ReorderableItemKind::Other => false,
195 fn in_group(self) -> bool {
197 ReorderableItemKind::ExternCrate
198 | ReorderableItemKind::Mod
199 | ReorderableItemKind::Use => true,
200 ReorderableItemKind::Other => false,
205 impl<'b, 'a: 'b> FmtVisitor<'a> {
206 /// Format items with the same item kind and reorder them. If `in_group` is
207 /// `true`, then the items separated by an empty line will not be reordered
209 fn walk_reorderable_items(
211 items: &[&ast::Item],
212 item_kind: ReorderableItemKind,
215 let mut last = self.source_map.lookup_line_range(items[0].span());
216 let item_length = items
219 item_kind.is_same_item_kind(&***ppi)
221 let current = self.source_map.lookup_line_range(ppi.span());
222 let in_same_group = current.lo < last.hi + 2;
228 let items = &items[..item_length];
230 let at_least_one_in_file_lines = items
232 .any(|item| !out_of_file_lines_range!(self, item.span));
234 if at_least_one_in_file_lines && !items.is_empty() {
235 let lo = items.first().unwrap().span().lo();
236 let hi = items.last().unwrap().span().hi();
237 let span = mk_sp(lo, hi);
238 let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
239 self.push_rewrite(span, rw);
242 self.push_rewrite(item.span, None);
249 /// Visits and format the given items. Items are reordered If they are
250 /// consecutive and reorderable.
251 pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
252 while !items.is_empty() {
253 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
254 // subsequent items that have the same item kind to be reordered within
255 // `walk_reorderable_items`. Otherwise, just format the next item for output.
256 let item_kind = ReorderableItemKind::from(items[0]);
257 if item_kind.is_reorderable(self.config) {
258 let visited_items_num =
259 self.walk_reorderable_items(items, item_kind, item_kind.in_group());
260 let (_, rest) = items.split_at(visited_items_num);
263 // Reaching here means items were not reordered. There must be at least
264 // one item left in `items`, so calling `unwrap()` here is safe.
265 let (item, rest) = items.split_first().unwrap();
266 self.visit_item(item);