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};
12 use rustc_span::{symbol::sym, Span};
14 use crate::config::{Config, GroupImportsTactic, ImportGranularity};
15 use crate::imports::{flatten_use_trees, merge_use_trees, SharedPrefix, UseSegment, 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.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 {
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 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],
86 match reorderable_items[0].kind {
87 // FIXME: Remove duplicated code.
88 ast::ItemKind::Use(..) => {
89 let mut normalized_items: Vec<_> = reorderable_items
91 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
93 let cloned = normalized_items.clone();
94 // Add comments before merging.
95 let list_items = itemize_list(
96 context.snippet_provider,
100 |item| item.span().lo(),
101 |item| item.span().hi(),
102 |_item| Some("".to_owned()),
107 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
108 item.list_item = Some(list_item.clone());
110 normalized_items = match context.config.imports_granularity() {
111 ImportGranularity::Crate => merge_use_trees(normalized_items, SharedPrefix::Crate),
112 ImportGranularity::Module => {
113 merge_use_trees(normalized_items, SharedPrefix::Module)
115 ImportGranularity::Item => flatten_use_trees(normalized_items),
116 ImportGranularity::One => merge_use_trees(normalized_items, SharedPrefix::One),
117 ImportGranularity::Preserve => normalized_items,
120 let mut regrouped_items = match context.config.group_imports() {
121 GroupImportsTactic::Preserve | GroupImportsTactic::One => {
122 vec![normalized_items]
124 GroupImportsTactic::StdExternalCrate => group_imports(normalized_items),
127 if context.config.reorder_imports() {
128 regrouped_items.iter_mut().for_each(|items| items.sort())
131 // 4 = "use ", 1 = ";"
132 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
133 let item_vec: Vec<_> = regrouped_items
135 .filter(|use_group| !use_group.is_empty())
137 let item_vec: Vec<_> = use_group
139 .map(|use_tree| ListItem {
140 item: use_tree.rewrite_top_level(context, nested_shape),
141 ..use_tree.list_item.unwrap_or_else(ListItem::empty)
144 wrap_reorderable_items(context, &item_vec, nested_shape)
146 .collect::<Option<Vec<_>>>()?;
148 let join_string = format!("\n\n{}", shape.indent.to_string(context.config));
149 Some(item_vec.join(&join_string))
152 let list_items = itemize_list(
153 context.snippet_provider,
154 reorderable_items.iter(),
157 |item| item.span().lo(),
158 |item| item.span().hi(),
159 |item| rewrite_reorderable_item(context, item, shape),
165 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
166 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
167 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
169 wrap_reorderable_items(context, &item_vec, shape)
174 fn contains_macro_use_attr(item: &ast::Item) -> bool {
175 crate::attr::contains_name(&item.attrs, sym::macro_use)
178 /// Divides imports into three groups, corresponding to standard, external
179 /// and local imports. Sorts each subgroup.
180 fn group_imports(uts: Vec<UseTree>) -> Vec<Vec<UseTree>> {
181 let mut std_imports = Vec::new();
182 let mut external_imports = Vec::new();
183 let mut local_imports = Vec::new();
185 for ut in uts.into_iter() {
186 if ut.path.is_empty() {
187 external_imports.push(ut);
191 UseSegment::Ident(id, _) => match id.as_ref() {
192 "std" | "alloc" | "core" => std_imports.push(ut),
193 _ => external_imports.push(ut),
195 UseSegment::Slf(_) | UseSegment::Super(_) | UseSegment::Crate(_) => {
196 local_imports.push(ut)
198 // These are probably illegal here
199 UseSegment::Glob | UseSegment::List(_) => external_imports.push(ut),
203 vec![std_imports, external_imports, local_imports]
206 /// A simplified version of `ast::ItemKind`.
207 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
208 enum ReorderableItemKind {
212 /// An item that cannot be reordered. Either has an unreorderable item kind
213 /// or an `macro_use` attribute.
217 impl ReorderableItemKind {
218 fn from(item: &ast::Item) -> Self {
220 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
221 ReorderableItemKind::Other
223 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
224 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
225 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
226 _ => ReorderableItemKind::Other,
230 fn is_same_item_kind(self, item: &ast::Item) -> bool {
231 ReorderableItemKind::from(item) == self
234 fn is_reorderable(self, config: &Config) -> bool {
236 ReorderableItemKind::ExternCrate => config.reorder_imports(),
237 ReorderableItemKind::Mod => config.reorder_modules(),
238 ReorderableItemKind::Use => config.reorder_imports(),
239 ReorderableItemKind::Other => false,
243 fn is_regroupable(self, config: &Config) -> bool {
245 ReorderableItemKind::ExternCrate
246 | ReorderableItemKind::Mod
247 | ReorderableItemKind::Other => false,
248 ReorderableItemKind::Use => config.group_imports() != GroupImportsTactic::Preserve,
252 fn in_group(self, config: &Config) -> bool {
254 ReorderableItemKind::ExternCrate | ReorderableItemKind::Mod => true,
255 ReorderableItemKind::Use => config.group_imports() == GroupImportsTactic::Preserve,
256 ReorderableItemKind::Other => false,
261 impl<'b, 'a: 'b> FmtVisitor<'a> {
262 /// Format items with the same item kind and reorder them, regroup them, or
263 /// both. If `in_group` is `true`, then the items separated by an empty line
264 /// will not be reordered together.
265 fn walk_reorderable_or_regroupable_items(
267 items: &[&ast::Item],
268 item_kind: ReorderableItemKind,
271 let mut last = self.parse_sess.lookup_line_range(items[0].span());
272 let item_length = items
275 item_kind.is_same_item_kind(&***ppi)
277 let current = self.parse_sess.lookup_line_range(ppi.span());
278 let in_same_group = current.lo < last.hi + 2;
284 let items = &items[..item_length];
286 let at_least_one_in_file_lines = items
288 .any(|item| !out_of_file_lines_range!(self, item.span));
290 if at_least_one_in_file_lines && !items.is_empty() {
291 let lo = items.first().unwrap().span().lo();
292 let hi = items.last().unwrap().span().hi();
293 let span = mk_sp(lo, hi);
294 let rw = rewrite_reorderable_or_regroupable_items(
300 self.push_rewrite(span, rw);
303 self.push_rewrite(item.span, None);
310 /// Visits and format the given items. Items are reordered If they are
311 /// consecutive and reorderable.
312 pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
313 while !items.is_empty() {
314 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
315 // subsequent items that have the same item kind to be reordered within
316 // `walk_reorderable_items`. Otherwise, just format the next item for output.
317 let item_kind = ReorderableItemKind::from(items[0]);
318 if item_kind.is_reorderable(self.config) || item_kind.is_regroupable(self.config) {
319 let visited_items_num = self.walk_reorderable_or_regroupable_items(
322 item_kind.in_group(self.config),
324 let (_, rest) = items.split_at(visited_items_num);
327 // Reaching here means items were not reordered. There must be at least
328 // one item left in `items`, so calling `unwrap()` here is safe.
329 let (item, rest) = items.split_first().unwrap();
330 self.visit_item(item);