1
1
// Formatting top-level items - functions, structs, enums, traits, impls.
2
2
3
- use std:: borrow:: Cow ;
4
- use std:: cmp:: { Ordering , max, min} ;
5
-
3
+ use itertools:: Itertools ;
6
4
use regex:: Regex ;
7
- use rustc_ast:: visit;
5
+ use rustc_ast:: { AttrVec , visit} ;
8
6
use rustc_ast:: { ast, ptr} ;
9
7
use rustc_span:: { BytePos , DUMMY_SP , Span , symbol} ;
8
+ use std:: borrow:: Cow ;
9
+ use std:: cmp:: { Ordering , max, min} ;
10
10
11
11
use crate :: attr:: filter_inline_attrs;
12
12
use crate :: comment:: {
@@ -536,6 +536,7 @@ impl<'a> FmtVisitor<'a> {
536
536
enum_def : & ast:: EnumDef ,
537
537
generics : & ast:: Generics ,
538
538
span : Span ,
539
+ attrs : & AttrVec ,
539
540
) {
540
541
let enum_header =
541
542
format_header ( & self . get_context ( ) , "enum " , ident, vis, self . block_indent ) ;
@@ -563,7 +564,7 @@ impl<'a> FmtVisitor<'a> {
563
564
564
565
self . last_pos = body_start;
565
566
566
- match self . format_variant_list ( enum_def, body_start, span. hi ( ) ) {
567
+ match self . format_variant_list ( enum_def, body_start, span. hi ( ) , attrs ) {
567
568
Some ( ref s) if enum_def. variants . is_empty ( ) => self . push_str ( s) ,
568
569
rw => {
569
570
self . push_rewrite ( mk_sp ( body_start, span. hi ( ) ) , rw) ;
@@ -578,6 +579,7 @@ impl<'a> FmtVisitor<'a> {
578
579
enum_def : & ast:: EnumDef ,
579
580
body_lo : BytePos ,
580
581
body_hi : BytePos ,
582
+ attrs : & AttrVec ,
581
583
) -> Option < String > {
582
584
if enum_def. variants . is_empty ( ) {
583
585
let mut buffer = String :: with_capacity ( 128 ) ;
@@ -615,7 +617,7 @@ impl<'a> FmtVisitor<'a> {
615
617
. unwrap_or ( & 0 ) ;
616
618
617
619
let itemize_list_with = |one_line_width : usize | {
618
- itemize_list (
620
+ let iter = itemize_list (
619
621
self . snippet_provider ,
620
622
enum_def. variants . iter ( ) ,
621
623
"}" ,
@@ -635,8 +637,16 @@ impl<'a> FmtVisitor<'a> {
635
637
body_lo,
636
638
body_hi,
637
639
false ,
638
- )
639
- . collect ( )
640
+ ) ;
641
+ if contains_sort ( attrs) {
642
+ // sort the items by their name as this enum has the rustfmt::sort attr
643
+ iter. enumerate ( )
644
+ . sorted_by_key ( |& ( i, _) | enum_def. variants [ i] . ident . name . as_str ( ) )
645
+ . map ( |( _, item) | item)
646
+ . collect ( )
647
+ } else {
648
+ iter. collect ( )
649
+ }
640
650
} ;
641
651
let mut items: Vec < _ > = itemize_list_with ( self . config . struct_variant_width ( ) ) ;
642
652
0 commit comments