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