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};
13 use crate::attr::filter_inline_attrs;
14 use crate::comment::combine_strs_with_missing_comments;
15 use crate::config::Config;
16 use crate::imports::{merge_use_trees, UseTree};
17 use crate::items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
18 use crate::lists::{itemize_list, write_list, ListFormatting, ListItem};
19 use crate::rewrite::{Rewrite, RewriteContext};
20 use crate::shape::Shape;
21 use crate::source_map::LineRangeUtils;
22 use crate::spanned::Spanned;
23 use crate::utils::{contains_skip, mk_sp};
24 use crate::visitor::FmtVisitor;
26 /// Choose the ordering between the given two items.
27 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
28 match (&a.node, &b.node) {
29 (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
30 a.ident.as_str().cmp(&b.ident.as_str())
32 (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
33 // `extern crate foo as bar;`
34 // ^^^ Comparing this.
36 a_name.map_or_else(|| a.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
38 b_name.map_or_else(|| b.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
39 let result = a_orig_name.cmp(&b_orig_name);
40 if result != Ordering::Equal {
44 // `extern crate foo as bar;`
45 // ^^^ Comparing this.
46 match (a_name, b_name) {
47 (Some(..), None) => Ordering::Greater,
48 (None, Some(..)) => Ordering::Less,
49 (None, None) => Ordering::Equal,
50 (Some(..), Some(..)) => a.ident.as_str().cmp(&b.ident.as_str()),
57 fn wrap_reorderable_items(
58 context: &RewriteContext<'_>,
59 list_items: &[ListItem],
62 let fmt = ListFormatting::new(shape, context.config)
64 .align_comments(false);
65 write_list(list_items, &fmt)
68 fn rewrite_reorderable_item(
69 context: &RewriteContext<'_>,
73 let attrs = filter_inline_attrs(&item.attrs, item.span());
74 let attrs_str = attrs.rewrite(context, shape)?;
76 let missed_span = if attrs.is_empty() {
77 mk_sp(item.span.lo(), item.span.lo())
79 mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
82 let item_str = match item.node {
83 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
84 ast::ItemKind::Mod(..) => rewrite_mod(context, item),
88 let allow_extend = if attrs.len() == 1 {
89 let line_len = attrs_str.len() + 1 + item_str.len();
90 !attrs.first().unwrap().is_sugared_doc
91 && context.config.inline_attribute_width() >= line_len
96 combine_strs_with_missing_comments(
106 /// Rewrite a list of items with reordering. Every item in `items` must have
107 /// the same `ast::ItemKind`.
108 fn rewrite_reorderable_items(
109 context: &RewriteContext<'_>,
110 reorderable_items: &[&ast::Item],
113 ) -> Option<String> {
114 match reorderable_items[0].node {
115 // FIXME: Remove duplicated code.
116 ast::ItemKind::Use(..) => {
117 let mut normalized_items: Vec<_> = reorderable_items
119 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
121 let cloned = normalized_items.clone();
122 // Add comments before merging.
123 let list_items = itemize_list(
124 context.snippet_provider,
128 |item| item.span().lo(),
129 |item| item.span().hi(),
130 |_item| Some("".to_owned()),
135 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
136 item.list_item = Some(list_item.clone());
138 if context.config.merge_imports() {
139 normalized_items = merge_use_trees(normalized_items);
141 normalized_items.sort();
143 // 4 = "use ", 1 = ";"
144 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
145 let item_vec: Vec<_> = normalized_items
147 .map(|use_tree| ListItem {
148 item: use_tree.rewrite_top_level(context, nested_shape),
149 ..use_tree.list_item.unwrap_or_else(ListItem::empty)
153 wrap_reorderable_items(context, &item_vec, nested_shape)
156 let list_items = itemize_list(
157 context.snippet_provider,
158 reorderable_items.iter(),
161 |item| item.span().lo(),
162 |item| item.span().hi(),
163 |item| rewrite_reorderable_item(context, item, shape),
169 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
170 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
171 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
173 wrap_reorderable_items(context, &item_vec, shape)
178 fn contains_macro_use_attr(item: &ast::Item) -> bool {
179 attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
182 /// A simplified version of `ast::ItemKind`.
183 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
184 enum ReorderableItemKind {
188 /// An item that cannot be reordered. Either has an unreorderable item kind
189 /// or an `macro_use` attribute.
193 impl ReorderableItemKind {
194 fn from(item: &ast::Item) -> Self {
196 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
197 ReorderableItemKind::Other
199 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
200 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
201 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
202 _ => ReorderableItemKind::Other,
206 fn is_same_item_kind(self, item: &ast::Item) -> bool {
207 ReorderableItemKind::from(item) == self
210 fn is_reorderable(self, config: &Config) -> bool {
212 ReorderableItemKind::ExternCrate => config.reorder_imports(),
213 ReorderableItemKind::Mod => config.reorder_modules(),
214 ReorderableItemKind::Use => config.reorder_imports(),
215 ReorderableItemKind::Other => false,
219 fn in_group(self) -> bool {
221 ReorderableItemKind::ExternCrate
222 | ReorderableItemKind::Mod
223 | ReorderableItemKind::Use => true,
224 ReorderableItemKind::Other => false,
229 impl<'b, 'a: 'b> FmtVisitor<'a> {
230 /// Format items with the same item kind and reorder them. If `in_group` is
231 /// `true`, then the items separated by an empty line will not be reordered
233 fn walk_reorderable_items(
235 items: &[&ast::Item],
236 item_kind: ReorderableItemKind,
239 let mut last = self.source_map.lookup_line_range(items[0].span());
240 let item_length = items
243 item_kind.is_same_item_kind(&***ppi)
245 let current = self.source_map.lookup_line_range(ppi.span());
246 let in_same_group = current.lo < last.hi + 2;
252 let items = &items[..item_length];
254 let at_least_one_in_file_lines = items
256 .any(|item| !out_of_file_lines_range!(self, item.span));
258 if at_least_one_in_file_lines && !items.is_empty() {
259 let lo = items.first().unwrap().span().lo();
260 let hi = items.last().unwrap().span().hi();
261 let span = mk_sp(lo, hi);
262 let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
263 self.push_rewrite(span, rw);
266 self.push_rewrite(item.span, None);
273 /// Visits and format the given items. Items are reordered If they are
274 /// consecutive and reorderable.
275 pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
276 while !items.is_empty() {
277 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
278 // subsequent items that have the same item kind to be reordered within
279 // `walk_reorderable_items`. Otherwise, just format the next item for output.
280 let item_kind = ReorderableItemKind::from(items[0]);
281 if item_kind.is_reorderable(self.config) {
282 let visited_items_num =
283 self.walk_reorderable_items(items, item_kind, item_kind.in_group());
284 let (_, rest) = items.split_at(visited_items_num);
287 // Reaching here means items were not reordered. There must be at least
288 // one item left in `items`, so calling `unwrap()` here is safe.
289 let (item, rest) = items.split_first().unwrap();
290 self.visit_item(item);