]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs
move code around
[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_trait_body_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_trait_body_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         "Default" => gen_default_impl(adt, func),
192         _ => None,
193     }
194 }
195
196 /// Generate a `Debug` impl based on the fields and members of the target type.
197 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn, annotated_name: &ast::Name) -> Option<()> {
198     match adt {
199         // `Debug` cannot be derived for unions, so no default impl can be provided.
200         ast::Adt::Union(_) => None,
201
202         // => match self { Self::Variant => write!(f, "Variant") }
203         ast::Adt::Enum(enum_) => {
204             let list = enum_.variant_list()?;
205             let mut arms = vec![];
206             for variant in list.variants() {
207                 let name = variant.name()?;
208                 let left = make::ext::ident_path("Self");
209                 let right = make::ext::ident_path(&format!("{}", name));
210                 let variant_name = make::path_pat(make::path_concat(left, right));
211
212                 let target = make::expr_path(make::ext::ident_path("f").into());
213                 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
214                 let args = make::arg_list(vec![target, fmt_string]);
215                 let macro_name = make::expr_path(make::ext::ident_path("write"));
216                 let macro_call = make::expr_macro_call(macro_name, args);
217
218                 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
219             }
220
221             let match_target = make::expr_path(make::ext::ident_path("self"));
222             let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
223             let match_expr = make::expr_match(match_target, list);
224
225             let body = make::block_expr(None, Some(match_expr));
226             let body = body.indent(ast::edit::IndentLevel(1));
227             ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
228             Some(())
229         }
230
231         ast::Adt::Struct(strukt) => {
232             let name = format!("\"{}\"", annotated_name);
233             let args = make::arg_list(Some(make::expr_literal(&name).into()));
234             let target = make::expr_path(make::ext::ident_path("f"));
235
236             let expr = match strukt.field_list() {
237                 // => f.debug_struct("Name").finish()
238                 None => make::expr_method_call(target, make::name_ref("debug_struct"), args),
239
240                 // => f.debug_struct("Name").field("foo", &self.foo).finish()
241                 Some(ast::FieldList::RecordFieldList(field_list)) => {
242                     let method = make::name_ref("debug_struct");
243                     let mut expr = make::expr_method_call(target, method, args);
244                     for field in field_list.fields() {
245                         let name = field.name()?;
246                         let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
247                         let f_path = make::expr_path(make::ext::ident_path("self"));
248                         let f_path = make::expr_ref(f_path, false);
249                         let f_path = make::expr_field(f_path, &format!("{}", name)).into();
250                         let args = make::arg_list(vec![f_name, f_path]);
251                         expr = make::expr_method_call(expr, make::name_ref("field"), args);
252                     }
253                     expr
254                 }
255
256                 // => f.debug_tuple("Name").field(self.0).finish()
257                 Some(ast::FieldList::TupleFieldList(field_list)) => {
258                     let method = make::name_ref("debug_tuple");
259                     let mut expr = make::expr_method_call(target, method, args);
260                     for (idx, _) in field_list.fields().enumerate() {
261                         let f_path = make::expr_path(make::ext::ident_path("self"));
262                         let f_path = make::expr_ref(f_path, false);
263                         let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
264                         let method = make::name_ref("field");
265                         expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
266                     }
267                     expr
268                 }
269             };
270
271             let method = make::name_ref("finish");
272             let expr = make::expr_method_call(expr, method, make::arg_list(None));
273             let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
274             ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
275             Some(())
276         }
277     }
278 }
279
280 /// Generate a `Debug` impl based on the fields and members of the target type.
281 fn gen_default_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
282     fn gen_default_call() -> ast::Expr {
283         let trait_name = make::ext::ident_path("Default");
284         let method_name = make::ext::ident_path("default");
285         let fn_name = make::expr_path(make::path_concat(trait_name, method_name));
286         make::expr_call(fn_name, make::arg_list(None))
287     }
288     match adt {
289         // `Debug` cannot be derived for unions, so no default impl can be provided.
290         ast::Adt::Union(_) => None,
291         // Deriving `Debug` for enums is not stable yet.
292         ast::Adt::Enum(_) => None,
293         ast::Adt::Struct(strukt) => {
294             let expr = match strukt.field_list() {
295                 Some(ast::FieldList::RecordFieldList(field_list)) => {
296                     let mut fields = vec![];
297                     for field in field_list.fields() {
298                         let method_call = gen_default_call();
299                         let name_ref = make::name_ref(&field.name()?.to_string());
300                         let field = make::record_expr_field(name_ref, Some(method_call));
301                         fields.push(field);
302                     }
303                     let struct_name = make::ext::ident_path("Self");
304                     let fields = make::record_expr_field_list(fields);
305                     make::record_expr(struct_name, fields).into()
306                 }
307                 Some(ast::FieldList::TupleFieldList(field_list)) => {
308                     let struct_name = make::expr_path(make::ext::ident_path("Self"));
309                     let fields = field_list.fields().map(|_| gen_default_call());
310                     make::expr_call(struct_name, make::arg_list(fields))
311                 }
312                 None => {
313                     let struct_name = make::ext::ident_path("Self");
314                     let fields = make::record_expr_field_list(None);
315                     make::record_expr(struct_name, fields).into()
316                 }
317             };
318             let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
319             ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
320             Some(())
321         }
322     }
323 }
324 fn update_attribute(
325     builder: &mut AssistBuilder,
326     input: &ast::TokenTree,
327     trait_name: &ast::NameRef,
328     attr: &ast::Attr,
329 ) {
330     let trait_name = trait_name.text();
331     let new_attr_input = input
332         .syntax()
333         .descendants_with_tokens()
334         .filter(|t| t.kind() == IDENT)
335         .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
336         .filter(|t| t != &trait_name)
337         .collect::<Vec<_>>();
338     let has_more_derives = !new_attr_input.is_empty();
339
340     if has_more_derives {
341         let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
342         builder.replace(input.syntax().text_range(), new_attr_input);
343     } else {
344         let attr_range = attr.syntax().text_range();
345         builder.delete(attr_range);
346
347         if let Some(line_break_range) = attr
348             .syntax()
349             .next_sibling_or_token()
350             .filter(|t| t.kind() == WHITESPACE)
351             .map(|t| t.text_range())
352         {
353             builder.delete(line_break_range);
354         }
355     }
356 }
357
358 #[cfg(test)]
359 mod tests {
360     use crate::tests::{check_assist, check_assist_not_applicable};
361
362     use super::*;
363
364     #[test]
365     fn add_custom_impl_debug_record_struct() {
366         check_assist(
367             replace_derive_with_manual_impl,
368             r#"
369 //- minicore: fmt
370 #[derive(Debu$0g)]
371 struct Foo {
372     bar: String,
373 }
374 "#,
375             r#"
376 struct Foo {
377     bar: String,
378 }
379
380 impl core::fmt::Debug for Foo {
381     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
382         f.debug_struct("Foo").field("bar", &self.bar).finish()
383     }
384 }
385 "#,
386         )
387     }
388     #[test]
389     fn add_custom_impl_debug_tuple_struct() {
390         check_assist(
391             replace_derive_with_manual_impl,
392             r#"
393 //- minicore: fmt
394 #[derive(Debu$0g)]
395 struct Foo(String, usize);
396 "#,
397             r#"struct Foo(String, usize);
398
399 impl core::fmt::Debug for Foo {
400     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401         f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
402     }
403 }
404 "#,
405         )
406     }
407     #[test]
408     fn add_custom_impl_debug_empty_struct() {
409         check_assist(
410             replace_derive_with_manual_impl,
411             r#"
412 //- minicore: fmt
413 #[derive(Debu$0g)]
414 struct Foo;
415 "#,
416             r#"
417 struct Foo;
418
419 impl core::fmt::Debug for Foo {
420     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
421         f.debug_struct("Foo").finish()
422     }
423 }
424 "#,
425         )
426     }
427     #[test]
428     fn add_custom_impl_debug_enum() {
429         check_assist(
430             replace_derive_with_manual_impl,
431             r#"
432 //- minicore: fmt
433 #[derive(Debu$0g)]
434 enum Foo {
435     Bar,
436     Baz,
437 }
438 "#,
439             r#"
440 enum Foo {
441     Bar,
442     Baz,
443 }
444
445 impl core::fmt::Debug for Foo {
446     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
447         match self {
448             Self::Bar => write!(f, "Bar"),
449             Self::Baz => write!(f, "Baz"),
450         }
451     }
452 }
453 "#,
454         )
455     }
456     #[test]
457     fn add_custom_impl_default_record_struct() {
458         check_assist(
459             replace_derive_with_manual_impl,
460             r#"
461 //- minicore: default
462 #[derive(Defau$0lt)]
463 struct Foo {
464     foo: usize,
465 }
466 "#,
467             r#"
468 struct Foo {
469     foo: usize,
470 }
471
472 impl Default for Foo {
473     $0fn default() -> Self {
474         Self { foo: Default::default() }
475     }
476 }
477 "#,
478         )
479     }
480     #[test]
481     fn add_custom_impl_default_tuple_struct() {
482         check_assist(
483             replace_derive_with_manual_impl,
484             r#"
485 //- minicore: default
486 #[derive(Defau$0lt)]
487 struct Foo(usize);
488 "#,
489             r#"
490 struct Foo(usize);
491
492 impl Default for Foo {
493     $0fn default() -> Self {
494         Self(Default::default())
495     }
496 }
497 "#,
498         )
499     }
500     #[test]
501     fn add_custom_impl_default_empty_struct() {
502         check_assist(
503             replace_derive_with_manual_impl,
504             r#"
505 //- minicore: default
506 #[derive(Defau$0lt)]
507 struct Foo;
508 "#,
509             r#"
510 struct Foo;
511
512 impl Default for Foo {
513     $0fn default() -> Self {
514         Self {  }
515     }
516 }
517 "#,
518         )
519     }
520     #[test]
521     fn add_custom_impl_all() {
522         check_assist(
523             replace_derive_with_manual_impl,
524             r#"
525 mod foo {
526     pub trait Bar {
527         type Qux;
528         const Baz: usize = 42;
529         const Fez: usize;
530         fn foo();
531         fn bar() {}
532     }
533 }
534
535 #[derive($0Bar)]
536 struct Foo {
537     bar: String,
538 }
539 "#,
540             r#"
541 mod foo {
542     pub trait Bar {
543         type Qux;
544         const Baz: usize = 42;
545         const Fez: usize;
546         fn foo();
547         fn bar() {}
548     }
549 }
550
551 struct Foo {
552     bar: String,
553 }
554
555 impl foo::Bar for Foo {
556     $0type Qux;
557
558     const Baz: usize = 42;
559
560     const Fez: usize;
561
562     fn foo() {
563         todo!()
564     }
565 }
566 "#,
567         )
568     }
569     #[test]
570     fn add_custom_impl_for_unique_input() {
571         check_assist(
572             replace_derive_with_manual_impl,
573             r#"
574 #[derive(Debu$0g)]
575 struct Foo {
576     bar: String,
577 }
578             "#,
579             r#"
580 struct Foo {
581     bar: String,
582 }
583
584 impl Debug for Foo {
585     $0
586 }
587             "#,
588         )
589     }
590
591     #[test]
592     fn add_custom_impl_for_with_visibility_modifier() {
593         check_assist(
594             replace_derive_with_manual_impl,
595             r#"
596 #[derive(Debug$0)]
597 pub struct Foo {
598     bar: String,
599 }
600             "#,
601             r#"
602 pub struct Foo {
603     bar: String,
604 }
605
606 impl Debug for Foo {
607     $0
608 }
609             "#,
610         )
611     }
612
613     #[test]
614     fn add_custom_impl_when_multiple_inputs() {
615         check_assist(
616             replace_derive_with_manual_impl,
617             r#"
618 #[derive(Display, Debug$0, Serialize)]
619 struct Foo {}
620             "#,
621             r#"
622 #[derive(Display, Serialize)]
623 struct Foo {}
624
625 impl Debug for Foo {
626     $0
627 }
628             "#,
629         )
630     }
631
632     #[test]
633     fn test_ignore_derive_macro_without_input() {
634         check_assist_not_applicable(
635             replace_derive_with_manual_impl,
636             r#"
637 #[derive($0)]
638 struct Foo {}
639             "#,
640         )
641     }
642
643     #[test]
644     fn test_ignore_if_cursor_on_param() {
645         check_assist_not_applicable(
646             replace_derive_with_manual_impl,
647             r#"
648 #[derive$0(Debug)]
649 struct Foo {}
650             "#,
651         );
652
653         check_assist_not_applicable(
654             replace_derive_with_manual_impl,
655             r#"
656 #[derive(Debug)$0]
657 struct Foo {}
658             "#,
659         )
660     }
661
662     #[test]
663     fn test_ignore_if_not_derive() {
664         check_assist_not_applicable(
665             replace_derive_with_manual_impl,
666             r#"
667 #[allow(non_camel_$0case_types)]
668 struct Foo {}
669             "#,
670         )
671     }
672
673     #[test]
674     fn works_at_start_of_file() {
675         cov_mark::check!(outside_of_attr_args);
676         check_assist_not_applicable(
677             replace_derive_with_manual_impl,
678             r#"
679 $0#[derive(Debug)]
680 struct S;
681             "#,
682         );
683     }
684 }