Skip to content

Commit 25f2dff

Browse files
authored
Merge pull request #2461 from topecongiro/reorder-mod
Refactoring: add `reorder` modules
2 parents cbf524f + c32eb1f commit 25f2dff

File tree

5 files changed

+351
-298
lines changed

5 files changed

+351
-298
lines changed

rustfmt-core/src/imports.rs

Lines changed: 6 additions & 207 deletions
Original file line numberDiff line numberDiff line change
@@ -15,132 +15,20 @@ use syntax::ast;
1515
use syntax::codemap::{BytePos, Span};
1616

1717
use codemap::SpanUtils;
18-
use comment::combine_strs_with_missing_comments;
1918
use config::IndentStyle;
2019
use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
2120
use rewrite::{Rewrite, RewriteContext};
2221
use shape::Shape;
23-
use spanned::Spanned;
2422
use types::{rewrite_path, PathContext};
2523
use utils::{format_visibility, mk_sp};
26-
use visitor::{rewrite_extern_crate, FmtVisitor};
24+
use visitor::FmtVisitor;
2725

28-
fn compare_path_segments(a: &ast::PathSegment, b: &ast::PathSegment) -> Ordering {
29-
a.identifier.name.as_str().cmp(&b.identifier.name.as_str())
30-
}
31-
32-
fn compare_paths(a: &ast::Path, b: &ast::Path) -> Ordering {
33-
for segment in a.segments.iter().zip(b.segments.iter()) {
34-
let ord = compare_path_segments(segment.0, segment.1);
35-
if ord != Ordering::Equal {
36-
return ord;
37-
}
38-
}
39-
a.segments.len().cmp(&b.segments.len())
40-
}
41-
42-
fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree, nested: bool) -> Ordering {
43-
use ast::UseTreeKind::*;
44-
45-
// `use_nested_groups` is not yet supported, remove the `if !nested` when support will be
46-
// fully added
47-
if !nested {
48-
let paths_cmp = compare_paths(&a.prefix, &b.prefix);
49-
if paths_cmp != Ordering::Equal {
50-
return paths_cmp;
51-
}
52-
}
53-
54-
match (&a.kind, &b.kind) {
55-
(&Simple(ident_a), &Simple(ident_b)) => {
56-
let name_a = &*path_to_imported_ident(&a.prefix).name.as_str();
57-
let name_b = &*path_to_imported_ident(&b.prefix).name.as_str();
58-
let name_ordering = if name_a == "self" {
59-
if name_b == "self" {
60-
Ordering::Equal
61-
} else {
62-
Ordering::Less
63-
}
64-
} else if name_b == "self" {
65-
Ordering::Greater
66-
} else {
67-
name_a.cmp(name_b)
68-
};
69-
if name_ordering == Ordering::Equal {
70-
if ident_a.name.as_str() != name_a {
71-
if ident_b.name.as_str() != name_b {
72-
ident_a.name.as_str().cmp(&ident_b.name.as_str())
73-
} else {
74-
Ordering::Greater
75-
}
76-
} else {
77-
Ordering::Less
78-
}
79-
} else {
80-
name_ordering
81-
}
82-
}
83-
(&Glob, &Glob) => Ordering::Equal,
84-
(&Simple(_), _) | (&Glob, &Nested(_)) => Ordering::Less,
85-
(&Nested(ref a_items), &Nested(ref b_items)) => {
86-
let mut a = a_items
87-
.iter()
88-
.map(|&(ref tree, _)| tree.clone())
89-
.collect::<Vec<_>>();
90-
let mut b = b_items
91-
.iter()
92-
.map(|&(ref tree, _)| tree.clone())
93-
.collect::<Vec<_>>();
94-
a.sort_by(|a, b| compare_use_trees(a, b, true));
95-
b.sort_by(|a, b| compare_use_trees(a, b, true));
96-
for comparison_pair in a.iter().zip(b.iter()) {
97-
let ord = compare_use_trees(comparison_pair.0, comparison_pair.1, true);
98-
if ord != Ordering::Equal {
99-
return ord;
100-
}
101-
}
102-
a.len().cmp(&b.len())
103-
}
104-
(&Glob, &Simple(_)) | (&Nested(_), _) => Ordering::Greater,
105-
}
106-
}
107-
108-
fn compare_use_items(a: &ast::Item, b: &ast::Item) -> Ordering {
109-
match (&a.node, &b.node) {
110-
(&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
111-
a.ident.name.as_str().cmp(&b.ident.name.as_str())
112-
}
113-
(&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
114-
compare_use_trees(a_tree, b_tree, false)
115-
}
116-
(&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
117-
// `extern crate foo as bar;`
118-
// ^^^ Comparing this.
119-
let a_orig_name =
120-
a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
121-
let b_orig_name =
122-
b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
123-
let result = a_orig_name.cmp(&b_orig_name);
124-
if result != Ordering::Equal {
125-
return result;
126-
}
127-
128-
// `extern crate foo as bar;`
129-
// ^^^ Comparing this.
130-
match (a_name, b_name) {
131-
(Some(..), None) => Ordering::Greater,
132-
(None, Some(..)) => Ordering::Less,
133-
(None, None) => Ordering::Equal,
134-
(Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
135-
}
136-
}
137-
_ => unreachable!(),
138-
}
26+
/// Returns a name imported by a `use` declaration. e.g. returns `Ordering`
27+
/// for `std::cmp::Ordering` and `self` for `std::cmp::self`.
28+
pub fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
29+
path.segments.last().unwrap().identifier
13930
}
14031

141-
// TODO (some day) remove unused imports, expand globs, compress many single
142-
// imports into a list import.
143-
14432
fn rewrite_prefix(path: &ast::Path, context: &RewriteContext, shape: Shape) -> Option<String> {
14533
if path.segments.len() > 1 && path_to_imported_ident(path).to_string() == "self" {
14634
let path = &ast::Path {
@@ -208,7 +96,7 @@ fn is_unused_import_inner(tree: &ast::UseTree) -> bool {
20896
}
20997

21098
// Rewrite `use foo;` WITHOUT attributes.
211-
fn rewrite_import(
99+
pub fn rewrite_import(
212100
context: &RewriteContext,
213101
vis: &ast::Visibility,
214102
tree: &ast::UseTree,
@@ -234,92 +122,7 @@ fn rewrite_import(
234122
}
235123
}
236124

237-
/// Rewrite an inline mod.
238-
fn rewrite_mod(item: &ast::Item) -> String {
239-
let mut result = String::with_capacity(32);
240-
result.push_str(&*format_visibility(&item.vis));
241-
result.push_str("mod ");
242-
result.push_str(&item.ident.to_string());
243-
result.push(';');
244-
result
245-
}
246-
247-
fn rewrite_imports(
248-
context: &RewriteContext,
249-
use_items: &[&ast::Item],
250-
shape: Shape,
251-
span: Span,
252-
) -> Option<String> {
253-
let items = itemize_list(
254-
context.codemap,
255-
use_items.iter(),
256-
"",
257-
";",
258-
|item| item.span().lo(),
259-
|item| item.span().hi(),
260-
|item| {
261-
let attrs = ::visitor::filter_inline_attrs(&item.attrs, item.span());
262-
let attrs_str = attrs.rewrite(context, shape)?;
263-
264-
let missed_span = if attrs.is_empty() {
265-
mk_sp(item.span.lo(), item.span.lo())
266-
} else {
267-
mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
268-
};
269-
270-
let item_str = match item.node {
271-
ast::ItemKind::Use(ref tree) => {
272-
rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
273-
}
274-
ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
275-
ast::ItemKind::Mod(..) => rewrite_mod(item),
276-
_ => return None,
277-
};
278-
279-
combine_strs_with_missing_comments(
280-
context,
281-
&attrs_str,
282-
&item_str,
283-
missed_span,
284-
shape,
285-
false,
286-
)
287-
},
288-
span.lo(),
289-
span.hi(),
290-
false,
291-
);
292-
let mut item_pair_vec: Vec<_> = items.zip(use_items.iter()).collect();
293-
item_pair_vec.sort_by(|a, b| compare_use_items(a.1, b.1));
294-
let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
295-
296-
let fmt = ListFormatting {
297-
tactic: DefinitiveListTactic::Vertical,
298-
separator: "",
299-
trailing_separator: SeparatorTactic::Never,
300-
separator_place: SeparatorPlace::Back,
301-
shape,
302-
ends_with_newline: true,
303-
preserve_newline: false,
304-
config: context.config,
305-
};
306-
307-
write_list(&item_vec, &fmt)
308-
}
309-
310125
impl<'a> FmtVisitor<'a> {
311-
pub fn format_imports(&mut self, use_items: &[&ast::Item]) {
312-
if use_items.is_empty() {
313-
return;
314-
}
315-
316-
let lo = use_items.first().unwrap().span().lo();
317-
let hi = use_items.last().unwrap().span().hi();
318-
let span = mk_sp(lo, hi);
319-
let rw = rewrite_imports(&self.get_context(), use_items, self.shape(), span);
320-
self.push_rewrite(span, rw);
321-
}
322-
323126
pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
324127
let span = item.span;
325128
let shape = self.shape();
@@ -594,7 +397,3 @@ fn move_self_to_front(items: &mut Vec<ListItem>) -> bool {
594397
None => false,
595398
}
596399
}
597-
598-
fn path_to_imported_ident(path: &ast::Path) -> ast::Ident {
599-
path.segments.last().unwrap().identifier
600-
}

rustfmt-core/src/items.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2845,3 +2845,13 @@ impl Rewrite for ast::GenericParam {
28452845
}
28462846
}
28472847
}
2848+
2849+
/// Rewrite an inline mod.
2850+
pub fn rewrite_mod(item: &ast::Item) -> String {
2851+
let mut result = String::with_capacity(32);
2852+
result.push_str(&*format_visibility(&item.vis));
2853+
result.push_str("mod ");
2854+
result.push_str(&item.ident.to_string());
2855+
result.push(';');
2856+
result
2857+
}

rustfmt-core/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ pub use config::summary::Summary;
5252

5353
#[macro_use]
5454
mod utils;
55+
5556
mod chains;
5657
mod checkstyle;
5758
mod closures;
@@ -67,6 +68,7 @@ mod macros;
6768
mod missed_spans;
6869
pub mod modules;
6970
mod patterns;
71+
mod reorder;
7072
mod rewrite;
7173
pub mod rustfmt_diff;
7274
mod shape;

0 commit comments

Comments
 (0)