]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs
Merge #9258
[rust.git] / crates / ide_assists / src / handlers / replace_derive_with_manual_impl.rs
1 use hir::ModuleDef;
2 use ide_db::helpers::{import_assets::NameToImport, mod_path_to_ast};
3 use ide_db::items_locator;
4 use itertools::Itertools;
5 use syntax::{
6     ast::{self, make, AstNode, NameOwner},
7     SyntaxKind::{IDENT, WHITESPACE},
8 };
9
10 use crate::{
11     assist_context::{AssistBuilder, AssistContext, Assists},
12     utils::{
13         add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
14         render_snippet, Cursor, DefaultMethods,
15     },
16     AssistId, AssistKind,
17 };
18
19 // Assist: replace_derive_with_manual_impl
20 //
21 // Converts a `derive` impl into a manual one.
22 //
23 // ```
24 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
25 // #[derive(Deb$0ug, Display)]
26 // struct S;
27 // ```
28 // ->
29 // ```
30 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
31 // #[derive(Display)]
32 // struct S;
33 //
34 // impl Debug for S {
35 //     fn fmt(&self, f: &mut Formatter) -> Result<()> {
36 //         ${0:todo!()}
37 //     }
38 // }
39 // ```
40 pub(crate) fn replace_derive_with_manual_impl(
41     acc: &mut Assists,
42     ctx: &AssistContext,
43 ) -> Option<()> {
44     let attr = ctx.find_node_at_offset::<ast::Attr>()?;
45     let (name, args) = attr.as_simple_call()?;
46     if name != "derive" {
47         return None;
48     }
49
50     if !args.syntax().text_range().contains(ctx.offset()) {
51         cov_mark::hit!(outside_of_attr_args);
52         return None;
53     }
54
55     let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
56     let trait_name = trait_token.text();
57
58     let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
59
60     let current_module = ctx.sema.scope(adt.syntax()).module()?;
61     let current_crate = current_module.krate();
62
63     let found_traits = items_locator::items_with_name(
64         &ctx.sema,
65         current_crate,
66         NameToImport::Exact(trait_name.to_string()),
67         items_locator::AssocItemSearch::Exclude,
68         Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT),
69     )
70     .filter_map(|item| match ModuleDef::from(item.as_module_def_id()?) {
71         ModuleDef::Trait(trait_) => Some(trait_),
72         _ => None,
73     })
74     .flat_map(|trait_| {
75         current_module
76             .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
77             .as_ref()
78             .map(mod_path_to_ast)
79             .zip(Some(trait_))
80     });
81
82     let mut no_traits_found = true;
83     for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
84         add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
85     }
86     if no_traits_found {
87         let trait_path = make::ext::ident_path(trait_name);
88         add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
89     }
90     Some(())
91 }
92
93 fn add_assist(
94     acc: &mut Assists,
95     ctx: &AssistContext,
96     attr: &ast::Attr,
97     input: &ast::TokenTree,
98     trait_path: &ast::Path,
99     trait_: Option<hir::Trait>,
100     adt: &ast::Adt,
101 ) -> Option<()> {
102     let target = attr.syntax().text_range();
103     let annotated_name = adt.name()?;
104     let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
105     let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
106
107     acc.add(
108         AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
109         label,
110         target,
111         |builder| {
112             let insert_pos = adt.syntax().text_range().end();
113             let impl_def_with_items =
114                 impl_def_from_trait(&ctx.sema, &annotated_name, trait_, trait_path);
115             update_attribute(builder, input, &trait_name, attr);
116             let trait_path = format!("{}", trait_path);
117             match (ctx.config.snippet_cap, impl_def_with_items) {
118                 (None, _) => {
119                     builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
120                 }
121                 (Some(cap), None) => builder.insert_snippet(
122                     cap,
123                     insert_pos,
124                     generate_trait_impl_text(adt, &trait_path, "    $0"),
125                 ),
126                 (Some(cap), Some((impl_def, first_assoc_item))) => {
127                     let mut cursor = Cursor::Before(first_assoc_item.syntax());
128                     let placeholder;
129                     if let ast::AssocItem::Fn(ref func) = first_assoc_item {
130                         if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
131                         {
132                             if m.syntax().text() == "todo!()" {
133                                 placeholder = m;
134                                 cursor = Cursor::Replace(placeholder.syntax());
135                             }
136                         }
137                     }
138
139                     builder.insert_snippet(
140                         cap,
141                         insert_pos,
142                         format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
143                     )
144                 }
145             };
146         },
147     )
148 }
149
150 fn impl_def_from_trait(
151     sema: &hir::Semantics<ide_db::RootDatabase>,
152     annotated_name: &ast::Name,
153     trait_: Option<hir::Trait>,
154     trait_path: &ast::Path,
155 ) -> Option<(ast::Impl, ast::AssocItem)> {
156     let trait_ = trait_?;
157     let target_scope = sema.scope(annotated_name.syntax());
158     let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
159     if trait_items.is_empty() {
160         return None;
161     }
162     let impl_def =
163         make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
164     let (impl_def, first_assoc_item) =
165         add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
166     Some((impl_def, first_assoc_item))
167 }
168
169 fn update_attribute(
170     builder: &mut AssistBuilder,
171     input: &ast::TokenTree,
172     trait_name: &ast::NameRef,
173     attr: &ast::Attr,
174 ) {
175     let trait_name = trait_name.text();
176     let new_attr_input = input
177         .syntax()
178         .descendants_with_tokens()
179         .filter(|t| t.kind() == IDENT)
180         .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
181         .filter(|t| t != &trait_name)
182         .collect::<Vec<_>>();
183     let has_more_derives = !new_attr_input.is_empty();
184
185     if has_more_derives {
186         let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
187         builder.replace(input.syntax().text_range(), new_attr_input);
188     } else {
189         let attr_range = attr.syntax().text_range();
190         builder.delete(attr_range);
191
192         if let Some(line_break_range) = attr
193             .syntax()
194             .next_sibling_or_token()
195             .filter(|t| t.kind() == WHITESPACE)
196             .map(|t| t.text_range())
197         {
198             builder.delete(line_break_range);
199         }
200     }
201 }
202
203 #[cfg(test)]
204 mod tests {
205     use crate::tests::{check_assist, check_assist_not_applicable};
206
207     use super::*;
208
209     #[test]
210     fn add_custom_impl_debug() {
211         check_assist(
212             replace_derive_with_manual_impl,
213             r#"
214 mod fmt {
215     pub struct Error;
216     pub type Result = Result<(), Error>;
217     pub struct Formatter<'a>;
218     pub trait Debug {
219         fn fmt(&self, f: &mut Formatter<'_>) -> Result;
220     }
221 }
222
223 #[derive(Debu$0g)]
224 struct Foo {
225     bar: String,
226 }
227 "#,
228             r#"
229 mod fmt {
230     pub struct Error;
231     pub type Result = Result<(), Error>;
232     pub struct Formatter<'a>;
233     pub trait Debug {
234         fn fmt(&self, f: &mut Formatter<'_>) -> Result;
235     }
236 }
237
238 struct Foo {
239     bar: String,
240 }
241
242 impl fmt::Debug for Foo {
243     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244         ${0:todo!()}
245     }
246 }
247 "#,
248         )
249     }
250     #[test]
251     fn add_custom_impl_all() {
252         check_assist(
253             replace_derive_with_manual_impl,
254             r#"
255 mod foo {
256     pub trait Bar {
257         type Qux;
258         const Baz: usize = 42;
259         const Fez: usize;
260         fn foo();
261         fn bar() {}
262     }
263 }
264
265 #[derive($0Bar)]
266 struct Foo {
267     bar: String,
268 }
269 "#,
270             r#"
271 mod foo {
272     pub trait Bar {
273         type Qux;
274         const Baz: usize = 42;
275         const Fez: usize;
276         fn foo();
277         fn bar() {}
278     }
279 }
280
281 struct Foo {
282     bar: String,
283 }
284
285 impl foo::Bar for Foo {
286     $0type Qux;
287
288     const Baz: usize = 42;
289
290     const Fez: usize;
291
292     fn foo() {
293         todo!()
294     }
295 }
296 "#,
297         )
298     }
299     #[test]
300     fn add_custom_impl_for_unique_input() {
301         check_assist(
302             replace_derive_with_manual_impl,
303             r#"
304 #[derive(Debu$0g)]
305 struct Foo {
306     bar: String,
307 }
308             "#,
309             r#"
310 struct Foo {
311     bar: String,
312 }
313
314 impl Debug for Foo {
315     $0
316 }
317             "#,
318         )
319     }
320
321     #[test]
322     fn add_custom_impl_for_with_visibility_modifier() {
323         check_assist(
324             replace_derive_with_manual_impl,
325             r#"
326 #[derive(Debug$0)]
327 pub struct Foo {
328     bar: String,
329 }
330             "#,
331             r#"
332 pub struct Foo {
333     bar: String,
334 }
335
336 impl Debug for Foo {
337     $0
338 }
339             "#,
340         )
341     }
342
343     #[test]
344     fn add_custom_impl_when_multiple_inputs() {
345         check_assist(
346             replace_derive_with_manual_impl,
347             r#"
348 #[derive(Display, Debug$0, Serialize)]
349 struct Foo {}
350             "#,
351             r#"
352 #[derive(Display, Serialize)]
353 struct Foo {}
354
355 impl Debug for Foo {
356     $0
357 }
358             "#,
359         )
360     }
361
362     #[test]
363     fn test_ignore_derive_macro_without_input() {
364         check_assist_not_applicable(
365             replace_derive_with_manual_impl,
366             r#"
367 #[derive($0)]
368 struct Foo {}
369             "#,
370         )
371     }
372
373     #[test]
374     fn test_ignore_if_cursor_on_param() {
375         check_assist_not_applicable(
376             replace_derive_with_manual_impl,
377             r#"
378 #[derive$0(Debug)]
379 struct Foo {}
380             "#,
381         );
382
383         check_assist_not_applicable(
384             replace_derive_with_manual_impl,
385             r#"
386 #[derive(Debug)$0]
387 struct Foo {}
388             "#,
389         )
390     }
391
392     #[test]
393     fn test_ignore_if_not_derive() {
394         check_assist_not_applicable(
395             replace_derive_with_manual_impl,
396             r#"
397 #[allow(non_camel_$0case_types)]
398 struct Foo {}
399             "#,
400         )
401     }
402
403     #[test]
404     fn works_at_start_of_file() {
405         cov_mark::check!(outside_of_attr_args);
406         check_assist_not_applicable(
407             replace_derive_with_manual_impl,
408             r#"
409 $0#[derive(Debug)]
410 struct S;
411             "#,
412         );
413     }
414 }