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 constatns comes before methods).
17 // TODO(#2455): Reorder trait items.
19 use config::{Config, lists::*};
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::{path_to_imported_ident, rewrite_import};
26 use items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
27 use lists::{itemize_list, write_list, ListFormatting};
28 use rewrite::{Rewrite, RewriteContext};
32 use visitor::FmtVisitor;
34 use std::cmp::Ordering;
36 fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
37 a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
40 fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
41 for segment in a.segments.iter().zip(b.segments.iter()) {
42 let ord = compare_path_segments(segment.0, segment.1);
43 if ord != Ordering::Equal {
47 a.segments.len().cmp(&b.segments.len())
50 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
51 use ast::UseTreeKind::*;
53 // `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
56 let paths_cmp = compare_paths(&a.prefix, &b.prefix);
57 if paths_cmp != Ordering::Equal {
62 match (&a.kind, &b.kind) {
63 (&Simple(ident_a), &Simple(ident_b)) => {
64 let name_a = &*path_to_imported_ident(&a.prefix).name.as_str();
65 let name_b = &*path_to_imported_ident(&b.prefix).name.as_str();
66 let name_ordering = if name_a == "self" {
72 } else if name_b == "self" {
77 if name_ordering == Ordering::Equal {
78 if ident_a.name.as_str() != name_a {
79 if ident_b.name.as_str() != name_b {
80 ident_a.name.as_str().cmp(&ident_b.name.as_str())
91 (&Glob, &Glob) => Ordering::Equal,
92 (&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
93 (&Nested(ref a_items), &Nested(ref b_items)) => {
96 .map(|&(ref tree, _)| tree.clone())
100 .map(|&(ref tree, _)| tree.clone())
101 .collect::<Vec<_>>();
102 a.sort_by(|a, b| compare_use_trees(a, b, true));
103 b.sort_by(|a, b| compare_use_trees(a, b, true));
104 for comparison_pair in a.iter().zip(b.iter()) {
105 let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
106 if ord != Ordering::Equal {
110 a.len().cmp(&b.len())
112 (&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
116 /// Choose the ordering between the given two items.
117 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
118 match (&a.node, &b.node) {
119 (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
120 a.ident.name.as_str().cmp(&b.ident.name.as_str())
122 (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
123 compare_use_trees(a_tree, b_tree, false)
125 (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
126 // `extern crate foo as bar;`
127 // ^^^ Comparing this.
129 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
131 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
132 let result = a_orig_name.cmp(&b_orig_name);
133 if result != Ordering::Equal {
137 // `extern crate foo as bar;`
138 // ^^^ Comparing this.
139 match (a_name, b_name) {
140 (Some(..), None) => Ordering::Greater,
141 (None, Some(..)) => Ordering::Less,
142 (None, None) => Ordering::Equal,
143 (Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
150 /// Rewrite a list of items with reordering. Every item in `items` must have
151 /// the same `ast::ItemKind`.
152 // TODO (some day) remove unused imports, expand globs, compress many single
153 // imports into a list import.
154 fn rewrite_reorderable_items(
155 context: &RewriteContext,
156 reorderable_items: &[&ast::Item],
159 ) -> Option<String> {
160 let items = itemize_list(
161 context.snippet_provider,
162 reorderable_items.iter(),
165 |item| item.span().lo(),
166 |item| item.span().hi(),
168 let attrs = filter_inline_attrs(&item.attrs, item.span());
169 let attrs_str = attrs.rewrite(context, shape)?;
171 let missed_span = if attrs.is_empty() {
172 mk_sp(item.span.lo(), item.span.lo())
174 mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
177 let item_str = match item.node {
178 ast::ItemKind::Use(ref tree) => {
179 rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
181 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
182 ast::ItemKind::Mod(..) => rewrite_mod(item),
186 combine_strs_with_missing_comments(
199 let mut item_pair_vec: Vec<_> = items.zip(reorderable_items.iter()).collect();
200 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
201 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
203 let fmt = ListFormatting {
204 tactic: DefinitiveListTactic::Vertical,
206 trailing_separator: SeparatorTactic::Never,
207 separator_place: SeparatorPlace::Back,
209 ends_with_newline: true,
210 preserve_newline: false,
211 config: context.config,
214 write_list(&item_vec, &fmt)
217 fn contains_macro_use_attr(item: &ast::Item) -> bool {
218 attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
221 /// A simplified version of `ast::ItemKind`.
222 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
223 enum ReorderableItemKind {
227 /// An item that cannot be reordered. Either has an unreorderable item kind
228 /// or an `macro_use` attribute.
232 impl ReorderableItemKind {
233 pub fn from(item: &ast::Item) -> Self {
235 _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
236 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
237 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
238 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
239 _ => ReorderableItemKind::Other,
243 pub fn is_same_item_kind(&self, item: &ast::Item) -> bool {
244 ReorderableItemKind::from(item) == *self
247 pub fn is_reorderable(&self, config: &Config) -> bool {
249 ReorderableItemKind::ExternCrate => config.reorder_extern_crates(),
250 ReorderableItemKind::Mod => config.reorder_modules(),
251 ReorderableItemKind::Use => config.reorder_imports(),
252 ReorderableItemKind::Other => false,
256 pub fn in_group(&self, config: &Config) -> bool {
258 ReorderableItemKind::ExternCrate => config.reorder_extern_crates_in_group(),
259 ReorderableItemKind::Mod => config.reorder_modules(),
260 ReorderableItemKind::Use => config.reorder_imports_in_group(),
261 ReorderableItemKind::Other => false,
266 impl<'b, 'a: 'b> FmtVisitor<'a> {
267 /// Format items with the same item kind and reorder them. If `in_group` is
268 /// `true`, then the items separated by an empty line will not be reordered
270 fn walk_reorderable_items(
272 items: &[&ast::Item],
273 item_kind: ReorderableItemKind,
276 let mut last = self.codemap.lookup_line_range(items[0].span());
277 let item_length = items
280 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
281 let current = self.codemap.lookup_line_range(ppi.span());
282 let in_same_group = current.lo < last.hi + 2;
288 let items = &items[..item_length];
290 let at_least_one_in_file_lines = items
292 .any(|item| !out_of_file_lines_range!(self, item.span));
294 if at_least_one_in_file_lines && !items.is_empty() {
295 let lo = items.first().unwrap().span().lo();
296 let hi = items.last().unwrap().span().hi();
297 let span = mk_sp(lo, hi);
298 let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
299 self.push_rewrite(span, rw);
302 self.push_rewrite(item.span, None);
309 /// Visit and format the given items. Items are reordered If they are
310 /// consecutive and reorderable.
311 pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
312 while !items.is_empty() {
313 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
314 // subsequent items that have the same item kind to be reordered within
315 // `walk_reorderable_items`. Otherwise, just format the next item for output.
316 let item_kind = ReorderableItemKind::from(items[0]);
317 if item_kind.is_reorderable(self.config) {
318 let visited_items_num =
319 self.walk_reorderable_items(items, item_kind, item_kind.in_group(self.config));
320 let (_, rest) = items.split_at(visited_items_num);
323 // Reaching here means items were not reordered. There must be at least
324 // one item left in `items`, so calling `unwrap()` here is safe.
325 let (item, rest) = items.split_first().unwrap();
326 self.visit_item(item);