2 use ide_db::helpers::{import_assets::NameToImport, mod_path_to_ast};
3 use ide_db::items_locator;
4 use itertools::Itertools;
6 ast::{self, make, AstNode, HasName},
7 SyntaxKind::{IDENT, WHITESPACE},
11 assist_context::{AssistBuilder, AssistContext, Assists},
13 add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body,
14 generate_trait_impl_text, render_snippet, Cursor, DefaultMethods,
19 // Assist: replace_derive_with_manual_impl
21 // Converts a `derive` impl into a manual one.
24 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
25 // #[derive(Deb$0ug, Display)]
30 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
35 // $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
36 // f.debug_struct("S").finish()
40 pub(crate) fn replace_derive_with_manual_impl(
44 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
45 let (name, args) = attr.as_simple_call()?;
50 if !args.syntax().text_range().contains(ctx.offset()) {
51 cov_mark::hit!(outside_of_attr_args);
55 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
56 let trait_name = trait_token.text();
58 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
60 let current_module = ctx.sema.scope(adt.syntax()).module()?;
61 let current_crate = current_module.krate();
63 let found_traits = items_locator::items_with_name(
66 NameToImport::Exact(trait_name.to_string()),
67 items_locator::AssocItemSearch::Exclude,
68 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
70 .filter_map(|item| match item.as_module_def()? {
71 ModuleDef::Trait(trait_) => Some(trait_),
76 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
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)?;
87 let trait_path = make::ext::ident_path(trait_name);
88 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
97 input: &ast::TokenTree,
98 trait_path: &ast::Path,
99 trait_: Option<hir::Trait>,
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())?;
108 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
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) {
119 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
121 (Some(cap), None) => builder.insert_snippet(
124 generate_trait_impl_text(adt, &trait_path, " $0"),
126 (Some(cap), Some((impl_def, first_assoc_item))) => {
127 let mut cursor = Cursor::Before(first_assoc_item.syntax());
129 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
130 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
132 if m.syntax().text() == "todo!()" {
134 cursor = Cursor::Replace(placeholder.syntax());
139 builder.insert_snippet(
142 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
150 fn impl_def_from_trait(
151 sema: &hir::Semantics<ide_db::RootDatabase>,
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() {
164 make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
165 let (impl_def, first_assoc_item) =
166 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
168 // Generate a default `impl` function body for the derived trait.
169 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
170 let _ = gen_trait_fn_body(func, trait_path, adt);
173 Some((impl_def, first_assoc_item))
177 builder: &mut AssistBuilder,
178 input: &ast::TokenTree,
179 trait_name: &ast::NameRef,
182 let trait_name = trait_name.text();
183 let new_attr_input = input
185 .descendants_with_tokens()
186 .filter(|t| t.kind() == IDENT)
187 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
188 .filter(|t| t != &trait_name)
189 .collect::<Vec<_>>();
190 let has_more_derives = !new_attr_input.is_empty();
192 if has_more_derives {
193 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
194 builder.replace(input.syntax().text_range(), new_attr_input);
196 let attr_range = attr.syntax().text_range();
197 builder.delete(attr_range);
199 if let Some(line_break_range) = attr
201 .next_sibling_or_token()
202 .filter(|t| t.kind() == WHITESPACE)
203 .map(|t| t.text_range())
205 builder.delete(line_break_range);
212 use crate::tests::{check_assist, check_assist_not_applicable};
217 fn add_custom_impl_debug_record_struct() {
219 replace_derive_with_manual_impl,
232 impl core::fmt::Debug for Foo {
233 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
234 f.debug_struct("Foo").field("bar", &self.bar).finish()
241 fn add_custom_impl_debug_tuple_struct() {
243 replace_derive_with_manual_impl,
247 struct Foo(String, usize);
249 r#"struct Foo(String, usize);
251 impl core::fmt::Debug for Foo {
252 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
253 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
260 fn add_custom_impl_debug_empty_struct() {
262 replace_derive_with_manual_impl,
271 impl core::fmt::Debug for Foo {
272 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
273 f.debug_struct("Foo").finish()
280 fn add_custom_impl_debug_enum() {
282 replace_derive_with_manual_impl,
297 impl core::fmt::Debug for Foo {
298 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
300 Self::Bar => write!(f, "Bar"),
301 Self::Baz => write!(f, "Baz"),
310 fn add_custom_impl_debug_tuple_enum() {
312 replace_derive_with_manual_impl,
327 impl core::fmt::Debug for Foo {
328 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
330 Self::Bar(arg0, arg1) => f.debug_tuple("Bar").field(arg0).field(arg1).finish(),
331 Self::Baz => write!(f, "Baz"),
339 fn add_custom_impl_debug_record_enum() {
341 replace_derive_with_manual_impl,
362 impl core::fmt::Debug for Foo {
363 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
365 Self::Bar { baz, qux } => f.debug_struct("Bar").field("baz", baz).field("qux", qux).finish(),
366 Self::Baz => write!(f, "Baz"),
374 fn add_custom_impl_default_record_struct() {
376 replace_derive_with_manual_impl,
378 //- minicore: default
389 impl Default for Foo {
390 $0fn default() -> Self {
391 Self { foo: Default::default() }
398 fn add_custom_impl_default_tuple_struct() {
400 replace_derive_with_manual_impl,
402 //- minicore: default
409 impl Default for Foo {
410 $0fn default() -> Self {
411 Self(Default::default())
418 fn add_custom_impl_default_empty_struct() {
420 replace_derive_with_manual_impl,
422 //- minicore: default
429 impl Default for Foo {
430 $0fn default() -> Self {
439 fn add_custom_impl_hash_record_struct() {
441 replace_derive_with_manual_impl,
456 impl core::hash::Hash for Foo {
457 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
458 self.bin.hash(state);
459 self.bar.hash(state);
467 fn add_custom_impl_hash_tuple_struct() {
469 replace_derive_with_manual_impl,
473 struct Foo(usize, usize);
476 struct Foo(usize, usize);
478 impl core::hash::Hash for Foo {
479 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
489 fn add_custom_impl_hash_enum() {
491 replace_derive_with_manual_impl,
506 impl core::hash::Hash for Foo {
507 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
508 core::mem::discriminant(self).hash(state);
516 fn add_custom_impl_clone_record_struct() {
518 replace_derive_with_manual_impl,
534 $0fn clone(&self) -> Self {
535 Self { bin: self.bin.clone(), bar: self.bar.clone() }
543 fn add_custom_impl_clone_tuple_struct() {
545 replace_derive_with_manual_impl,
549 struct Foo(usize, usize);
552 struct Foo(usize, usize);
555 $0fn clone(&self) -> Self {
556 Self(self.0.clone(), self.1.clone())
564 fn add_custom_impl_clone_empty_struct() {
566 replace_derive_with_manual_impl,
576 $0fn clone(&self) -> Self {
585 fn add_custom_impl_clone_enum() {
587 replace_derive_with_manual_impl,
603 $0fn clone(&self) -> Self {
605 Self::Bar => Self::Bar,
606 Self::Baz => Self::Baz,
615 fn add_custom_impl_clone_tuple_enum() {
617 replace_derive_with_manual_impl,
633 $0fn clone(&self) -> Self {
635 Self::Bar(arg0) => Self::Bar(arg0.clone()),
636 Self::Baz => Self::Baz,
645 fn add_custom_impl_clone_record_enum() {
647 replace_derive_with_manual_impl,
667 $0fn clone(&self) -> Self {
669 Self::Bar { bin } => Self::Bar { bin: bin.clone() },
670 Self::Baz => Self::Baz,
679 fn add_custom_impl_partial_ord_record_struct() {
681 replace_derive_with_manual_impl,
684 #[derive(Partial$0Ord)]
694 impl PartialOrd for Foo {
695 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
696 self.bin.partial_cmp(other.bin)
704 fn add_custom_impl_partial_ord_record_struct_multi_field() {
706 replace_derive_with_manual_impl,
709 #[derive(Partial$0Ord)]
723 impl PartialOrd for Foo {
724 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
725 (self.bin, self.bar, self.baz).partial_cmp((other.bin, other.bar, other.baz))
733 fn add_custom_impl_partial_ord_tuple_struct() {
735 replace_derive_with_manual_impl,
738 #[derive(Partial$0Ord)]
739 struct Foo(usize, usize, usize);
742 struct Foo(usize, usize, usize);
744 impl PartialOrd for Foo {
745 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
746 (self.0, self.1, self.2).partial_cmp((other.0, other.1, other.2))
754 fn add_custom_impl_partial_ord_enum() {
756 replace_derive_with_manual_impl,
759 #[derive(Partial$0Ord)]
773 impl PartialOrd for Foo {
774 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
775 core::mem::discriminant(self).partial_cmp(core::mem::discriminant(other))
783 fn add_custom_impl_partial_ord_record_enum() {
785 replace_derive_with_manual_impl,
788 #[derive(Partial$0Ord)]
814 impl PartialOrd for Foo {
815 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
816 match (self, other) {
817 (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin.partial_cmp(r_bin),
818 (Self::Baz { qux: l_qux, fez: l_fez }, Self::Baz { qux: r_qux, fez: r_fez }) => {
819 (l_qux, l_fez).partial_cmp((r_qux, r_fez))
821 _ => core::mem::discriminant(self).partial_cmp(core::mem::discriminant(other)),
830 fn add_custom_impl_partial_ord_tuple_enum() {
832 replace_derive_with_manual_impl,
835 #[derive(Partial$0Ord)]
851 impl PartialOrd for Foo {
852 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
853 match (self, other) {
854 (Self::Bar(l0), Self::Bar(r0)) => l0.partial_cmp(r0),
855 (Self::Baz(l0, l1), Self::Baz(r0, r1)) => {
856 (l0, l1).partial_cmp((r0, r1))
858 _ => core::mem::discriminant(self).partial_cmp(core::mem::discriminant(other)),
867 fn add_custom_impl_partial_eq_record_struct() {
869 replace_derive_with_manual_impl,
872 #[derive(Partial$0Eq)]
884 impl PartialEq for Foo {
885 $0fn eq(&self, other: &Self) -> bool {
886 self.bin == other.bin && self.bar == other.bar
894 fn add_custom_impl_partial_eq_tuple_struct() {
896 replace_derive_with_manual_impl,
899 #[derive(Partial$0Eq)]
900 struct Foo(usize, usize);
903 struct Foo(usize, usize);
905 impl PartialEq for Foo {
906 $0fn eq(&self, other: &Self) -> bool {
907 self.0 == other.0 && self.1 == other.1
915 fn add_custom_impl_partial_eq_empty_struct() {
917 replace_derive_with_manual_impl,
920 #[derive(Partial$0Eq)]
926 impl PartialEq for Foo {
927 $0fn eq(&self, other: &Self) -> bool {
936 fn add_custom_impl_partial_eq_enum() {
938 replace_derive_with_manual_impl,
941 #[derive(Partial$0Eq)]
953 impl PartialEq for Foo {
954 $0fn eq(&self, other: &Self) -> bool {
955 core::mem::discriminant(self) == core::mem::discriminant(other)
963 fn add_custom_impl_partial_eq_tuple_enum() {
965 replace_derive_with_manual_impl,
968 #[derive(Partial$0Eq)]
980 impl PartialEq for Foo {
981 $0fn eq(&self, other: &Self) -> bool {
982 match (self, other) {
983 (Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
984 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
993 fn add_custom_impl_partial_eq_record_enum() {
995 replace_derive_with_manual_impl,
998 #[derive(Partial$0Eq)]
1024 impl PartialEq for Foo {
1025 $0fn eq(&self, other: &Self) -> bool {
1026 match (self, other) {
1027 (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin == r_bin,
1028 (Self::Baz { qux: l_qux, fez: l_fez }, Self::Baz { qux: r_qux, fez: r_fez }) => l_qux == r_qux && l_fez == r_fez,
1029 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
1037 fn add_custom_impl_all() {
1039 replace_derive_with_manual_impl,
1044 const Baz: usize = 42;
1060 const Baz: usize = 42;
1071 impl foo::Bar for Foo {
1074 const Baz: usize = 42;
1086 fn add_custom_impl_for_unique_input() {
1088 replace_derive_with_manual_impl,
1100 impl Debug for Foo {
1108 fn add_custom_impl_for_with_visibility_modifier() {
1110 replace_derive_with_manual_impl,
1122 impl Debug for Foo {
1130 fn add_custom_impl_when_multiple_inputs() {
1132 replace_derive_with_manual_impl,
1134 #[derive(Display, Debug$0, Serialize)]
1138 #[derive(Display, Serialize)]
1141 impl Debug for Foo {
1149 fn test_ignore_derive_macro_without_input() {
1150 check_assist_not_applicable(
1151 replace_derive_with_manual_impl,
1160 fn test_ignore_if_cursor_on_param() {
1161 check_assist_not_applicable(
1162 replace_derive_with_manual_impl,
1169 check_assist_not_applicable(
1170 replace_derive_with_manual_impl,
1179 fn test_ignore_if_not_derive() {
1180 check_assist_not_applicable(
1181 replace_derive_with_manual_impl,
1183 #[allow(non_camel_$0case_types)]
1190 fn works_at_start_of_file() {
1191 cov_mark::check!(outside_of_attr_args);
1192 check_assist_not_applicable(
1193 replace_derive_with_manual_impl,