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};
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;
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 = normalize_use_trees_with_granularity(
112 context.config.imports_granularity(),
115 let mut regrouped_items = match context.config.group_imports() {
116 GroupImportsTactic::Preserve | GroupImportsTactic::One => {
117 vec![normalized_items]
119 GroupImportsTactic::StdExternalCrate => group_imports(normalized_items),
122 if context.config.reorder_imports() {
123 regrouped_items.iter_mut().for_each(|items| items.sort())
126 // 4 = "use ", 1 = ";"
127 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
128 let item_vec: Vec<_> = regrouped_items
130 .filter(|use_group| !use_group.is_empty())
132 let item_vec: Vec<_> = use_group
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)
139 wrap_reorderable_items(context, &item_vec, nested_shape)
141 .collect::<Option<Vec<_>>>()?;
143 let join_string = format!("\n\n{}", shape.indent.to_string(context.config));
144 Some(item_vec.join(&join_string))
147 let list_items = itemize_list(
148 context.snippet_provider,
149 reorderable_items.iter(),
152 |item| item.span().lo(),
153 |item| item.span().hi(),
154 |item| rewrite_reorderable_item(context, item, shape),
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();
164 wrap_reorderable_items(context, &item_vec, shape)
169 fn contains_macro_use_attr(item: &ast::Item) -> bool {
170 crate::attr::contains_name(&item.attrs, sym::macro_use)
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();
180 for ut in uts.into_iter() {
181 if ut.path.is_empty() {
182 external_imports.push(ut);
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),
190 UseSegmentKind::Slf(_) | UseSegmentKind::Super(_) | UseSegmentKind::Crate(_) => {
191 local_imports.push(ut)
193 // These are probably illegal here
194 UseSegmentKind::Glob | UseSegmentKind::List(_) => external_imports.push(ut),
198 vec![std_imports, external_imports, local_imports]
201 /// A simplified version of `ast::ItemKind`.
202 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
203 enum ReorderableItemKind {
207 /// An item that cannot be reordered. Either has an unreorderable item kind
208 /// or an `macro_use` attribute.
212 impl ReorderableItemKind {
213 fn from(item: &ast::Item) -> Self {
215 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
216 ReorderableItemKind::Other
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,
225 fn is_same_item_kind(self, item: &ast::Item) -> bool {
226 ReorderableItemKind::from(item) == self
229 fn is_reorderable(self, config: &Config) -> bool {
231 ReorderableItemKind::ExternCrate => config.reorder_imports(),
232 ReorderableItemKind::Mod => config.reorder_modules(),
233 ReorderableItemKind::Use => config.reorder_imports(),
234 ReorderableItemKind::Other => false,
238 fn is_regroupable(self, config: &Config) -> bool {
240 ReorderableItemKind::ExternCrate
241 | ReorderableItemKind::Mod
242 | ReorderableItemKind::Other => false,
243 ReorderableItemKind::Use => config.group_imports() != GroupImportsTactic::Preserve,
247 fn in_group(self, config: &Config) -> bool {
249 ReorderableItemKind::ExternCrate | ReorderableItemKind::Mod => true,
250 ReorderableItemKind::Use => config.group_imports() == GroupImportsTactic::Preserve,
251 ReorderableItemKind::Other => false,
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(
262 items: &[&ast::Item],
263 item_kind: ReorderableItemKind,
266 let mut last = self.parse_sess.lookup_line_range(items[0].span());
267 let item_length = items
270 item_kind.is_same_item_kind(&***ppi)
272 let current = self.parse_sess.lookup_line_range(ppi.span());
273 let in_same_group = current.lo < last.hi + 2;
279 let items = &items[..item_length];
281 let at_least_one_in_file_lines = items
283 .any(|item| !out_of_file_lines_range!(self, item.span));
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(
295 self.push_rewrite(span, rw);
298 self.push_rewrite(item.span, None);
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(
317 item_kind.in_group(self.config),
319 let (_, rest) = items.split_at(visited_items_num);
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);