1
1
use either:: Either ;
2
2
use ide_db:: FxHashMap ;
3
3
use itertools:: Itertools ;
4
- use syntax:: { ast, ted , AstNode , SmolStr , ToSmolStr } ;
4
+ use syntax:: { ast, syntax_editor :: SyntaxEditor , AstNode , SmolStr , SyntaxElement , ToSmolStr } ;
5
5
6
6
use crate :: { AssistContext , AssistId , AssistKind , Assists } ;
7
7
@@ -24,6 +24,11 @@ pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
24
24
let record =
25
25
path. syntax ( ) . parent ( ) . and_then ( <Either < ast:: RecordExpr , ast:: RecordPat > >:: cast) ?;
26
26
27
+ let parent_node = match ctx. covering_element ( ) {
28
+ SyntaxElement :: Node ( n) => n,
29
+ SyntaxElement :: Token ( t) => t. parent ( ) ?,
30
+ } ;
31
+
27
32
let ranks = compute_fields_ranks ( & path, ctx) ?;
28
33
let get_rank_of_field = |of : Option < SmolStr > | {
29
34
* ranks. get ( of. unwrap_or_default ( ) . trim_start_matches ( "r#" ) ) . unwrap_or ( & usize:: MAX )
@@ -65,23 +70,31 @@ pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
65
70
AssistId ( "reorder_fields" , AssistKind :: RefactorRewrite ) ,
66
71
"Reorder record fields" ,
67
72
target,
68
- |builder| match fields {
69
- Either :: Left ( ( sorted, field_list) ) => {
70
- replace ( builder. make_mut ( field_list) . fields ( ) , sorted)
71
- }
72
- Either :: Right ( ( sorted, field_list) ) => {
73
- replace ( builder. make_mut ( field_list) . fields ( ) , sorted)
73
+ |builder| {
74
+ let mut editor = builder. make_editor ( & parent_node) ;
75
+
76
+ match fields {
77
+ Either :: Left ( ( sorted, field_list) ) => {
78
+ replace ( & mut editor, field_list. fields ( ) , sorted)
79
+ }
80
+ Either :: Right ( ( sorted, field_list) ) => {
81
+ replace ( & mut editor, field_list. fields ( ) , sorted)
82
+ }
74
83
}
84
+
85
+ builder. add_file_edits ( ctx. file_id ( ) , editor) ;
75
86
} ,
76
87
)
77
88
}
78
89
79
90
fn replace < T : AstNode + PartialEq > (
91
+ editor : & mut SyntaxEditor ,
80
92
fields : impl Iterator < Item = T > ,
81
93
sorted_fields : impl IntoIterator < Item = T > ,
82
94
) {
83
95
fields. zip ( sorted_fields) . for_each ( |( field, sorted_field) | {
84
- ted:: replace ( field. syntax ( ) , sorted_field. syntax ( ) . clone_for_update ( ) )
96
+ // FIXME: remove `clone_for_update` when `SyntaxEditor` handles it for us
97
+ editor. replace ( field. syntax ( ) , sorted_field. syntax ( ) . clone_for_update ( ) )
85
98
} ) ;
86
99
}
87
100
0 commit comments