]> git.lizzy.rs Git - rust.git/blob - src/reorder.rs
0a33177d72f8ec88db5944c0f6d0d38c993de230
[rust.git] / src / reorder.rs
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.
4 //
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.
10
11 //! Reorder items.
12 //!
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).
16
17 // TODO(#2455): Reorder trait items.
18
19 use config::{Config, lists::*};
20 use syntax::ast::UseTreeKind;
21 use syntax::{ast, attr, codemap::Span};
22
23 use attr::filter_inline_attrs;
24 use codemap::LineRangeUtils;
25 use comment::combine_strs_with_missing_comments;
26 use imports::{path_to_imported_ident, rewrite_import};
27 use items::{is_mod_decl, rewrite_extern_crate, rewrite_mod};
28 use lists::{itemize_list, write_list, ListFormatting};
29 use rewrite::{Rewrite, RewriteContext};
30 use shape::Shape;
31 use spanned::Spanned;
32 use utils::mk_sp;
33 use visitor::FmtVisitor;
34
35 use std::cmp::{Ord, Ordering, PartialOrd};
36
37 fn compare_use_trees(a: &ast::UseTree, b: &ast::UseTree) -> Ordering {
38     let aa = UseTree::from_ast(a).normalize();
39     let bb = UseTree::from_ast(b).normalize();
40     aa.cmp(&bb)
41 }
42
43 /// Choose the ordering between the given two items.
44 fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
45     match (&a.node, &b.node) {
46         (&ast::ItemKind::Mod(..), &ast::ItemKind::Mod(..)) => {
47             a.ident.name.as_str().cmp(&b.ident.name.as_str())
48         }
49         (&ast::ItemKind::Use(ref a_tree), &ast::ItemKind::Use(ref b_tree)) => {
50             compare_use_trees(a_tree, b_tree)
51         }
52         (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
53             // `extern crate foo as bar;`
54             //               ^^^ Comparing this.
55             let a_orig_name =
56                 a_name.map_or_else(|| a.ident.name.as_str(), |symbol| symbol.as_str());
57             let b_orig_name =
58                 b_name.map_or_else(|| b.ident.name.as_str(), |symbol| symbol.as_str());
59             let result = a_orig_name.cmp(&b_orig_name);
60             if result != Ordering::Equal {
61                 return result;
62             }
63
64             // `extern crate foo as bar;`
65             //                      ^^^ Comparing this.
66             match (a_name, b_name) {
67                 (Some(..), None) => Ordering::Greater,
68                 (None, Some(..)) => Ordering::Less,
69                 (None, None) => Ordering::Equal,
70                 (Some(..), Some(..)) => a.ident.name.as_str().cmp(&b.ident.name.as_str()),
71             }
72         }
73         _ => unreachable!(),
74     }
75 }
76
77 /// Rewrite a list of items with reordering. Every item in `items` must have
78 /// the same `ast::ItemKind`.
79 fn rewrite_reorderable_items(
80     context: &RewriteContext,
81     reorderable_items: &[&ast::Item],
82     shape: Shape,
83     span: Span,
84 ) -> Option<String> {
85     let items = itemize_list(
86         context.snippet_provider,
87         reorderable_items.iter(),
88         "",
89         ";",
90         |item| item.span().lo(),
91         |item| item.span().hi(),
92         |item| {
93             let attrs = filter_inline_attrs(&item.attrs, item.span());
94             let attrs_str = attrs.rewrite(context, shape)?;
95
96             let missed_span = if attrs.is_empty() {
97                 mk_sp(item.span.lo(), item.span.lo())
98             } else {
99                 mk_sp(attrs.last().unwrap().span.hi(), item.span.lo())
100             };
101
102             let item_str = match item.node {
103                 ast::ItemKind::Use(ref tree) => {
104                     rewrite_import(context, &item.vis, tree, &item.attrs, shape)?
105                 }
106                 ast::ItemKind::ExternCrate(..) => rewrite_extern_crate(context, item)?,
107                 ast::ItemKind::Mod(..) => rewrite_mod(item),
108                 _ => return None,
109             };
110
111             combine_strs_with_missing_comments(
112                 context,
113                 &attrs_str,
114                 &item_str,
115                 missed_span,
116                 shape,
117                 false,
118             )
119         },
120         span.lo(),
121         span.hi(),
122         false,
123     );
124     let mut item_pair_vec: Vec<_> = items.zip(reorderable_items.iter()).collect();
125     item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1));
126     let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect();
127
128     let fmt = ListFormatting {
129         tactic: DefinitiveListTactic::Vertical,
130         separator: "",
131         trailing_separator: SeparatorTactic::Never,
132         separator_place: SeparatorPlace::Back,
133         shape,
134         ends_with_newline: true,
135         preserve_newline: false,
136         config: context.config,
137     };
138
139     write_list(&item_vec, &fmt)
140 }
141
142 fn contains_macro_use_attr(item: &ast::Item) -> bool {
143     attr::contains_name(&filter_inline_attrs(&item.attrs, item.span()), "macro_use")
144 }
145
146 /// A simplified version of `ast::ItemKind`.
147 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
148 enum ReorderableItemKind {
149     ExternCrate,
150     Mod,
151     Use,
152     /// An item that cannot be reordered. Either has an unreorderable item kind
153     /// or an `macro_use` attribute.
154     Other,
155 }
156
157 impl ReorderableItemKind {
158     pub fn from(item: &ast::Item) -> Self {
159         match item.node {
160             _ if contains_macro_use_attr(item) => ReorderableItemKind::Other,
161             ast::ItemKind::ExternCrate(..) => ReorderableItemKind::ExternCrate,
162             ast::ItemKind::Mod(..) if is_mod_decl(item) => ReorderableItemKind::Mod,
163             ast::ItemKind::Use(..) => ReorderableItemKind::Use,
164             _ => ReorderableItemKind::Other,
165         }
166     }
167
168     pub fn is_same_item_kind(&self, item: &ast::Item) -> bool {
169         ReorderableItemKind::from(item) == *self
170     }
171
172     pub fn is_reorderable(&self, config: &Config) -> bool {
173         match *self {
174             ReorderableItemKind::ExternCrate => config.reorder_extern_crates(),
175             ReorderableItemKind::Mod => config.reorder_modules(),
176             ReorderableItemKind::Use => config.reorder_imports(),
177             ReorderableItemKind::Other => false,
178         }
179     }
180
181     pub fn in_group(&self, config: &Config) -> bool {
182         match *self {
183             ReorderableItemKind::ExternCrate => config.reorder_extern_crates_in_group(),
184             ReorderableItemKind::Mod => config.reorder_modules(),
185             ReorderableItemKind::Use => config.reorder_imports_in_group(),
186             ReorderableItemKind::Other => false,
187         }
188     }
189 }
190
191 impl<'b, 'a: 'b> FmtVisitor<'a> {
192     /// Format items with the same item kind and reorder them. If `in_group` is
193     /// `true`, then the items separated by an empty line will not be reordered
194     /// together.
195     fn walk_reorderable_items(
196         &mut self,
197         items: &[&ast::Item],
198         item_kind: ReorderableItemKind,
199         in_group: bool,
200     ) -> usize {
201         let mut last = self.codemap.lookup_line_range(items[0].span());
202         let item_length = items
203             .iter()
204             .take_while(|ppi| {
205                 item_kind.is_same_item_kind(&***ppi) && (!in_group || {
206                     let current = self.codemap.lookup_line_range(ppi.span());
207                     let in_same_group = current.lo < last.hi + 2;
208                     last = current;
209                     in_same_group
210                 })
211             })
212             .count();
213         let items = &items[..item_length];
214
215         let at_least_one_in_file_lines = items
216             .iter()
217             .any(|item| !out_of_file_lines_range!(self, item.span));
218
219         if at_least_one_in_file_lines && !items.is_empty() {
220             let lo = items.first().unwrap().span().lo();
221             let hi = items.last().unwrap().span().hi();
222             let span = mk_sp(lo, hi);
223             let rw = rewrite_reorderable_items(&self.get_context(), items, self.shape(), span);
224             self.push_rewrite(span, rw);
225         } else {
226             for item in items {
227                 self.push_rewrite(item.span, None);
228             }
229         }
230
231         item_length
232     }
233
234     /// Visit and format the given items. Items are reordered If they are
235     /// consecutive and reorderable.
236     pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) {
237         while !items.is_empty() {
238             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
239             // subsequent items that have the same item kind to be reordered within
240             // `walk_reorderable_items`. Otherwise, just format the next item for output.
241             let item_kind = ReorderableItemKind::from(items[0]);
242             if item_kind.is_reorderable(self.config) {
243                 let visited_items_num =
244                     self.walk_reorderable_items(items, item_kind, item_kind.in_group(self.config));
245                 let (_, rest) = items.split_at(visited_items_num);
246                 items = rest;
247             } else {
248                 // Reaching here means items were not reordered. There must be at least
249                 // one item left in `items`, so calling `unwrap()` here is safe.
250                 let (item, rest) = items.split_first().unwrap();
251                 self.visit_item(item);
252                 items = rest;
253             }
254         }
255     }
256 }
257
258 // Ordering of imports
259
260 // We order imports by translating to our own representation and then sorting.
261 // The Rust AST data structures are really bad for this. Rustfmt applies a bunch
262 // of normalisations to imports and since we want to sort based on the result
263 // of these (and to maintain idempotence) we must apply the same normalisations
264 // to the data structures for sorting.
265 //
266 // We sort `self` and `super` before other imports, then identifier imports,
267 // then glob imports, then lists of imports. We do not take aliases into account
268 // when ordering unless the imports are identical except for the alias (rare in
269 // practice).
270
271 // FIXME(#2531) - we should unify the comparison code here with the formatting
272 // code elsewhere since we are essentially string-ifying twice. Furthermore, by
273 // parsing to our own format on comparison, we repeat a lot of work when
274 // sorting.
275
276 // FIXME we do a lot of allocation to make our own representation.
277 #[derive(Debug, Clone, Eq, PartialEq)]
278 enum UseSegment {
279     Ident(String, Option<String>),
280     Slf(Option<String>),
281     Super(Option<String>),
282     Glob,
283     List(Vec<UseTree>),
284 }
285
286 #[derive(Debug, Clone, Eq, PartialEq)]
287 struct UseTree {
288     path: Vec<UseSegment>,
289 }
290
291 impl UseSegment {
292     // Clone a version of self with any top-level alias removed.
293     fn remove_alias(&self) -> UseSegment {
294         match *self {
295             UseSegment::Ident(ref s, _) => UseSegment::Ident(s.clone(), None),
296             UseSegment::Slf(_) => UseSegment::Slf(None),
297             UseSegment::Super(_) => UseSegment::Super(None),
298             _ => self.clone(),
299         }
300     }
301 }
302
303 impl UseTree {
304     fn from_ast(a: &ast::UseTree) -> UseTree {
305         let mut result = UseTree { path: vec![] };
306         for p in &a.prefix.segments {
307             result.path.push(UseSegment::Ident(
308                 (*p.identifier.name.as_str()).to_owned(),
309                 None,
310             ));
311         }
312         match a.kind {
313             UseTreeKind::Glob => {
314                 result.path.push(UseSegment::Glob);
315             }
316             UseTreeKind::Nested(ref list) => {
317                 result.path.push(UseSegment::List(
318                     list.iter().map(|t| Self::from_ast(&t.0)).collect(),
319                 ));
320             }
321             UseTreeKind::Simple(ref rename) => {
322                 let mut name = (*path_to_imported_ident(&a.prefix).name.as_str()).to_owned();
323                 let alias = if &name == &*rename.name.as_str() {
324                     None
325                 } else {
326                     Some((&*rename.name.as_str()).to_owned())
327                 };
328
329                 let segment = if &name == "self" {
330                     UseSegment::Slf(alias)
331                 } else if &name == "super" {
332                     UseSegment::Super(alias)
333                 } else {
334                     UseSegment::Ident(name, alias)
335                 };
336
337                 // `name` is already in result.
338                 result.path.pop();
339                 result.path.push(segment);
340             }
341         }
342         result
343     }
344
345     // Do the adjustments that rustfmt does elsewhere to use paths.
346     fn normalize(mut self) -> UseTree {
347         let mut last = self.path.pop().expect("Empty use tree?");
348         // Hack around borrow checker.
349         let mut normalize_sole_list = false;
350         let mut aliased_self = false;
351
352         // Normalise foo::self -> foo.
353         if let UseSegment::Slf(None) = last {
354             return self;
355         }
356
357         // Normalise foo::self as bar -> foo as bar.
358         if let UseSegment::Slf(_) = last {
359             match self.path.last() {
360                 None => {}
361                 Some(UseSegment::Ident(_, None)) => {
362                     aliased_self = true;
363                 }
364                 _ => unreachable!(),
365             }
366         }
367
368         if aliased_self {
369             match self.path.last() {
370                 Some(UseSegment::Ident(_, ref mut old_rename)) => {
371                     assert!(old_rename.is_none());
372                     if let UseSegment::Slf(Some(rename)) = last {
373                         *old_rename = Some(rename);
374                         return self;
375                     }
376                 }
377                 _ => unreachable!(),
378             }
379         }
380
381         // Normalise foo::{bar} -> foo::bar
382         if let UseSegment::List(ref list) = last {
383             if list.len() == 1 && list[0].path.len() == 1 {
384                 normalize_sole_list = true;
385             }
386         }
387
388         if normalize_sole_list {
389             match last {
390                 UseSegment::List(list) => {
391                     self.path.push(list[0].path[0].clone());
392                     return self.normalize();
393                 }
394                 _ => unreachable!(),
395             }
396         }
397
398         // Recursively normalize elements of a list use (including sorting the list).
399         if let UseSegment::List(list) = last {
400             let mut list: Vec<_> = list.into_iter().map(|ut| ut.normalize()).collect();
401             list.sort();
402             last = UseSegment::List(list);
403         }
404
405         self.path.push(last);
406         self
407     }
408 }
409
410 impl PartialOrd for UseSegment {
411     fn partial_cmp(&self, other: &UseSegment) -> Option<Ordering> {
412         Some(self.cmp(other))
413     }
414 }
415 impl PartialOrd for UseTree {
416     fn partial_cmp(&self, other: &UseTree) -> Option<Ordering> {
417         Some(self.cmp(other))
418     }
419 }
420 impl Ord for UseSegment {
421     fn cmp(&self, other: &UseSegment) -> Ordering {
422         use self::UseSegment::*;
423
424         match (self, other) {
425             (&Slf(ref a), &Slf(ref b)) | (&Super(ref a), &Super(ref b)) => a.cmp(b),
426             (&Glob, &Glob) => Ordering::Equal,
427             (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => {
428                 let ident_ord = ia.cmp(ib);
429                 if ident_ord != Ordering::Equal {
430                     return ident_ord;
431                 }
432                 if aa.is_none() && ab.is_some() {
433                     return Ordering::Less;
434                 }
435                 if aa.is_some() && ab.is_none() {
436                     return Ordering::Greater;
437                 }
438                 aa.cmp(ab)
439             }
440             (&List(ref a), &List(ref b)) => {
441                 for (a, b) in a.iter().zip(b.iter()) {
442                     let ord = a.cmp(b);
443                     if ord != Ordering::Equal {
444                         return ord;
445                     }
446                 }
447
448                 a.len().cmp(&b.len())
449             }
450             (&Slf(_), _) => Ordering::Less,
451             (_, &Slf(_)) => Ordering::Greater,
452             (&Super(_), _) => Ordering::Less,
453             (_, &Super(_)) => Ordering::Greater,
454             (&Ident(..), _) => Ordering::Less,
455             (_, &Ident(..)) => Ordering::Greater,
456             (&Glob, _) => Ordering::Less,
457             (_, &Glob) => Ordering::Greater,
458         }
459     }
460 }
461 impl Ord for UseTree {
462     fn cmp(&self, other: &UseTree) -> Ordering {
463         for (a, b) in self.path.iter().zip(other.path.iter()) {
464             let ord = a.cmp(b);
465             // The comparison without aliases is a hack to avoid situations like
466             // comparing `a::b` to `a as c` - where the latter should be ordered
467             // first since it is shorter.
468             if ord != Ordering::Equal && a.remove_alias().cmp(&b.remove_alias()) != Ordering::Equal
469             {
470                 return ord;
471             }
472         }
473
474         self.path.len().cmp(&other.path.len())
475     }
476 }
477
478 #[cfg(test)]
479 mod test {
480     use super::*;
481
482     // Parse the path part of an import. This parser is not robust and is only
483     // suitable for use in a test harness.
484     fn parse_use_tree(s: &str) -> UseTree {
485         use std::iter::Peekable;
486         use std::mem::swap;
487         use std::str::Chars;
488
489         struct Parser<'a> {
490             input: Peekable<Chars<'a>>,
491         }
492
493         impl<'a> Parser<'a> {
494             fn bump(&mut self) {
495                 self.input.next().unwrap();
496             }
497             fn eat(&mut self, c: char) {
498                 assert!(self.input.next().unwrap() == c);
499             }
500             fn push_segment(
501                 result: &mut Vec<UseSegment>,
502                 buf: &mut String,
503                 alias_buf: &mut Option<String>,
504             ) {
505                 if !buf.is_empty() {
506                     let mut alias = None;
507                     swap(alias_buf, &mut alias);
508                     if buf == "self" {
509                         result.push(UseSegment::Slf(alias));
510                         *buf = String::new();
511                         *alias_buf = None;
512                     } else if buf == "super" {
513                         result.push(UseSegment::Super(alias));
514                         *buf = String::new();
515                         *alias_buf = None;
516                     } else {
517                         let mut name = String::new();
518                         swap(buf, &mut name);
519                         result.push(UseSegment::Ident(name, alias));
520                     }
521                 }
522             }
523             fn parse_in_list(&mut self) -> UseTree {
524                 let mut result = vec![];
525                 let mut buf = String::new();
526                 let mut alias_buf = None;
527                 while let Some(&c) = self.input.peek() {
528                     match c {
529                         '{' => {
530                             assert!(buf.is_empty());
531                             self.bump();
532                             result.push(UseSegment::List(self.parse_list()));
533                             self.eat('}');
534                         }
535                         '*' => {
536                             assert!(buf.is_empty());
537                             self.bump();
538                             result.push(UseSegment::Glob);
539                         }
540                         ':' => {
541                             self.bump();
542                             self.eat(':');
543                             Self::push_segment(&mut result, &mut buf, &mut alias_buf);
544                         }
545                         '}' | ',' => {
546                             Self::push_segment(&mut result, &mut buf, &mut alias_buf);
547                             return UseTree { path: result };
548                         }
549                         ' ' => {
550                             self.bump();
551                             self.eat('a');
552                             self.eat('s');
553                             self.eat(' ');
554                             alias_buf = Some(String::new());
555                         }
556                         c => {
557                             self.bump();
558                             if let Some(ref mut buf) = alias_buf {
559                                 buf.push(c);
560                             } else {
561                                 buf.push(c);
562                             }
563                         }
564                     }
565                 }
566                 Self::push_segment(&mut result, &mut buf, &mut alias_buf);
567                 UseTree { path: result }
568             }
569
570             fn parse_list(&mut self) -> Vec<UseTree> {
571                 let mut result = vec![];
572                 loop {
573                     match self.input.peek().unwrap() {
574                         ',' | ' ' => self.bump(),
575                         '}' => {
576                             return result;
577                         }
578                         _ => result.push(self.parse_in_list()),
579                     }
580                 }
581             }
582         }
583
584         let mut parser = Parser {
585             input: s.chars().peekable(),
586         };
587         parser.parse_in_list()
588     }
589
590     #[test]
591     fn test_use_tree_normalize() {
592         assert_eq!(parse_use_tree("a::self").normalize(), parse_use_tree("a"));
593         assert_eq!(
594             parse_use_tree("a::self as foo").normalize(),
595             parse_use_tree("a as foo")
596         );
597         assert_eq!(parse_use_tree("a::{self}").normalize(), parse_use_tree("a"));
598         assert_eq!(parse_use_tree("a::{b}").normalize(), parse_use_tree("a::b"));
599         assert_eq!(
600             parse_use_tree("a::{b, c::self}").normalize(),
601             parse_use_tree("a::{b, c}")
602         );
603         assert_eq!(
604             parse_use_tree("a::{b as bar, c::self}").normalize(),
605             parse_use_tree("a::{b as bar, c}")
606         );
607     }
608
609     #[test]
610     fn test_use_tree_ord() {
611         assert!(parse_use_tree("a").normalize() < parse_use_tree("aa").normalize());
612         assert!(parse_use_tree("a").normalize() < parse_use_tree("a::a").normalize());
613         assert!(parse_use_tree("a").normalize() < parse_use_tree("*").normalize());
614         assert!(parse_use_tree("a").normalize() < parse_use_tree("{a, b}").normalize());
615         assert!(parse_use_tree("*").normalize() < parse_use_tree("{a, b}").normalize());
616
617         assert!(
618             parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, dddddddd}").normalize()
619                 < parse_use_tree("aaaaaaaaaaaaaaa::{bb, cc, ddddddddd}").normalize()
620         );
621         assert!(
622             parse_use_tree("serde::de::{Deserialize}").normalize()
623                 < parse_use_tree("serde_json").normalize()
624         );
625         assert!(parse_use_tree("a::b::c").normalize() < parse_use_tree("a::b::*").normalize());
626         assert!(
627             parse_use_tree("foo::{Bar, Baz}").normalize()
628                 < parse_use_tree("{Bar, Baz}").normalize()
629         );
630
631         assert!(
632             parse_use_tree("foo::{self as bar}").normalize()
633                 < parse_use_tree("foo::{qux as bar}").normalize()
634         );
635         assert!(
636             parse_use_tree("foo::{qux as bar}").normalize()
637                 < parse_use_tree("foo::{baz, qux as bar}").normalize()
638         );
639         assert!(
640             parse_use_tree("foo::{self as bar, baz}").normalize()
641                 < parse_use_tree("foo::{baz, qux as bar}").normalize()
642         );
643
644         assert!(parse_use_tree("Foo").normalize() < parse_use_tree("foo").normalize());
645         assert!(parse_use_tree("foo").normalize() < parse_use_tree("foo::Bar").normalize());
646
647         assert!(
648             parse_use_tree("std::cmp::{d, c, b, a}").normalize()
649                 < parse_use_tree("std::cmp::{b, e, g, f}").normalize()
650         );
651     }
652 }