]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs
Merge #9735
[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::ast::edit::AstNodeEdit;
6 use syntax::ted;
7 use syntax::{
8     ast::{self, make, AstNode, NameOwner},
9     SyntaxKind::{IDENT, WHITESPACE},
10 };
11
12 use crate::{
13     assist_context::{AssistBuilder, AssistContext, Assists},
14     utils::{
15         add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
16         render_snippet, Cursor, DefaultMethods,
17     },
18     AssistId, AssistKind,
19 };
20
21 // Assist: replace_derive_with_manual_impl
22 //
23 // Converts a `derive` impl into a manual one.
24 //
25 // ```
26 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
27 // #[derive(Deb$0ug, Display)]
28 // struct S;
29 // ```
30 // ->
31 // ```
32 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
33 // #[derive(Display)]
34 // struct S;
35 //
36 // impl Debug for S {
37 //     $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
38 //         f.debug_struct("S").finish()
39 //     }
40 // }
41 // ```
42 pub(crate) fn replace_derive_with_manual_impl(
43     acc: &mut Assists,
44     ctx: &AssistContext,
45 ) -> Option<()> {
46     let attr = ctx.find_node_at_offset::<ast::Attr>()?;
47     let (name, args) = attr.as_simple_call()?;
48     if name != "derive" {
49         return None;
50     }
51
52     if !args.syntax().text_range().contains(ctx.offset()) {
53         cov_mark::hit!(outside_of_attr_args);
54         return None;
55     }
56
57     let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
58     let trait_name = trait_token.text();
59
60     let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
61
62     let current_module = ctx.sema.scope(adt.syntax()).module()?;
63     let current_crate = current_module.krate();
64
65     let found_traits = items_locator::items_with_name(
66         &ctx.sema,
67         current_crate,
68         NameToImport::Exact(trait_name.to_string()),
69         items_locator::AssocItemSearch::Exclude,
70         Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
71     )
72     .filter_map(|item| match item.as_module_def()? {
73         ModuleDef::Trait(trait_) => Some(trait_),
74         _ => None,
75     })
76     .flat_map(|trait_| {
77         current_module
78             .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
79             .as_ref()
80             .map(mod_path_to_ast)
81             .zip(Some(trait_))
82     });
83
84     let mut no_traits_found = true;
85     for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
86         add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
87     }
88     if no_traits_found {
89         let trait_path = make::ext::ident_path(trait_name);
90         add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
91     }
92     Some(())
93 }
94
95 fn add_assist(
96     acc: &mut Assists,
97     ctx: &AssistContext,
98     attr: &ast::Attr,
99     input: &ast::TokenTree,
100     trait_path: &ast::Path,
101     trait_: Option<hir::Trait>,
102     adt: &ast::Adt,
103 ) -> Option<()> {
104     let target = attr.syntax().text_range();
105     let annotated_name = adt.name()?;
106     let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
107     let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
108
109     acc.add(
110         AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
111         label,
112         target,
113         |builder| {
114             let insert_pos = adt.syntax().text_range().end();
115             let impl_def_with_items =
116                 impl_def_from_trait(&ctx.sema, adt, &annotated_name, trait_, trait_path);
117             update_attribute(builder, input, &trait_name, attr);
118             let trait_path = format!("{}", trait_path);
119             match (ctx.config.snippet_cap, impl_def_with_items) {
120                 (None, _) => {
121                     builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
122                 }
123                 (Some(cap), None) => builder.insert_snippet(
124                     cap,
125                     insert_pos,
126                     generate_trait_impl_text(adt, &trait_path, "    $0"),
127                 ),
128                 (Some(cap), Some((impl_def, first_assoc_item))) => {
129                     let mut cursor = Cursor::Before(first_assoc_item.syntax());
130                     let placeholder;
131                     if let ast::AssocItem::Fn(ref func) = first_assoc_item {
132                         if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
133                         {
134                             if m.syntax().text() == "todo!()" {
135                                 placeholder = m;
136                                 cursor = Cursor::Replace(placeholder.syntax());
137                             }
138                         }
139                     }
140
141                     builder.insert_snippet(
142                         cap,
143                         insert_pos,
144                         format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
145                     )
146                 }
147             };
148         },
149     )
150 }
151
152 fn impl_def_from_trait(
153     sema: &hir::Semantics<ide_db::RootDatabase>,
154     adt: &ast::Adt,
155     annotated_name: &ast::Name,
156     trait_: Option<hir::Trait>,
157     trait_path: &ast::Path,
158 ) -> Option<(ast::Impl, ast::AssocItem)> {
159     let trait_ = trait_?;
160     let target_scope = sema.scope(annotated_name.syntax());
161     let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
162     if trait_items.is_empty() {
163         return None;
164     }
165     let impl_def =
166         make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
167     let (impl_def, first_assoc_item) =
168         add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
169
170     // Generate a default `impl` function body for the derived trait.
171     if let ast::AssocItem::Fn(ref func) = first_assoc_item {
172         let _ = gen_default_impl(func, trait_path, adt, annotated_name);
173     };
174
175     Some((impl_def, first_assoc_item))
176 }
177
178 /// Generate custom trait bodies where possible.
179 ///
180 /// Returns `Option` so that we can use `?` rather than `if let Some`. Returning
181 /// `None` means that generating a custom trait body failed, and the body will remain
182 /// as `todo!` instead.
183 fn gen_default_impl(
184     func: &ast::Fn,
185     trait_path: &ast::Path,
186     adt: &ast::Adt,
187     annotated_name: &ast::Name,
188 ) -> Option<()> {
189     match trait_path.segment()?.name_ref()?.text().as_str() {
190         "Debug" => gen_debug_impl(adt, func, annotated_name),
191         _ => Some(()),
192     }
193 }
194
195 /// Generate a `Debug` impl based on the fields and members of the target type.
196 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn, annotated_name: &ast::Name) -> Option<()> {
197     match adt {
198         // `Debug` cannot be derived for unions, so no default impl can be provided.
199         ast::Adt::Union(_) => Some(()),
200
201         // => match self { Self::Variant => write!(f, "Variant") }
202         ast::Adt::Enum(enum_) => {
203             let list = enum_.variant_list()?;
204             let mut arms = vec![];
205             for variant in list.variants() {
206                 let name = variant.name()?;
207                 let left = make::ext::ident_path("Self");
208                 let right = make::ext::ident_path(&format!("{}", name));
209                 let variant_name = make::path_pat(make::path_concat(left, right));
210
211                 let target = make::expr_path(make::ext::ident_path("f").into());
212                 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
213                 let args = make::arg_list(vec![target, fmt_string]);
214                 let macro_name = make::expr_path(make::ext::ident_path("write"));
215                 let macro_call = make::expr_macro_call(macro_name, args);
216
217                 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
218             }
219
220             let match_target = make::expr_path(make::ext::ident_path("self"));
221             let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
222             let match_expr = make::expr_match(match_target, list);
223
224             let body = make::block_expr(None, Some(match_expr));
225             let body = body.indent(ast::edit::IndentLevel(1));
226             ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
227             Some(())
228         }
229
230         ast::Adt::Struct(strukt) => {
231             let name = format!("\"{}\"", annotated_name);
232             let args = make::arg_list(Some(make::expr_literal(&name).into()));
233             let target = make::expr_path(make::ext::ident_path("f"));
234
235             let expr = match strukt.field_list() {
236                 // => f.debug_struct("Name").finish()
237                 None => make::expr_method_call(target, make::name_ref("debug_struct"), args),
238
239                 // => f.debug_struct("Name").field("foo", &self.foo).finish()
240                 Some(ast::FieldList::RecordFieldList(field_list)) => {
241                     let method = make::name_ref("debug_struct");
242                     let mut expr = make::expr_method_call(target, method, args);
243                     for field in field_list.fields() {
244                         let name = field.name()?;
245                         let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
246                         let f_path = make::expr_path(make::ext::ident_path("self"));
247                         let f_path = make::expr_ref(f_path, false);
248                         let f_path = make::expr_field(f_path, &format!("{}", name)).into();
249                         let args = make::arg_list(vec![f_name, f_path]);
250                         expr = make::expr_method_call(expr, make::name_ref("field"), args);
251                     }
252                     expr
253                 }
254
255                 // => f.debug_tuple("Name").field(self.0).finish()
256                 Some(ast::FieldList::TupleFieldList(field_list)) => {
257                     let method = make::name_ref("debug_tuple");
258                     let mut expr = make::expr_method_call(target, method, args);
259                     for (idx, _) in field_list.fields().enumerate() {
260                         let f_path = make::expr_path(make::ext::ident_path("self"));
261                         let f_path = make::expr_ref(f_path, false);
262                         let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
263                         let method = make::name_ref("field");
264                         expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
265                     }
266                     expr
267                 }
268             };
269
270             let method = make::name_ref("finish");
271             let expr = make::expr_method_call(expr, method, make::arg_list(None));
272             let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
273             ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
274             Some(())
275         }
276     }
277 }
278
279 fn update_attribute(
280     builder: &mut AssistBuilder,
281     input: &ast::TokenTree,
282     trait_name: &ast::NameRef,
283     attr: &ast::Attr,
284 ) {
285     let trait_name = trait_name.text();
286     let new_attr_input = input
287         .syntax()
288         .descendants_with_tokens()
289         .filter(|t| t.kind() == IDENT)
290         .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
291         .filter(|t| t != &trait_name)
292         .collect::<Vec<_>>();
293     let has_more_derives = !new_attr_input.is_empty();
294
295     if has_more_derives {
296         let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
297         builder.replace(input.syntax().text_range(), new_attr_input);
298     } else {
299         let attr_range = attr.syntax().text_range();
300         builder.delete(attr_range);
301
302         if let Some(line_break_range) = attr
303             .syntax()
304             .next_sibling_or_token()
305             .filter(|t| t.kind() == WHITESPACE)
306             .map(|t| t.text_range())
307         {
308             builder.delete(line_break_range);
309         }
310     }
311 }
312
313 #[cfg(test)]
314 mod tests {
315     use crate::tests::{check_assist, check_assist_not_applicable};
316
317     use super::*;
318
319     #[test]
320     fn add_custom_impl_debug_record_struct() {
321         check_assist(
322             replace_derive_with_manual_impl,
323             r#"
324 //- minicore: fmt
325 #[derive(Debu$0g)]
326 struct Foo {
327     bar: String,
328 }
329 "#,
330             r#"
331 struct Foo {
332     bar: String,
333 }
334
335 impl core::fmt::Debug for Foo {
336     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
337         f.debug_struct("Foo").field("bar", &self.bar).finish()
338     }
339 }
340 "#,
341         )
342     }
343     #[test]
344     fn add_custom_impl_debug_tuple_struct() {
345         check_assist(
346             replace_derive_with_manual_impl,
347             r#"
348 //- minicore: fmt
349 #[derive(Debu$0g)]
350 struct Foo(String, usize);
351 "#,
352             r#"struct Foo(String, usize);
353
354 impl core::fmt::Debug for Foo {
355     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356         f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
357     }
358 }
359 "#,
360         )
361     }
362     #[test]
363     fn add_custom_impl_debug_empty_struct() {
364         check_assist(
365             replace_derive_with_manual_impl,
366             r#"
367 //- minicore: fmt
368 #[derive(Debu$0g)]
369 struct Foo;
370 "#,
371             r#"
372 struct Foo;
373
374 impl core::fmt::Debug for Foo {
375     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376         f.debug_struct("Foo").finish()
377     }
378 }
379 "#,
380         )
381     }
382     #[test]
383     fn add_custom_impl_debug_enum() {
384         check_assist(
385             replace_derive_with_manual_impl,
386             r#"
387 //- minicore: fmt
388 #[derive(Debu$0g)]
389 enum Foo {
390     Bar,
391     Baz,
392 }
393 "#,
394             r#"
395 enum Foo {
396     Bar,
397     Baz,
398 }
399
400 impl core::fmt::Debug for Foo {
401     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
402         match self {
403             Self::Bar => write!(f, "Bar"),
404             Self::Baz => write!(f, "Baz"),
405         }
406     }
407 }
408 "#,
409         )
410     }
411     #[test]
412     fn add_custom_impl_all() {
413         check_assist(
414             replace_derive_with_manual_impl,
415             r#"
416 mod foo {
417     pub trait Bar {
418         type Qux;
419         const Baz: usize = 42;
420         const Fez: usize;
421         fn foo();
422         fn bar() {}
423     }
424 }
425
426 #[derive($0Bar)]
427 struct Foo {
428     bar: String,
429 }
430 "#,
431             r#"
432 mod foo {
433     pub trait Bar {
434         type Qux;
435         const Baz: usize = 42;
436         const Fez: usize;
437         fn foo();
438         fn bar() {}
439     }
440 }
441
442 struct Foo {
443     bar: String,
444 }
445
446 impl foo::Bar for Foo {
447     $0type Qux;
448
449     const Baz: usize = 42;
450
451     const Fez: usize;
452
453     fn foo() {
454         todo!()
455     }
456 }
457 "#,
458         )
459     }
460     #[test]
461     fn add_custom_impl_for_unique_input() {
462         check_assist(
463             replace_derive_with_manual_impl,
464             r#"
465 #[derive(Debu$0g)]
466 struct Foo {
467     bar: String,
468 }
469             "#,
470             r#"
471 struct Foo {
472     bar: String,
473 }
474
475 impl Debug for Foo {
476     $0
477 }
478             "#,
479         )
480     }
481
482     #[test]
483     fn add_custom_impl_for_with_visibility_modifier() {
484         check_assist(
485             replace_derive_with_manual_impl,
486             r#"
487 #[derive(Debug$0)]
488 pub struct Foo {
489     bar: String,
490 }
491             "#,
492             r#"
493 pub struct Foo {
494     bar: String,
495 }
496
497 impl Debug for Foo {
498     $0
499 }
500             "#,
501         )
502     }
503
504     #[test]
505     fn add_custom_impl_when_multiple_inputs() {
506         check_assist(
507             replace_derive_with_manual_impl,
508             r#"
509 #[derive(Display, Debug$0, Serialize)]
510 struct Foo {}
511             "#,
512             r#"
513 #[derive(Display, Serialize)]
514 struct Foo {}
515
516 impl Debug for Foo {
517     $0
518 }
519             "#,
520         )
521     }
522
523     #[test]
524     fn test_ignore_derive_macro_without_input() {
525         check_assist_not_applicable(
526             replace_derive_with_manual_impl,
527             r#"
528 #[derive($0)]
529 struct Foo {}
530             "#,
531         )
532     }
533
534     #[test]
535     fn test_ignore_if_cursor_on_param() {
536         check_assist_not_applicable(
537             replace_derive_with_manual_impl,
538             r#"
539 #[derive$0(Debug)]
540 struct Foo {}
541             "#,
542         );
543
544         check_assist_not_applicable(
545             replace_derive_with_manual_impl,
546             r#"
547 #[derive(Debug)$0]
548 struct Foo {}
549             "#,
550         )
551     }
552
553     #[test]
554     fn test_ignore_if_not_derive() {
555         check_assist_not_applicable(
556             replace_derive_with_manual_impl,
557             r#"
558 #[allow(non_camel_$0case_types)]
559 struct Foo {}
560             "#,
561         )
562     }
563
564     #[test]
565     fn works_at_start_of_file() {
566         cov_mark::check!(outside_of_attr_args);
567         check_assist_not_applicable(
568             replace_derive_with_manual_impl,
569             r#"
570 $0#[derive(Debug)]
571 struct S;
572             "#,
573         );
574     }
575 }