1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! `mod`, `extern crate` and `use` declarations are reorderd in alphabetical
14 //! order. Trait items are reordered in pre-determined order (associated types
15 //! and constants comes before methods).
17 // TODO(#2455): Reorder trait items.
19 use config::{lists::*, Config};
20 use syntax::{ast, attr, codemap::Span};
22 use attr::filter_inline_attrs;
23 use codemap::LineRangeUtils;
24 use comment::combine_strs_with_missing_comments;
25 use imports::{merge_use_trees, UseTree};
26 use items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
27 use lists::{itemize_list, write_list, ListFormatting, ListItem};
28 use rewrite::{Rewrite, RewriteContext};
32 use visitor::FmtVisitor;
34 use std::cmp::{Ord, Ordering};
36 /// Choose the ordering between the given two items.
37 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
38 match (&a.node, &b.node) {
39 (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
40 a.ident.name.as_str().cmp(&b.ident.name.as_str())
42 (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
43 // `extern crate foo as bar;`
44 // ^^^ Comparing this.
46 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
48 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
49 let result = a_orig_name.cmp(&b_orig_name);
50 if result != Ordering::Equal {
54 // `extern crate foo as bar;`
55 // ^^^ Comparing this.
56 match (a_name, b_name) {
57 (Some(..), None) => Ordering::Greater,
58 (None, Some(..)) => Ordering::Less,
59 (None, None) => Ordering::Equal,
60 (Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
67 fn wrap_reorderable_items(
68 context: &RewriteContext,
69 list_items: &[ListItem],
72 let fmt = ListFormatting {
73 tactic: DefinitiveListTactic::Vertical,
75 trailing_separator: SeparatorTactic::Never,
76 separator_place: SeparatorPlace::Back,
78 ends_with_newline: true,
79 preserve_newline: false,
80 config: context.config,
83 write_list(list_items, &fmt)
86 fn rewrite_reorderable_item(
87 context: &RewriteContext,
91 let attrs = filter_inline_attrs(&item.attrs, item.span());
92 let attrs_str = attrs.rewrite(context, shape)?;
94 let missed_span = if attrs.is_empty() {
95 mk_sp(item.span.lo(), item.span.lo())
97 mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
100 let item_str = match item.node {
101 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
102 ast::ItemKind::Mod(..) => rewrite_mod(item),
106 combine_strs_with_missing_comments(context, &attrs_str, &item_str, missed_span, shape, false)
109 /// Rewrite a list of items with reordering. Every item in `items` must have
110 /// the same `ast::ItemKind`.
111 fn rewrite_reorderable_items(
112 context: &RewriteContext,
113 reorderable_items: &[&ast::Item],
116 ) -> Option<String> {
117 match reorderable_items[0].node {
118 // FIXME: Remove duplicated code.
119 ast::ItemKind::Use(..) => {
120 let mut normalized_items: Vec<_> = reorderable_items
122 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
124 let cloned = normalized_items.clone();
125 // Add comments before merging.
126 let list_items = itemize_list(
127 context.snippet_provider,
131 |item| item.span().lo(),
132 |item| item.span().hi(),
133 |_item| Some("".to_owned()),
138 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
139 item.list_item = Some(list_item.clone());
141 if context.config.merge_imports() {
142 normalized_items = merge_use_trees(normalized_items);
144 normalized_items.sort();
146 // 4 = "use ", 1 = ";"
147 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
148 let item_vec: Vec<_> = normalized_items
150 .map(|use_tree| ListItem {
151 item: use_tree.rewrite_top_level(context, nested_shape),
152 ..use_tree.list_item.unwrap_or_else(ListItem::empty)
156 wrap_reorderable_items(context, &item_vec, nested_shape)
159 let list_items = itemize_list(
160 context.snippet_provider,
161 reorderable_items.iter(),
164 |item| item.span().lo(),
165 |item| item.span().hi(),
166 |item| rewrite_reorderable_item(context, item, shape),
172 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
173 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
174 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
176 wrap_reorderable_items(context, &item_vec, shape)
181 fn contains_macro_use_attr(item: &ast::Item) -> bool {
182 attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
185 /// A simplified version of `ast::ItemKind`.
186 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
187 enum ReorderableItemKind {
191 /// An item that cannot be reordered. Either has an unreorderable item kind
192 /// or an `macro_use` attribute.
196 impl ReorderableItemKind {
197 pub fn from(item: &ast::Item) -> Self {
199 _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
200 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
201 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
202 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
203 _ => ReorderableItemKind::Other,
207 pub fn is_same_item_kind(&self, item: &ast::Item) -> bool {
208 ReorderableItemKind::from(item) == *self
211 pub fn is_reorderable(&self, config: &Config) -> bool {
213 ReorderableItemKind::ExternCrate => config.reorder_imports(),
214 ReorderableItemKind::Mod => config.reorder_modules(),
215 ReorderableItemKind::Use => config.reorder_imports(),
216 ReorderableItemKind::Other => false,
220 pub fn in_group(&self) -> bool {
222 ReorderableItemKind::ExternCrate
223 | ReorderableItemKind::Mod
224 | ReorderableItemKind::Use => true,
225 ReorderableItemKind::Other => false,
230 impl<'b, 'a: 'b> FmtVisitor<'a> {
231 /// Format items with the same item kind and reorder them. If `in_group` is
232 /// `true`, then the items separated by an empty line will not be reordered
234 fn walk_reorderable_items(
236 items: &[&ast::Item],
237 item_kind: ReorderableItemKind,
240 let mut last = self.codemap.lookup_line_range(items[0].span());
241 let item_length = items
244 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
245 let current = self.codemap.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 /// Visit and format the given items. Items are reordered If they are
274 /// consecutive and reorderable.
275 pub 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);