1use std::cmp::Ordering;
10
11use rustc_ast::{ast, attr};
12use rustc_span::{Span, symbol::sym};
13
14use crate::config::{Config, GroupImportsTactic};
15use crate::imports::{UseSegmentKind, UseTree, normalize_use_trees_with_granularity};
16use crate::items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
17use crate::lists::{ListFormatting, ListItem, itemize_list, write_list};
18use crate::rewrite::{RewriteContext, RewriteErrorExt};
19use crate::shape::Shape;
20use crate::source_map::LineRangeUtils;
21use crate::spanned::Spanned;
22use crate::utils::{contains_skip, mk_sp};
23use crate::visitor::FmtVisitor;
24
25fn 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())
30 }
31 (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
32 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 {
38 return result;
39 }
40
41 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()),
48 }
49 }
50 _ => unreachable!(),
51 }
52}
53
54fn wrap_reorderable_items(
55 context: &RewriteContext<'_>,
56 list_items: &[ListItem],
57 shape: Shape,
58) -> Option<String> {
59 let fmt = ListFormatting::new(shape, context.config)
60 .separator("")
61 .align_comments(false);
62 write_list(list_items, &fmt).ok()
63}
64
65fn rewrite_reorderable_item(
66 context: &RewriteContext<'_>,
67 item: &ast::Item,
68 shape: Shape,
69) -> Option<String> {
70 match item.kind {
71 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item, shape),
72 ast::ItemKind::Mod(..) => rewrite_mod(context, item, shape),
73 _ => None,
74 }
75}
76
77fn rewrite_reorderable_or_regroupable_items(
81 context: &RewriteContext<'_>,
82 reorderable_items: &[&ast::Item],
83 shape: Shape,
84 span: Span,
85) -> Option<String> {
86 match reorderable_items[0].kind {
87 ast::ItemKind::Use(..) => {
89 let mut normalized_items: Vec<_> = reorderable_items
90 .iter()
91 .filter_map(|item| UseTree::from_ast_with_normalization(context, item))
92 .collect();
93 let cloned = normalized_items.clone();
94 let list_items = itemize_list(
96 context.snippet_provider,
97 cloned.iter(),
98 "",
99 ";",
100 |item| item.span().lo(),
101 |item| item.span().hi(),
102 |_item| Ok("".to_owned()),
103 span.lo(),
104 span.hi(),
105 false,
106 );
107 for (item, list_item) in normalized_items.iter_mut().zip(list_items) {
108 item.list_item = Some(list_item.clone());
109 }
110 normalized_items = normalize_use_trees_with_granularity(
111 normalized_items,
112 context.config.imports_granularity(),
113 );
114
115 let mut regrouped_items = match context.config.group_imports() {
116 GroupImportsTactic::Preserve | GroupImportsTactic::One => {
117 vec![normalized_items]
118 }
119 GroupImportsTactic::StdExternalCrate => group_imports(normalized_items),
120 };
121
122 if context.config.reorder_imports() {
123 regrouped_items.iter_mut().for_each(|items| items.sort())
124 }
125
126 let nested_shape = shape.offset_left(4)?.sub_width(1)?;
128 let item_vec: Vec<_> = regrouped_items
129 .into_iter()
130 .filter(|use_group| !use_group.is_empty())
131 .map(|use_group| {
132 let item_vec: Vec<_> = use_group
133 .into_iter()
134 .map(|use_tree| {
135 let item = use_tree.rewrite_top_level(context, nested_shape);
136 if let Some(list_item) = use_tree.list_item {
137 ListItem {
138 item: item,
139 ..list_item
140 }
141 } else {
142 ListItem::from_item(item)
143 }
144 })
145 .collect();
146 wrap_reorderable_items(context, &item_vec, nested_shape)
147 })
148 .collect::<Option<Vec<_>>>()?;
149
150 let join_string = format!("\n\n{}", shape.indent.to_string(context.config));
151 Some(item_vec.join(&join_string))
152 }
153 _ => {
154 let list_items = itemize_list(
155 context.snippet_provider,
156 reorderable_items.iter(),
157 "",
158 ";",
159 |item| item.span().lo(),
160 |item| item.span().hi(),
161 |item| rewrite_reorderable_item(context, item, shape).unknown_error(),
162 span.lo(),
163 span.hi(),
164 false,
165 );
166
167 let mut item_pair_vec: Vec<_> = list_items.zip(reorderable_items.iter()).collect();
168 item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
169 let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
170
171 wrap_reorderable_items(context, &item_vec, shape)
172 }
173 }
174}
175
176fn contains_macro_use_attr(item: &ast::Item) -> bool {
177 attr::contains_name(&item.attrs, sym::macro_use)
178}
179
180fn group_imports(uts: Vec<UseTree>) -> Vec<Vec<UseTree>> {
183 let mut std_imports = Vec::new();
184 let mut external_imports = Vec::new();
185 let mut local_imports = Vec::new();
186
187 for ut in uts.into_iter() {
188 if ut.path.is_empty() {
189 external_imports.push(ut);
190 continue;
191 }
192 match &ut.path[0].kind {
193 UseSegmentKind::Ident(id, _) => match id.as_ref() {
194 "std" | "alloc" | "core" => std_imports.push(ut),
195 _ => external_imports.push(ut),
196 },
197 UseSegmentKind::Slf(_) | UseSegmentKind::Super(_) | UseSegmentKind::Crate(_) => {
198 local_imports.push(ut)
199 }
200 UseSegmentKind::Glob | UseSegmentKind::List(_) => external_imports.push(ut),
202 }
203 }
204
205 vec![std_imports, external_imports, local_imports]
206}
207
208#[derive(Debug, PartialEq, Eq, Copy, Clone)]
210enum ReorderableItemKind {
211 ExternCrate,
212 Mod,
213 Use,
214 Other,
217}
218
219impl ReorderableItemKind {
220 fn from(item: &ast::Item) -> Self {
221 match item.kind {
222 _ if contains_macro_use_attr(item) | contains_skip(&item.attrs) => {
223 ReorderableItemKind::Other
224 }
225 ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
226 ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
227 ast::ItemKind::Use(..) => ReorderableItemKind::Use,
228 _ => ReorderableItemKind::Other,
229 }
230 }
231
232 fn is_same_item_kind(self, item: &ast::Item) -> bool {
233 ReorderableItemKind::from(item) == self
234 }
235
236 fn is_reorderable(self, config: &Config) -> bool {
237 match self {
238 ReorderableItemKind::ExternCrate => config.reorder_imports(),
239 ReorderableItemKind::Mod => config.reorder_modules(),
240 ReorderableItemKind::Use => config.reorder_imports(),
241 ReorderableItemKind::Other => false,
242 }
243 }
244
245 fn is_regroupable(self, config: &Config) -> bool {
246 match self {
247 ReorderableItemKind::ExternCrate
248 | ReorderableItemKind::Mod
249 | ReorderableItemKind::Other => false,
250 ReorderableItemKind::Use => config.group_imports() != GroupImportsTactic::Preserve,
251 }
252 }
253
254 fn in_group(self, config: &Config) -> bool {
255 match self {
256 ReorderableItemKind::ExternCrate | ReorderableItemKind::Mod => true,
257 ReorderableItemKind::Use => config.group_imports() == GroupImportsTactic::Preserve,
258 ReorderableItemKind::Other => false,
259 }
260 }
261}
262
263impl<'b, 'a: 'b> FmtVisitor<'a> {
264 fn walk_reorderable_or_regroupable_items(
268 &mut self,
269 items: &[&ast::Item],
270 item_kind: ReorderableItemKind,
271 in_group: bool,
272 ) -> usize {
273 let mut last = self.psess.lookup_line_range(items[0].span());
274 let item_length = items
275 .iter()
276 .take_while(|ppi| {
277 item_kind.is_same_item_kind(&***ppi)
278 && (!in_group || {
279 let current = self.psess.lookup_line_range(ppi.span());
280 let in_same_group = current.lo < last.hi + 2;
281 last = current;
282 in_same_group
283 })
284 })
285 .count();
286 let items = &items[..item_length];
287
288 let at_least_one_in_file_lines = items
289 .iter()
290 .any(|item| !out_of_file_lines_range!(self, item.span));
291
292 if at_least_one_in_file_lines && !items.is_empty() {
293 let lo = items.first().unwrap().span().lo();
294 let hi = items.last().unwrap().span().hi();
295 let span = mk_sp(lo, hi);
296 let rw = rewrite_reorderable_or_regroupable_items(
297 &self.get_context(),
298 items,
299 self.shape(),
300 span,
301 );
302 self.push_rewrite(span, rw);
303 } else {
304 for item in items {
305 self.push_rewrite(item.span, None);
306 }
307 }
308
309 item_length
310 }
311
312 pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
315 while !items.is_empty() {
316 let item_kind = ReorderableItemKind::from(items[0]);
320 if item_kind.is_reorderable(self.config) || item_kind.is_regroupable(self.config) {
321 let visited_items_num = self.walk_reorderable_or_regroupable_items(
322 items,
323 item_kind,
324 item_kind.in_group(self.config),
325 );
326 let (_, rest) = items.split_at(visited_items_num);
327 items = rest;
328 } else {
329 let (item, rest) = items.split_first().unwrap();
332 self.visit_item(item);
333 items = rest;
334 }
335 }
336 }
337}