2 use ide_db::helpers::insert_whitespace_into_node::insert_ws_into;
4 get_path_at_cursor_in_tt, import_assets::NameToImport, mod_path_to_ast,
5 parse_tt_as_comma_sep_paths,
7 use ide_db::items_locator;
8 use itertools::Itertools;
10 ast::{self, AstNode, AstToken, HasName},
11 SyntaxKind::WHITESPACE,
15 assist_context::{AssistBuilder, AssistContext, Assists},
17 add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body,
18 generate_trait_impl_text, render_snippet, Cursor, DefaultMethods,
23 // Assist: replace_derive_with_manual_impl
25 // Converts a `derive` impl into a manual one.
28 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
29 // #[derive(Deb$0ug, Display)]
34 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
39 // $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
40 // f.debug_struct("S").finish()
44 pub(crate) fn replace_derive_with_manual_impl(
48 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
49 let (name, args) = attr.as_simple_call()?;
54 if !args.syntax().text_range().contains(ctx.offset()) {
55 cov_mark::hit!(outside_of_attr_args);
59 let ident = args.syntax().token_at_offset(ctx.offset()).find_map(ast::Ident::cast)?;
60 let trait_path = get_path_at_cursor_in_tt(&ident)?;
61 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
63 let current_module = ctx.sema.scope(adt.syntax()).module()?;
64 let current_crate = current_module.krate();
66 let found_traits = items_locator::items_with_name(
69 NameToImport::exact_case_sensitive(trait_path.segments().last()?.to_string()),
70 items_locator::AssocItemSearch::Exclude,
71 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
73 .filter_map(|item| match item.as_module_def()? {
74 ModuleDef::Trait(trait_) => Some(trait_),
79 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
85 let mut no_traits_found = true;
86 let current_derives = parse_tt_as_comma_sep_paths(args.clone())?;
87 let current_derives = current_derives.as_slice();
88 for (replace_trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
102 add_assist(acc, ctx, &attr, ¤t_derives, &args, &trait_path, &trait_path, None, &adt)?;
111 old_derives: &[ast::Path],
112 old_tree: &ast::TokenTree,
113 old_trait_path: &ast::Path,
114 replace_trait_path: &ast::Path,
115 trait_: Option<hir::Trait>,
118 let target = attr.syntax().text_range();
119 let annotated_name = adt.name()?;
120 let label = format!("Convert to manual `impl {} for {}`", replace_trait_path, annotated_name);
123 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
127 let insert_pos = adt.syntax().text_range().end();
128 let impl_def_with_items =
129 impl_def_from_trait(&ctx.sema, adt, &annotated_name, trait_, replace_trait_path);
130 update_attribute(builder, old_derives, old_tree, old_trait_path, attr);
131 let trait_path = format!("{}", replace_trait_path);
132 match (ctx.config.snippet_cap, impl_def_with_items) {
134 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
136 (Some(cap), None) => builder.insert_snippet(
139 generate_trait_impl_text(adt, &trait_path, " $0"),
141 (Some(cap), Some((impl_def, first_assoc_item))) => {
142 let mut cursor = Cursor::Before(first_assoc_item.syntax());
144 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
145 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
147 if m.syntax().text() == "todo!()" {
149 cursor = Cursor::Replace(placeholder.syntax());
154 builder.insert_snippet(
157 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
165 fn impl_def_from_trait(
166 sema: &hir::Semantics<ide_db::RootDatabase>,
168 annotated_name: &ast::Name,
169 trait_: Option<hir::Trait>,
170 trait_path: &ast::Path,
171 ) -> Option<(ast::Impl, ast::AssocItem)> {
172 let trait_ = trait_?;
173 let target_scope = sema.scope(annotated_name.syntax());
174 let trait_items = filter_assoc_items(sema, &trait_.items(sema.db), DefaultMethods::No);
175 if trait_items.is_empty() {
179 use syntax::ast::Impl;
180 let text = generate_trait_impl_text(adt, trait_path.to_string().as_str(), "");
181 let parse = syntax::SourceFile::parse(&text);
182 let node = match parse.tree().syntax().descendants().find_map(Impl::cast) {
186 "Failed to make ast node `{}` from text {}",
187 std::any::type_name::<Impl>(),
192 let node = node.clone_subtree();
193 assert_eq!(node.syntax().text_range().start(), 0.into());
197 let trait_items = trait_items
200 if sema.hir_file_for(it.syntax()).is_macro() {
201 if let Some(it) = ast::AssocItem::cast(insert_ws_into(it.syntax().clone())) {
205 it.clone_for_update()
208 let (impl_def, first_assoc_item) =
209 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
211 // Generate a default `impl` function body for the derived trait.
212 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
213 let _ = gen_trait_fn_body(func, trait_path, adt);
216 Some((impl_def, first_assoc_item))
220 builder: &mut AssistBuilder,
221 old_derives: &[ast::Path],
222 old_tree: &ast::TokenTree,
223 old_trait_path: &ast::Path,
226 let new_derives = old_derives
228 .filter(|t| t.to_string() != old_trait_path.to_string())
229 .collect::<Vec<_>>();
230 let has_more_derives = !new_derives.is_empty();
232 if has_more_derives {
233 let new_derives = format!("({})", new_derives.iter().format(", "));
234 builder.replace(old_tree.syntax().text_range(), new_derives);
236 let attr_range = attr.syntax().text_range();
237 builder.delete(attr_range);
239 if let Some(line_break_range) = attr
241 .next_sibling_or_token()
242 .filter(|t| t.kind() == WHITESPACE)
243 .map(|t| t.text_range())
245 builder.delete(line_break_range);
252 use crate::tests::{check_assist, check_assist_not_applicable};
257 fn add_custom_impl_debug_record_struct() {
259 replace_derive_with_manual_impl,
272 impl core::fmt::Debug for Foo {
273 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
274 f.debug_struct("Foo").field("bar", &self.bar).finish()
281 fn add_custom_impl_debug_tuple_struct() {
283 replace_derive_with_manual_impl,
287 struct Foo(String, usize);
289 r#"struct Foo(String, usize);
291 impl core::fmt::Debug for Foo {
292 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
293 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
300 fn add_custom_impl_debug_empty_struct() {
302 replace_derive_with_manual_impl,
311 impl core::fmt::Debug for Foo {
312 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
313 f.debug_struct("Foo").finish()
320 fn add_custom_impl_debug_enum() {
322 replace_derive_with_manual_impl,
337 impl core::fmt::Debug for Foo {
338 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
340 Self::Bar => write!(f, "Bar"),
341 Self::Baz => write!(f, "Baz"),
350 fn add_custom_impl_debug_tuple_enum() {
352 replace_derive_with_manual_impl,
367 impl core::fmt::Debug for Foo {
368 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
370 Self::Bar(arg0, arg1) => f.debug_tuple("Bar").field(arg0).field(arg1).finish(),
371 Self::Baz => write!(f, "Baz"),
379 fn add_custom_impl_debug_record_enum() {
381 replace_derive_with_manual_impl,
402 impl core::fmt::Debug for Foo {
403 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
405 Self::Bar { baz, qux } => f.debug_struct("Bar").field("baz", baz).field("qux", qux).finish(),
406 Self::Baz => write!(f, "Baz"),
414 fn add_custom_impl_default_record_struct() {
416 replace_derive_with_manual_impl,
418 //- minicore: default
429 impl Default for Foo {
430 $0fn default() -> Self {
431 Self { foo: Default::default() }
438 fn add_custom_impl_default_tuple_struct() {
440 replace_derive_with_manual_impl,
442 //- minicore: default
449 impl Default for Foo {
450 $0fn default() -> Self {
451 Self(Default::default())
458 fn add_custom_impl_default_empty_struct() {
460 replace_derive_with_manual_impl,
462 //- minicore: default
469 impl Default for Foo {
470 $0fn default() -> Self {
479 fn add_custom_impl_hash_record_struct() {
481 replace_derive_with_manual_impl,
496 impl core::hash::Hash for Foo {
497 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
498 self.bin.hash(state);
499 self.bar.hash(state);
507 fn add_custom_impl_hash_tuple_struct() {
509 replace_derive_with_manual_impl,
513 struct Foo(usize, usize);
516 struct Foo(usize, usize);
518 impl core::hash::Hash for Foo {
519 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
529 fn add_custom_impl_hash_enum() {
531 replace_derive_with_manual_impl,
546 impl core::hash::Hash for Foo {
547 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
548 core::mem::discriminant(self).hash(state);
556 fn add_custom_impl_clone_record_struct() {
558 replace_derive_with_manual_impl,
574 $0fn clone(&self) -> Self {
575 Self { bin: self.bin.clone(), bar: self.bar.clone() }
583 fn add_custom_impl_clone_tuple_struct() {
585 replace_derive_with_manual_impl,
589 struct Foo(usize, usize);
592 struct Foo(usize, usize);
595 $0fn clone(&self) -> Self {
596 Self(self.0.clone(), self.1.clone())
604 fn add_custom_impl_clone_empty_struct() {
606 replace_derive_with_manual_impl,
616 $0fn clone(&self) -> Self {
625 fn add_custom_impl_clone_enum() {
627 replace_derive_with_manual_impl,
643 $0fn clone(&self) -> Self {
645 Self::Bar => Self::Bar,
646 Self::Baz => Self::Baz,
655 fn add_custom_impl_clone_tuple_enum() {
657 replace_derive_with_manual_impl,
673 $0fn clone(&self) -> Self {
675 Self::Bar(arg0) => Self::Bar(arg0.clone()),
676 Self::Baz => Self::Baz,
685 fn add_custom_impl_clone_record_enum() {
687 replace_derive_with_manual_impl,
707 $0fn clone(&self) -> Self {
709 Self::Bar { bin } => Self::Bar { bin: bin.clone() },
710 Self::Baz => Self::Baz,
719 fn add_custom_impl_partial_ord_record_struct() {
721 replace_derive_with_manual_impl,
724 #[derive(Partial$0Ord)]
734 impl PartialOrd for Foo {
735 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
736 self.bin.partial_cmp(&other.bin)
744 fn add_custom_impl_partial_ord_record_struct_multi_field() {
746 replace_derive_with_manual_impl,
749 #[derive(Partial$0Ord)]
763 impl PartialOrd for Foo {
764 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
765 match self.bin.partial_cmp(&other.bin) {
766 Some(core::cmp::Ordering::Equal) => {}
769 match self.bar.partial_cmp(&other.bar) {
770 Some(core::cmp::Ordering::Equal) => {}
773 self.baz.partial_cmp(&other.baz)
781 fn add_custom_impl_partial_ord_tuple_struct() {
783 replace_derive_with_manual_impl,
786 #[derive(Partial$0Ord)]
787 struct Foo(usize, usize, usize);
790 struct Foo(usize, usize, usize);
792 impl PartialOrd for Foo {
793 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
794 match self.0.partial_cmp(&other.0) {
795 Some(core::cmp::Ordering::Equal) => {}
798 match self.1.partial_cmp(&other.1) {
799 Some(core::cmp::Ordering::Equal) => {}
802 self.2.partial_cmp(&other.2)
810 fn add_custom_impl_partial_eq_record_struct() {
812 replace_derive_with_manual_impl,
815 #[derive(Partial$0Eq)]
827 impl PartialEq for Foo {
828 $0fn eq(&self, other: &Self) -> bool {
829 self.bin == other.bin && self.bar == other.bar
837 fn add_custom_impl_partial_eq_tuple_struct() {
839 replace_derive_with_manual_impl,
842 #[derive(Partial$0Eq)]
843 struct Foo(usize, usize);
846 struct Foo(usize, usize);
848 impl PartialEq for Foo {
849 $0fn eq(&self, other: &Self) -> bool {
850 self.0 == other.0 && self.1 == other.1
858 fn add_custom_impl_partial_eq_empty_struct() {
860 replace_derive_with_manual_impl,
863 #[derive(Partial$0Eq)]
869 impl PartialEq for Foo {
870 $0fn eq(&self, other: &Self) -> bool {
879 fn add_custom_impl_partial_eq_enum() {
881 replace_derive_with_manual_impl,
884 #[derive(Partial$0Eq)]
896 impl PartialEq for Foo {
897 $0fn eq(&self, other: &Self) -> bool {
898 core::mem::discriminant(self) == core::mem::discriminant(other)
906 fn add_custom_impl_partial_eq_tuple_enum() {
908 replace_derive_with_manual_impl,
911 #[derive(Partial$0Eq)]
923 impl PartialEq for Foo {
924 $0fn eq(&self, other: &Self) -> bool {
925 match (self, other) {
926 (Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
927 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
936 fn add_custom_impl_partial_eq_record_enum() {
938 replace_derive_with_manual_impl,
941 #[derive(Partial$0Eq)]
967 impl PartialEq for Foo {
968 $0fn eq(&self, other: &Self) -> bool {
969 match (self, other) {
970 (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin == r_bin,
971 (Self::Baz { qux: l_qux, fez: l_fez }, Self::Baz { qux: r_qux, fez: r_fez }) => l_qux == r_qux && l_fez == r_fez,
972 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
980 fn add_custom_impl_all() {
982 replace_derive_with_manual_impl,
987 const Baz: usize = 42;
1003 const Baz: usize = 42;
1014 impl foo::Bar for Foo {
1017 const Baz: usize = 42;
1029 fn add_custom_impl_for_unique_input() {
1031 replace_derive_with_manual_impl,
1043 impl Debug for Foo {
1051 fn add_custom_impl_for_with_visibility_modifier() {
1053 replace_derive_with_manual_impl,
1065 impl Debug for Foo {
1073 fn add_custom_impl_when_multiple_inputs() {
1075 replace_derive_with_manual_impl,
1077 #[derive(Display, Debug$0, Serialize)]
1081 #[derive(Display, Serialize)]
1084 impl Debug for Foo {
1092 fn add_custom_impl_default_generic_record_struct() {
1094 replace_derive_with_manual_impl,
1096 //- minicore: default
1097 #[derive(Defau$0lt)]
1109 impl<T, U> Default for Foo<T, U> {
1110 $0fn default() -> Self {
1111 Self { foo: Default::default(), bar: Default::default() }
1119 fn add_custom_impl_clone_generic_tuple_struct_with_bounds() {
1121 replace_derive_with_manual_impl,
1125 struct Foo<T: Clone>(T, usize);
1128 struct Foo<T: Clone>(T, usize);
1130 impl<T: Clone> Clone for Foo<T> {
1131 $0fn clone(&self) -> Self {
1132 Self(self.0.clone(), self.1.clone())
1140 fn test_ignore_derive_macro_without_input() {
1141 check_assist_not_applicable(
1142 replace_derive_with_manual_impl,
1151 fn test_ignore_if_cursor_on_param() {
1152 check_assist_not_applicable(
1153 replace_derive_with_manual_impl,
1160 check_assist_not_applicable(
1161 replace_derive_with_manual_impl,
1170 fn test_ignore_if_not_derive() {
1171 check_assist_not_applicable(
1172 replace_derive_with_manual_impl,
1174 #[allow(non_camel_$0case_types)]
1181 fn works_at_start_of_file() {
1182 cov_mark::check!(outside_of_attr_args);
1183 check_assist_not_applicable(
1184 replace_derive_with_manual_impl,
1193 fn add_custom_impl_keep_path() {
1195 replace_derive_with_manual_impl,
1198 #[derive(std::fmt::Debug, Clo$0ne)]
1202 #[derive(std::fmt::Debug)]
1205 impl Clone for Foo {
1206 $0fn clone(&self) -> Self {
1215 fn add_custom_impl_replace_path() {
1217 replace_derive_with_manual_impl,
1220 #[derive(core::fmt::Deb$0ug, Clone)]
1227 impl core::fmt::Debug for Foo {
1228 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1229 f.debug_struct("Foo").finish()