]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs
Merge #10769
[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, HasName},
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, gen_trait_fn_body,
14         generate_trait_impl_text, 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 //     $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
36 //         f.debug_struct("S").finish()
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.inner()),
69     )
70     .filter_map(|item| match item.as_module_def()? {
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, adt, &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     adt: &ast::Adt,
153     annotated_name: &ast::Name,
154     trait_: Option<hir::Trait>,
155     trait_path: &ast::Path,
156 ) -> Option<(ast::Impl, ast::AssocItem)> {
157     let trait_ = trait_?;
158     let target_scope = sema.scope(annotated_name.syntax());
159     let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
160     if trait_items.is_empty() {
161         return None;
162     }
163     let impl_def = {
164         use syntax::ast::Impl;
165         let text = generate_trait_impl_text(adt, trait_path.to_string().as_str(), "");
166         let parse = syntax::SourceFile::parse(&text);
167         let node = match parse.tree().syntax().descendants().find_map(Impl::cast) {
168             Some(it) => it,
169             None => {
170                 panic!(
171                     "Failed to make ast node `{}` from text {}",
172                     std::any::type_name::<Impl>(),
173                     text
174                 )
175             }
176         };
177         let node = node.clone_subtree();
178         assert_eq!(node.syntax().text_range().start(), 0.into());
179         node
180     };
181
182     let (impl_def, first_assoc_item) =
183         add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
184
185     // Generate a default `impl` function body for the derived trait.
186     if let ast::AssocItem::Fn(ref func) = first_assoc_item {
187         let _ = gen_trait_fn_body(func, trait_path, adt);
188     };
189
190     Some((impl_def, first_assoc_item))
191 }
192
193 fn update_attribute(
194     builder: &mut AssistBuilder,
195     input: &ast::TokenTree,
196     trait_name: &ast::NameRef,
197     attr: &ast::Attr,
198 ) {
199     let trait_name = trait_name.text();
200     let new_attr_input = input
201         .syntax()
202         .descendants_with_tokens()
203         .filter(|t| t.kind() == IDENT)
204         .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
205         .filter(|t| t != &trait_name)
206         .collect::<Vec<_>>();
207     let has_more_derives = !new_attr_input.is_empty();
208
209     if has_more_derives {
210         let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
211         builder.replace(input.syntax().text_range(), new_attr_input);
212     } else {
213         let attr_range = attr.syntax().text_range();
214         builder.delete(attr_range);
215
216         if let Some(line_break_range) = attr
217             .syntax()
218             .next_sibling_or_token()
219             .filter(|t| t.kind() == WHITESPACE)
220             .map(|t| t.text_range())
221         {
222             builder.delete(line_break_range);
223         }
224     }
225 }
226
227 #[cfg(test)]
228 mod tests {
229     use crate::tests::{check_assist, check_assist_not_applicable};
230
231     use super::*;
232
233     #[test]
234     fn add_custom_impl_debug_record_struct() {
235         check_assist(
236             replace_derive_with_manual_impl,
237             r#"
238 //- minicore: fmt
239 #[derive(Debu$0g)]
240 struct Foo {
241     bar: String,
242 }
243 "#,
244             r#"
245 struct Foo {
246     bar: String,
247 }
248
249 impl core::fmt::Debug for Foo {
250     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251         f.debug_struct("Foo").field("bar", &self.bar).finish()
252     }
253 }
254 "#,
255         )
256     }
257     #[test]
258     fn add_custom_impl_debug_tuple_struct() {
259         check_assist(
260             replace_derive_with_manual_impl,
261             r#"
262 //- minicore: fmt
263 #[derive(Debu$0g)]
264 struct Foo(String, usize);
265 "#,
266             r#"struct Foo(String, usize);
267
268 impl core::fmt::Debug for Foo {
269     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
270         f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
271     }
272 }
273 "#,
274         )
275     }
276     #[test]
277     fn add_custom_impl_debug_empty_struct() {
278         check_assist(
279             replace_derive_with_manual_impl,
280             r#"
281 //- minicore: fmt
282 #[derive(Debu$0g)]
283 struct Foo;
284 "#,
285             r#"
286 struct Foo;
287
288 impl core::fmt::Debug for Foo {
289     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
290         f.debug_struct("Foo").finish()
291     }
292 }
293 "#,
294         )
295     }
296     #[test]
297     fn add_custom_impl_debug_enum() {
298         check_assist(
299             replace_derive_with_manual_impl,
300             r#"
301 //- minicore: fmt
302 #[derive(Debu$0g)]
303 enum Foo {
304     Bar,
305     Baz,
306 }
307 "#,
308             r#"
309 enum Foo {
310     Bar,
311     Baz,
312 }
313
314 impl core::fmt::Debug for Foo {
315     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
316         match self {
317             Self::Bar => write!(f, "Bar"),
318             Self::Baz => write!(f, "Baz"),
319         }
320     }
321 }
322 "#,
323         )
324     }
325
326     #[test]
327     fn add_custom_impl_debug_tuple_enum() {
328         check_assist(
329             replace_derive_with_manual_impl,
330             r#"
331 //- minicore: fmt
332 #[derive(Debu$0g)]
333 enum Foo {
334     Bar(usize, usize),
335     Baz,
336 }
337 "#,
338             r#"
339 enum Foo {
340     Bar(usize, usize),
341     Baz,
342 }
343
344 impl core::fmt::Debug for Foo {
345     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
346         match self {
347             Self::Bar(arg0, arg1) => f.debug_tuple("Bar").field(arg0).field(arg1).finish(),
348             Self::Baz => write!(f, "Baz"),
349         }
350     }
351 }
352 "#,
353         )
354     }
355     #[test]
356     fn add_custom_impl_debug_record_enum() {
357         check_assist(
358             replace_derive_with_manual_impl,
359             r#"
360 //- minicore: fmt
361 #[derive(Debu$0g)]
362 enum Foo {
363     Bar {
364         baz: usize,
365         qux: usize,
366     },
367     Baz,
368 }
369 "#,
370             r#"
371 enum Foo {
372     Bar {
373         baz: usize,
374         qux: usize,
375     },
376     Baz,
377 }
378
379 impl core::fmt::Debug for Foo {
380     $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
381         match self {
382             Self::Bar { baz, qux } => f.debug_struct("Bar").field("baz", baz).field("qux", qux).finish(),
383             Self::Baz => write!(f, "Baz"),
384         }
385     }
386 }
387 "#,
388         )
389     }
390     #[test]
391     fn add_custom_impl_default_record_struct() {
392         check_assist(
393             replace_derive_with_manual_impl,
394             r#"
395 //- minicore: default
396 #[derive(Defau$0lt)]
397 struct Foo {
398     foo: usize,
399 }
400 "#,
401             r#"
402 struct Foo {
403     foo: usize,
404 }
405
406 impl Default for Foo {
407     $0fn default() -> Self {
408         Self { foo: Default::default() }
409     }
410 }
411 "#,
412         )
413     }
414     #[test]
415     fn add_custom_impl_default_tuple_struct() {
416         check_assist(
417             replace_derive_with_manual_impl,
418             r#"
419 //- minicore: default
420 #[derive(Defau$0lt)]
421 struct Foo(usize);
422 "#,
423             r#"
424 struct Foo(usize);
425
426 impl Default for Foo {
427     $0fn default() -> Self {
428         Self(Default::default())
429     }
430 }
431 "#,
432         )
433     }
434     #[test]
435     fn add_custom_impl_default_empty_struct() {
436         check_assist(
437             replace_derive_with_manual_impl,
438             r#"
439 //- minicore: default
440 #[derive(Defau$0lt)]
441 struct Foo;
442 "#,
443             r#"
444 struct Foo;
445
446 impl Default for Foo {
447     $0fn default() -> Self {
448         Self {  }
449     }
450 }
451 "#,
452         )
453     }
454
455     #[test]
456     fn add_custom_impl_hash_record_struct() {
457         check_assist(
458             replace_derive_with_manual_impl,
459             r#"
460 //- minicore: hash
461 #[derive(Has$0h)]
462 struct Foo {
463     bin: usize,
464     bar: usize,
465 }
466 "#,
467             r#"
468 struct Foo {
469     bin: usize,
470     bar: usize,
471 }
472
473 impl core::hash::Hash for Foo {
474     $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
475         self.bin.hash(state);
476         self.bar.hash(state);
477     }
478 }
479 "#,
480         )
481     }
482
483     #[test]
484     fn add_custom_impl_hash_tuple_struct() {
485         check_assist(
486             replace_derive_with_manual_impl,
487             r#"
488 //- minicore: hash
489 #[derive(Has$0h)]
490 struct Foo(usize, usize);
491 "#,
492             r#"
493 struct Foo(usize, usize);
494
495 impl core::hash::Hash for Foo {
496     $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
497         self.0.hash(state);
498         self.1.hash(state);
499     }
500 }
501 "#,
502         )
503     }
504
505     #[test]
506     fn add_custom_impl_hash_enum() {
507         check_assist(
508             replace_derive_with_manual_impl,
509             r#"
510 //- minicore: hash
511 #[derive(Has$0h)]
512 enum Foo {
513     Bar,
514     Baz,
515 }
516 "#,
517             r#"
518 enum Foo {
519     Bar,
520     Baz,
521 }
522
523 impl core::hash::Hash for Foo {
524     $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
525         core::mem::discriminant(self).hash(state);
526     }
527 }
528 "#,
529         )
530     }
531
532     #[test]
533     fn add_custom_impl_clone_record_struct() {
534         check_assist(
535             replace_derive_with_manual_impl,
536             r#"
537 //- minicore: clone
538 #[derive(Clo$0ne)]
539 struct Foo {
540     bin: usize,
541     bar: usize,
542 }
543 "#,
544             r#"
545 struct Foo {
546     bin: usize,
547     bar: usize,
548 }
549
550 impl Clone for Foo {
551     $0fn clone(&self) -> Self {
552         Self { bin: self.bin.clone(), bar: self.bar.clone() }
553     }
554 }
555 "#,
556         )
557     }
558
559     #[test]
560     fn add_custom_impl_clone_tuple_struct() {
561         check_assist(
562             replace_derive_with_manual_impl,
563             r#"
564 //- minicore: clone
565 #[derive(Clo$0ne)]
566 struct Foo(usize, usize);
567 "#,
568             r#"
569 struct Foo(usize, usize);
570
571 impl Clone for Foo {
572     $0fn clone(&self) -> Self {
573         Self(self.0.clone(), self.1.clone())
574     }
575 }
576 "#,
577         )
578     }
579
580     #[test]
581     fn add_custom_impl_clone_empty_struct() {
582         check_assist(
583             replace_derive_with_manual_impl,
584             r#"
585 //- minicore: clone
586 #[derive(Clo$0ne)]
587 struct Foo;
588 "#,
589             r#"
590 struct Foo;
591
592 impl Clone for Foo {
593     $0fn clone(&self) -> Self {
594         Self {  }
595     }
596 }
597 "#,
598         )
599     }
600
601     #[test]
602     fn add_custom_impl_clone_enum() {
603         check_assist(
604             replace_derive_with_manual_impl,
605             r#"
606 //- minicore: clone
607 #[derive(Clo$0ne)]
608 enum Foo {
609     Bar,
610     Baz,
611 }
612 "#,
613             r#"
614 enum Foo {
615     Bar,
616     Baz,
617 }
618
619 impl Clone for Foo {
620     $0fn clone(&self) -> Self {
621         match self {
622             Self::Bar => Self::Bar,
623             Self::Baz => Self::Baz,
624         }
625     }
626 }
627 "#,
628         )
629     }
630
631     #[test]
632     fn add_custom_impl_clone_tuple_enum() {
633         check_assist(
634             replace_derive_with_manual_impl,
635             r#"
636 //- minicore: clone
637 #[derive(Clo$0ne)]
638 enum Foo {
639     Bar(String),
640     Baz,
641 }
642 "#,
643             r#"
644 enum Foo {
645     Bar(String),
646     Baz,
647 }
648
649 impl Clone for Foo {
650     $0fn clone(&self) -> Self {
651         match self {
652             Self::Bar(arg0) => Self::Bar(arg0.clone()),
653             Self::Baz => Self::Baz,
654         }
655     }
656 }
657 "#,
658         )
659     }
660
661     #[test]
662     fn add_custom_impl_clone_record_enum() {
663         check_assist(
664             replace_derive_with_manual_impl,
665             r#"
666 //- minicore: clone
667 #[derive(Clo$0ne)]
668 enum Foo {
669     Bar {
670         bin: String,
671     },
672     Baz,
673 }
674 "#,
675             r#"
676 enum Foo {
677     Bar {
678         bin: String,
679     },
680     Baz,
681 }
682
683 impl Clone for Foo {
684     $0fn clone(&self) -> Self {
685         match self {
686             Self::Bar { bin } => Self::Bar { bin: bin.clone() },
687             Self::Baz => Self::Baz,
688         }
689     }
690 }
691 "#,
692         )
693     }
694
695     #[test]
696     fn add_custom_impl_partial_ord_record_struct() {
697         check_assist(
698             replace_derive_with_manual_impl,
699             r#"
700 //- minicore: ord
701 #[derive(Partial$0Ord)]
702 struct Foo {
703     bin: usize,
704 }
705 "#,
706             r#"
707 struct Foo {
708     bin: usize,
709 }
710
711 impl PartialOrd for Foo {
712     $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
713         self.bin.partial_cmp(&other.bin)
714     }
715 }
716 "#,
717         )
718     }
719
720     #[test]
721     fn add_custom_impl_partial_ord_record_struct_multi_field() {
722         check_assist(
723             replace_derive_with_manual_impl,
724             r#"
725 //- minicore: ord
726 #[derive(Partial$0Ord)]
727 struct Foo {
728     bin: usize,
729     bar: usize,
730     baz: usize,
731 }
732 "#,
733             r#"
734 struct Foo {
735     bin: usize,
736     bar: usize,
737     baz: usize,
738 }
739
740 impl PartialOrd for Foo {
741     $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
742         match self.bin.partial_cmp(&other.bin) {
743             Some(core::cmp::Ordering::Equal) => {}
744             ord => return ord,
745         }
746         match self.bar.partial_cmp(&other.bar) {
747             Some(core::cmp::Ordering::Equal) => {}
748             ord => return ord,
749         }
750         self.baz.partial_cmp(&other.baz)
751     }
752 }
753 "#,
754         )
755     }
756
757     #[test]
758     fn add_custom_impl_partial_ord_tuple_struct() {
759         check_assist(
760             replace_derive_with_manual_impl,
761             r#"
762 //- minicore: ord
763 #[derive(Partial$0Ord)]
764 struct Foo(usize, usize, usize);
765 "#,
766             r#"
767 struct Foo(usize, usize, usize);
768
769 impl PartialOrd for Foo {
770     $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
771         match self.0.partial_cmp(&other.0) {
772             Some(core::cmp::Ordering::Equal) => {}
773             ord => return ord,
774         }
775         match self.1.partial_cmp(&other.1) {
776             Some(core::cmp::Ordering::Equal) => {}
777             ord => return ord,
778         }
779         self.2.partial_cmp(&other.2)
780     }
781 }
782 "#,
783         )
784     }
785
786     #[test]
787     fn add_custom_impl_partial_eq_record_struct() {
788         check_assist(
789             replace_derive_with_manual_impl,
790             r#"
791 //- minicore: eq
792 #[derive(Partial$0Eq)]
793 struct Foo {
794     bin: usize,
795     bar: usize,
796 }
797 "#,
798             r#"
799 struct Foo {
800     bin: usize,
801     bar: usize,
802 }
803
804 impl PartialEq for Foo {
805     $0fn eq(&self, other: &Self) -> bool {
806         self.bin == other.bin && self.bar == other.bar
807     }
808 }
809 "#,
810         )
811     }
812
813     #[test]
814     fn add_custom_impl_partial_eq_tuple_struct() {
815         check_assist(
816             replace_derive_with_manual_impl,
817             r#"
818 //- minicore: eq
819 #[derive(Partial$0Eq)]
820 struct Foo(usize, usize);
821 "#,
822             r#"
823 struct Foo(usize, usize);
824
825 impl PartialEq for Foo {
826     $0fn eq(&self, other: &Self) -> bool {
827         self.0 == other.0 && self.1 == other.1
828     }
829 }
830 "#,
831         )
832     }
833
834     #[test]
835     fn add_custom_impl_partial_eq_empty_struct() {
836         check_assist(
837             replace_derive_with_manual_impl,
838             r#"
839 //- minicore: eq
840 #[derive(Partial$0Eq)]
841 struct Foo;
842 "#,
843             r#"
844 struct Foo;
845
846 impl PartialEq for Foo {
847     $0fn eq(&self, other: &Self) -> bool {
848         true
849     }
850 }
851 "#,
852         )
853     }
854
855     #[test]
856     fn add_custom_impl_partial_eq_enum() {
857         check_assist(
858             replace_derive_with_manual_impl,
859             r#"
860 //- minicore: eq
861 #[derive(Partial$0Eq)]
862 enum Foo {
863     Bar,
864     Baz,
865 }
866 "#,
867             r#"
868 enum Foo {
869     Bar,
870     Baz,
871 }
872
873 impl PartialEq for Foo {
874     $0fn eq(&self, other: &Self) -> bool {
875         core::mem::discriminant(self) == core::mem::discriminant(other)
876     }
877 }
878 "#,
879         )
880     }
881
882     #[test]
883     fn add_custom_impl_partial_eq_tuple_enum() {
884         check_assist(
885             replace_derive_with_manual_impl,
886             r#"
887 //- minicore: eq
888 #[derive(Partial$0Eq)]
889 enum Foo {
890     Bar(String),
891     Baz,
892 }
893 "#,
894             r#"
895 enum Foo {
896     Bar(String),
897     Baz,
898 }
899
900 impl PartialEq for Foo {
901     $0fn eq(&self, other: &Self) -> bool {
902         match (self, other) {
903             (Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
904             _ => core::mem::discriminant(self) == core::mem::discriminant(other),
905         }
906     }
907 }
908 "#,
909         )
910     }
911
912     #[test]
913     fn add_custom_impl_partial_eq_record_enum() {
914         check_assist(
915             replace_derive_with_manual_impl,
916             r#"
917 //- minicore: eq
918 #[derive(Partial$0Eq)]
919 enum Foo {
920     Bar {
921         bin: String,
922     },
923     Baz {
924         qux: String,
925         fez: String,
926     },
927     Qux {},
928     Bin,
929 }
930 "#,
931             r#"
932 enum Foo {
933     Bar {
934         bin: String,
935     },
936     Baz {
937         qux: String,
938         fez: String,
939     },
940     Qux {},
941     Bin,
942 }
943
944 impl PartialEq for Foo {
945     $0fn eq(&self, other: &Self) -> bool {
946         match (self, other) {
947             (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin == r_bin,
948             (Self::Baz { qux: l_qux, fez: l_fez }, Self::Baz { qux: r_qux, fez: r_fez }) => l_qux == r_qux && l_fez == r_fez,
949             _ => core::mem::discriminant(self) == core::mem::discriminant(other),
950         }
951     }
952 }
953 "#,
954         )
955     }
956     #[test]
957     fn add_custom_impl_all() {
958         check_assist(
959             replace_derive_with_manual_impl,
960             r#"
961 mod foo {
962     pub trait Bar {
963         type Qux;
964         const Baz: usize = 42;
965         const Fez: usize;
966         fn foo();
967         fn bar() {}
968     }
969 }
970
971 #[derive($0Bar)]
972 struct Foo {
973     bar: String,
974 }
975 "#,
976             r#"
977 mod foo {
978     pub trait Bar {
979         type Qux;
980         const Baz: usize = 42;
981         const Fez: usize;
982         fn foo();
983         fn bar() {}
984     }
985 }
986
987 struct Foo {
988     bar: String,
989 }
990
991 impl foo::Bar for Foo {
992     $0type Qux;
993
994     const Baz: usize = 42;
995
996     const Fez: usize;
997
998     fn foo() {
999         todo!()
1000     }
1001 }
1002 "#,
1003         )
1004     }
1005     #[test]
1006     fn add_custom_impl_for_unique_input() {
1007         check_assist(
1008             replace_derive_with_manual_impl,
1009             r#"
1010 #[derive(Debu$0g)]
1011 struct Foo {
1012     bar: String,
1013 }
1014             "#,
1015             r#"
1016 struct Foo {
1017     bar: String,
1018 }
1019
1020 impl Debug for Foo {
1021     $0
1022 }
1023             "#,
1024         )
1025     }
1026
1027     #[test]
1028     fn add_custom_impl_for_with_visibility_modifier() {
1029         check_assist(
1030             replace_derive_with_manual_impl,
1031             r#"
1032 #[derive(Debug$0)]
1033 pub struct Foo {
1034     bar: String,
1035 }
1036             "#,
1037             r#"
1038 pub struct Foo {
1039     bar: String,
1040 }
1041
1042 impl Debug for Foo {
1043     $0
1044 }
1045             "#,
1046         )
1047     }
1048
1049     #[test]
1050     fn add_custom_impl_when_multiple_inputs() {
1051         check_assist(
1052             replace_derive_with_manual_impl,
1053             r#"
1054 #[derive(Display, Debug$0, Serialize)]
1055 struct Foo {}
1056             "#,
1057             r#"
1058 #[derive(Display, Serialize)]
1059 struct Foo {}
1060
1061 impl Debug for Foo {
1062     $0
1063 }
1064             "#,
1065         )
1066     }
1067
1068     #[test]
1069     fn add_custom_impl_default_generic_record_struct() {
1070         check_assist(
1071             replace_derive_with_manual_impl,
1072             r#"
1073 //- minicore: default
1074 #[derive(Defau$0lt)]
1075 struct Foo<T, U> {
1076     foo: T,
1077     bar: U,
1078 }
1079 "#,
1080             r#"
1081 struct Foo<T, U> {
1082     foo: T,
1083     bar: U,
1084 }
1085
1086 impl<T, U> Default for Foo<T, U> {
1087     $0fn default() -> Self {
1088         Self { foo: Default::default(), bar: Default::default() }
1089     }
1090 }
1091 "#,
1092         )
1093     }
1094
1095     #[test]
1096     fn add_custom_impl_clone_generic_tuple_struct_with_bounds() {
1097         check_assist(
1098             replace_derive_with_manual_impl,
1099             r#"
1100 //- minicore: clone
1101 #[derive(Clo$0ne)]
1102 struct Foo<T: Clone>(T, usize);
1103 "#,
1104             r#"
1105 struct Foo<T: Clone>(T, usize);
1106
1107 impl<T: Clone> Clone for Foo<T> {
1108     $0fn clone(&self) -> Self {
1109         Self(self.0.clone(), self.1.clone())
1110     }
1111 }
1112 "#,
1113         )
1114     }
1115
1116     #[test]
1117     fn test_ignore_derive_macro_without_input() {
1118         check_assist_not_applicable(
1119             replace_derive_with_manual_impl,
1120             r#"
1121 #[derive($0)]
1122 struct Foo {}
1123             "#,
1124         )
1125     }
1126
1127     #[test]
1128     fn test_ignore_if_cursor_on_param() {
1129         check_assist_not_applicable(
1130             replace_derive_with_manual_impl,
1131             r#"
1132 #[derive$0(Debug)]
1133 struct Foo {}
1134             "#,
1135         );
1136
1137         check_assist_not_applicable(
1138             replace_derive_with_manual_impl,
1139             r#"
1140 #[derive(Debug)$0]
1141 struct Foo {}
1142             "#,
1143         )
1144     }
1145
1146     #[test]
1147     fn test_ignore_if_not_derive() {
1148         check_assist_not_applicable(
1149             replace_derive_with_manual_impl,
1150             r#"
1151 #[allow(non_camel_$0case_types)]
1152 struct Foo {}
1153             "#,
1154         )
1155     }
1156
1157     #[test]
1158     fn works_at_start_of_file() {
1159         cov_mark::check!(outside_of_attr_args);
1160         check_assist_not_applicable(
1161             replace_derive_with_manual_impl,
1162             r#"
1163 $0#[derive(Debug)]
1164 struct S;
1165             "#,
1166         );
1167     }
1168 }