ide_assists/handlers/
reorder_fields.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use either::Either;
use ide_db::FxHashMap;
use itertools::Itertools;
use syntax::{ast, syntax_editor::SyntaxEditor, AstNode, SmolStr, SyntaxElement, ToSmolStr};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: reorder_fields
//
// Reorder the fields of record literals and record patterns in the same order as in
// the definition.
//
// ```
// struct Foo {foo: i32, bar: i32};
// const test: Foo = $0Foo {bar: 0, foo: 1}
// ```
// ->
// ```
// struct Foo {foo: i32, bar: i32};
// const test: Foo = Foo {foo: 1, bar: 0}
// ```
pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let path = ctx.find_node_at_offset::<ast::Path>()?;
    let record =
        path.syntax().parent().and_then(<Either<ast::RecordExpr, ast::RecordPat>>::cast)?;

    let parent_node = match ctx.covering_element() {
        SyntaxElement::Node(n) => n,
        SyntaxElement::Token(t) => t.parent()?,
    };

    let ranks = compute_fields_ranks(&path, ctx)?;
    let get_rank_of_field = |of: Option<SmolStr>| {
        *ranks.get(of.unwrap_or_default().trim_start_matches("r#")).unwrap_or(&usize::MAX)
    };

    let field_list = match &record {
        Either::Left(it) => Either::Left(it.record_expr_field_list()?),
        Either::Right(it) => Either::Right(it.record_pat_field_list()?),
    };
    let fields = match field_list {
        Either::Left(it) => Either::Left((
            it.fields()
                .sorted_unstable_by_key(|field| {
                    get_rank_of_field(field.field_name().map(|it| it.to_smolstr()))
                })
                .collect::<Vec<_>>(),
            it,
        )),
        Either::Right(it) => Either::Right((
            it.fields()
                .sorted_unstable_by_key(|field| {
                    get_rank_of_field(field.field_name().map(|it| it.to_smolstr()))
                })
                .collect::<Vec<_>>(),
            it,
        )),
    };

    let is_sorted = fields.as_ref().either(
        |(sorted, field_list)| field_list.fields().zip(sorted).all(|(a, b)| a == *b),
        |(sorted, field_list)| field_list.fields().zip(sorted).all(|(a, b)| a == *b),
    );
    if is_sorted {
        cov_mark::hit!(reorder_sorted_fields);
        return None;
    }
    let target = record.as_ref().either(AstNode::syntax, AstNode::syntax).text_range();
    acc.add(
        AssistId("reorder_fields", AssistKind::RefactorRewrite),
        "Reorder record fields",
        target,
        |builder| {
            let mut editor = builder.make_editor(&parent_node);

            match fields {
                Either::Left((sorted, field_list)) => {
                    replace(&mut editor, field_list.fields(), sorted)
                }
                Either::Right((sorted, field_list)) => {
                    replace(&mut editor, field_list.fields(), sorted)
                }
            }

            builder.add_file_edits(ctx.file_id(), editor);
        },
    )
}

fn replace<T: AstNode + PartialEq>(
    editor: &mut SyntaxEditor,
    fields: impl Iterator<Item = T>,
    sorted_fields: impl IntoIterator<Item = T>,
) {
    fields
        .zip(sorted_fields)
        .for_each(|(field, sorted_field)| editor.replace(field.syntax(), sorted_field.syntax()));
}

fn compute_fields_ranks(
    path: &ast::Path,
    ctx: &AssistContext<'_>,
) -> Option<FxHashMap<String, usize>> {
    let strukt = match ctx.sema.resolve_path(path) {
        Some(hir::PathResolution::Def(hir::ModuleDef::Adt(hir::Adt::Struct(it)))) => it,
        _ => return None,
    };

    let res = strukt
        .fields(ctx.db())
        .into_iter()
        .enumerate()
        .map(|(idx, field)| (field.name(ctx.db()).unescaped().display(ctx.db()).to_string(), idx))
        .collect();

    Some(res)
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn reorder_sorted_fields() {
        cov_mark::check!(reorder_sorted_fields);
        check_assist_not_applicable(
            reorder_fields,
            r#"
struct Foo { foo: i32, bar: i32 }
const test: Foo = $0Foo { foo: 0, bar: 0 };
"#,
        )
    }

    #[test]
    fn trivial_empty_fields() {
        check_assist_not_applicable(
            reorder_fields,
            r#"
struct Foo {}
const test: Foo = $0Foo {};
"#,
        )
    }

    #[test]
    fn reorder_struct_fields() {
        check_assist(
            reorder_fields,
            r#"
struct Foo { foo: i32, bar: i32 }
const test: Foo = $0Foo { bar: 0, foo: 1 };
"#,
            r#"
struct Foo { foo: i32, bar: i32 }
const test: Foo = Foo { foo: 1, bar: 0 };
"#,
        )
    }
    #[test]
    fn reorder_struct_pattern() {
        check_assist(
            reorder_fields,
            r#"
struct Foo { foo: i64, bar: i64, baz: i64 }

fn f(f: Foo) -> {
    match f {
        $0Foo { baz: 0, ref mut bar, .. } => (),
        _ => ()
    }
}
"#,
            r#"
struct Foo { foo: i64, bar: i64, baz: i64 }

fn f(f: Foo) -> {
    match f {
        Foo { ref mut bar, baz: 0, .. } => (),
        _ => ()
    }
}
"#,
        )
    }

    #[test]
    fn reorder_with_extra_field() {
        check_assist(
            reorder_fields,
            r#"
struct Foo { foo: String, bar: String }

impl Foo {
    fn new() -> Foo {
        let foo = String::new();
        $0Foo {
            bar: foo.clone(),
            extra: "Extra field",
            foo,
        }
    }
}
"#,
            r#"
struct Foo { foo: String, bar: String }

impl Foo {
    fn new() -> Foo {
        let foo = String::new();
        Foo {
            foo,
            bar: foo.clone(),
            extra: "Extra field",
        }
    }
}
"#,
        )
    }
}