summaryrefslogtreecommitdiffstats
path: root/src/tools/rust-analyzer/crates/ide-assists/src/handlers/move_const_to_impl.rs
blob: d848fce4be821b79585bd3854c1dff06ccb3bc41 (plain)
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use hir::{AsAssocItem, AssocItemContainer, HasCrate, HasSource};
use ide_db::{assists::AssistId, base_db::FileRange, defs::Definition, search::SearchScope};
use syntax::{
    ast::{self, edit::IndentLevel, edit_in_place::Indent, AstNode},
    SyntaxKind,
};

use crate::assist_context::{AssistContext, Assists};

// NOTE: Code may break if the self type implements a trait that has associated const with the same
// name, but it's pretty expensive to check that (`hir::Impl::all_for_type()`) and we assume that's
// pretty rare case.

// Assist: move_const_to_impl
//
// Move a local constant item in a method to impl's associated constant. All the references will be
// qualified with `Self::`.
//
// ```
// struct S;
// impl S {
//     fn foo() -> usize {
//         /// The answer.
//         const C$0: usize = 42;
//
//         C * C
//     }
// }
// ```
// ->
// ```
// struct S;
// impl S {
//     /// The answer.
//     const C: usize = 42;
//
//     fn foo() -> usize {
//         Self::C * Self::C
//     }
// }
// ```
pub(crate) fn move_const_to_impl(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let db = ctx.db();
    let const_: ast::Const = ctx.find_node_at_offset()?;
    // Don't show the assist when the cursor is at the const's body.
    if let Some(body) = const_.body() {
        if body.syntax().text_range().contains(ctx.offset()) {
            return None;
        }
    }

    let parent_fn = const_.syntax().ancestors().find_map(ast::Fn::cast)?;

    // NOTE: We can technically provide this assist for default methods in trait definitions, but
    // it's somewhat complex to handle it correctly when the const's name conflicts with
    // supertrait's item. We may want to consider implementing it in the future.
    let AssocItemContainer::Impl(impl_) = ctx.sema.to_def(&parent_fn)?.as_assoc_item(db)?.container(db) else { return None; };
    if impl_.trait_(db).is_some() {
        return None;
    }

    let def = ctx.sema.to_def(&const_)?;
    let name = def.name(db)?;
    let items = impl_.source(db)?.value.assoc_item_list()?;

    let ty = impl_.self_ty(db);
    // If there exists another associated item with the same name, skip the assist.
    if ty
        .iterate_assoc_items(db, ty.krate(db), |assoc| {
            // Type aliases wouldn't conflict due to different namespaces, but we're only checking
            // the items in inherent impls, so we assume `assoc` is never type alias for the sake
            // of brevity (inherent associated types exist in nightly Rust, but it's *very*
            // unstable and we don't support them either).
            assoc.name(db).filter(|it| it == &name)
        })
        .is_some()
    {
        return None;
    }

    let usages =
        Definition::Const(def).usages(&ctx.sema).in_scope(SearchScope::file_range(FileRange {
            file_id: ctx.file_id(),
            range: parent_fn.syntax().text_range(),
        }));

    acc.add(
        AssistId("move_const_to_impl", crate::AssistKind::RefactorRewrite),
        "Move const to impl block",
        const_.syntax().text_range(),
        |builder| {
            let range_to_delete = match const_.syntax().next_sibling_or_token() {
                Some(s) if matches!(s.kind(), SyntaxKind::WHITESPACE) => {
                    // Remove following whitespaces too.
                    const_.syntax().text_range().cover(s.text_range())
                }
                _ => const_.syntax().text_range(),
            };
            builder.delete(range_to_delete);

            let const_ref = format!("Self::{name}");
            for range in usages.all().file_ranges().map(|it| it.range) {
                builder.replace(range, const_ref.clone());
            }

            // Heuristically inserting the extracted const after the consecutive existing consts
            // from the beginning of assoc items. We assume there are no inherent assoc type as
            // above.
            let last_const =
                items.assoc_items().take_while(|it| matches!(it, ast::AssocItem::Const(_))).last();
            let insert_offset = match &last_const {
                Some(it) => it.syntax().text_range().end(),
                None => match items.l_curly_token() {
                    Some(l_curly) => l_curly.text_range().end(),
                    // Not sure if this branch is ever reachable, but it wouldn't hurt to have a
                    // fallback.
                    None => items.syntax().text_range().start(),
                },
            };

            // If the moved const will be the first item of the impl, add a new line after that.
            //
            // We're assuming the code is formatted according to Rust's standard style guidelines
            // (i.e. no empty lines between impl's `{` token and its first assoc item).
            let fixup = if last_const.is_none() { "\n" } else { "" };
            let indent = IndentLevel::from_node(parent_fn.syntax());

            let const_ = const_.clone_for_update();
            const_.reindent_to(indent);
            builder.insert(insert_offset, format!("\n{indent}{const_}{fixup}"));
        },
    )
}

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

    use super::*;

    #[test]
    fn not_applicable_to_top_level_const() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
const C$0: () = ();
"#,
        );
    }

    #[test]
    fn not_applicable_to_free_fn() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
fn f() {
    const C$0: () = ();
}
"#,
        );
    }

    #[test]
    fn not_applicable_when_at_const_body() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() {
        const C: () = ($0);
    }
}
            "#,
        );
    }

    #[test]
    fn not_applicable_when_inside_const_body_block() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() {
        const C: () = {
            ($0)
        };
    }
}
            "#,
        );
    }

    #[test]
    fn not_applicable_to_trait_impl_fn() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
trait Trait {
    fn f();
}
impl Trait for () {
    fn f() {
        const C$0: () = ();
    }
}
"#,
        );
    }

    #[test]
    fn not_applicable_to_non_assoc_fn_inside_impl() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() {
        fn g() {
            const C$0: () = ();
        }
    }
}
"#,
        );
    }

    #[test]
    fn not_applicable_when_const_with_same_name_exists() {
        check_assist_not_applicable(
            move_const_to_impl,
            r#"
struct S;
impl S {
    const C: usize = 42;
    fn f() {
        const C$0: () = ();
    }
"#,
        );

        check_assist_not_applicable(
            move_const_to_impl,
            r#"
struct S;
impl S {
    const C: usize = 42;
}
impl S {
    fn f() {
        const C$0: () = ();
    }
"#,
        );
    }

    #[test]
    fn move_const_simple_body() {
        check_assist(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() -> usize {
        /// doc comment
        const C$0: usize = 42;

        C * C
    }
}
"#,
            r#"
struct S;
impl S {
    /// doc comment
    const C: usize = 42;

    fn f() -> usize {
        Self::C * Self::C
    }
}
"#,
        );
    }

    #[test]
    fn move_const_simple_body_existing_const() {
        check_assist(
            move_const_to_impl,
            r#"
struct S;
impl S {
    const X: () = ();
    const Y: () = ();

    fn f() -> usize {
        /// doc comment
        const C$0: usize = 42;

        C * C
    }
}
"#,
            r#"
struct S;
impl S {
    const X: () = ();
    const Y: () = ();
    /// doc comment
    const C: usize = 42;

    fn f() -> usize {
        Self::C * Self::C
    }
}
"#,
        );
    }

    #[test]
    fn move_const_block_body() {
        check_assist(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() -> usize {
        /// doc comment
        const C$0: usize = {
            let a = 3;
            let b = 4;
            a * b
        };

        C * C
    }
}
"#,
            r#"
struct S;
impl S {
    /// doc comment
    const C: usize = {
        let a = 3;
        let b = 4;
        a * b
    };

    fn f() -> usize {
        Self::C * Self::C
    }
}
"#,
        );
    }

    #[test]
    fn correct_indent_when_nested() {
        check_assist(
            move_const_to_impl,
            r#"
fn main() {
    struct S;
    impl S {
        fn f() -> usize {
            /// doc comment
            const C$0: usize = 42;

            C * C
        }
    }
}
"#,
            r#"
fn main() {
    struct S;
    impl S {
        /// doc comment
        const C: usize = 42;

        fn f() -> usize {
            Self::C * Self::C
        }
    }
}
"#,
        )
    }

    #[test]
    fn move_const_in_nested_scope_with_same_name_in_other_scope() {
        check_assist(
            move_const_to_impl,
            r#"
struct S;
impl S {
    fn f() -> usize {
        const C: &str = "outer";

        let n = {
            /// doc comment
            const C$0: usize = 42;

            let m = {
                const C: &str = "inner";
                C.len()
            };

            C * m
        };

        n + C.len()
    }
}
"#,
            r#"
struct S;
impl S {
    /// doc comment
    const C: usize = 42;

    fn f() -> usize {
        const C: &str = "outer";

        let n = {
            let m = {
                const C: &str = "inner";
                C.len()
            };

            Self::C * m
        };

        n + C.len()
    }
}
"#,
        );
    }
}