1 use hir::{InFile, ModuleDef};
3 helpers::mod_path_to_ast, imports::import_assets::NameToImport, items_locator,
4 syntax_helpers::insert_whitespace_into_node::insert_ws_into,
6 use itertools::Itertools;
8 ast::{self, AstNode, HasName},
9 SyntaxKind::WHITESPACE,
13 assist_context::{AssistContext, Assists, SourceChangeBuilder},
15 add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body,
16 generate_trait_impl_text, render_snippet, Cursor, DefaultMethods,
21 // Assist: replace_derive_with_manual_impl
23 // Converts a `derive` impl into a manual one.
26 // # //- minicore: derive
27 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
28 // #[derive(Deb$0ug, Display)]
33 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
38 // $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
39 // f.debug_struct("S").finish()
43 pub(crate) fn replace_derive_with_manual_impl(
45 ctx: &AssistContext<'_>,
47 let attr = ctx.find_node_at_offset_with_descend::<ast::Attr>()?;
48 let path = attr.path()?;
49 let hir_file = ctx.sema.hir_file_for(attr.syntax());
50 if !hir_file.is_derive_attr_pseudo_expansion(ctx.db()) {
54 let InFile { file_id, value } = hir_file.call_node(ctx.db())?;
55 if file_id.is_macro() {
56 // FIXME: make this work in macro files
59 // collect the derive paths from the #[derive] expansion
60 let current_derives = ctx
62 .parse_or_expand(hir_file)?
64 .filter_map(ast::Attr::cast)
65 .filter_map(|attr| attr.path())
68 let adt = value.parent().and_then(ast::Adt::cast)?;
69 let attr = ast::Attr::cast(value)?;
70 let args = attr.token_tree()?;
72 let current_module = ctx.sema.scope(adt.syntax())?.module();
73 let current_crate = current_module.krate();
75 let found_traits = items_locator::items_with_name(
78 NameToImport::exact_case_sensitive(path.segments().last()?.to_string()),
79 items_locator::AssocItemSearch::Exclude,
80 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
82 .filter_map(|item| match item.as_module_def()? {
83 ModuleDef::Trait(trait_) => Some(trait_),
88 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_no_std)
94 let mut no_traits_found = true;
95 for (replace_trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
109 add_assist(acc, ctx, &attr, ¤t_derives, &args, &path, &path, None, &adt)?;
116 ctx: &AssistContext<'_>,
118 old_derives: &[ast::Path],
119 old_tree: &ast::TokenTree,
120 old_trait_path: &ast::Path,
121 replace_trait_path: &ast::Path,
122 trait_: Option<hir::Trait>,
125 let target = attr.syntax().text_range();
126 let annotated_name = adt.name()?;
127 let label = format!("Convert to manual `impl {} for {}`", replace_trait_path, annotated_name);
130 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
134 let insert_pos = adt.syntax().text_range().end();
135 let impl_def_with_items =
136 impl_def_from_trait(&ctx.sema, adt, &annotated_name, trait_, replace_trait_path);
137 update_attribute(builder, old_derives, old_tree, old_trait_path, attr);
138 let trait_path = replace_trait_path.to_string();
139 match (ctx.config.snippet_cap, impl_def_with_items) {
141 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
143 (Some(cap), None) => builder.insert_snippet(
146 generate_trait_impl_text(adt, &trait_path, " $0"),
148 (Some(cap), Some((impl_def, first_assoc_item))) => {
149 let mut cursor = Cursor::Before(first_assoc_item.syntax());
151 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
152 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
154 if m.syntax().text() == "todo!()" {
156 cursor = Cursor::Replace(placeholder.syntax());
161 builder.insert_snippet(
164 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
172 fn impl_def_from_trait(
173 sema: &hir::Semantics<'_, ide_db::RootDatabase>,
175 annotated_name: &ast::Name,
176 trait_: Option<hir::Trait>,
177 trait_path: &ast::Path,
178 ) -> Option<(ast::Impl, ast::AssocItem)> {
179 let trait_ = trait_?;
180 let target_scope = sema.scope(annotated_name.syntax())?;
181 let trait_items = filter_assoc_items(sema, &trait_.items(sema.db), DefaultMethods::No);
182 if trait_items.is_empty() {
186 use syntax::ast::Impl;
187 let text = generate_trait_impl_text(adt, trait_path.to_string().as_str(), "");
188 let parse = syntax::SourceFile::parse(&text);
189 let node = match parse.tree().syntax().descendants().find_map(Impl::cast) {
193 "Failed to make ast node `{}` from text {}",
194 std::any::type_name::<Impl>(),
199 let node = node.clone_subtree();
200 assert_eq!(node.syntax().text_range().start(), 0.into());
204 let trait_items = trait_items
207 if sema.hir_file_for(it.syntax()).is_macro() {
208 if let Some(it) = ast::AssocItem::cast(insert_ws_into(it.syntax().clone())) {
212 it.clone_for_update()
215 let (impl_def, first_assoc_item) =
216 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
218 // Generate a default `impl` function body for the derived trait.
219 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
220 let _ = gen_trait_fn_body(func, trait_path, adt);
223 Some((impl_def, first_assoc_item))
227 builder: &mut SourceChangeBuilder,
228 old_derives: &[ast::Path],
229 old_tree: &ast::TokenTree,
230 old_trait_path: &ast::Path,
233 let new_derives = old_derives
235 .filter(|t| t.to_string() != old_trait_path.to_string())
236 .collect::<Vec<_>>();
237 let has_more_derives = !new_derives.is_empty();
239 if has_more_derives {
240 let new_derives = format!("({})", new_derives.iter().format(", "));
241 builder.replace(old_tree.syntax().text_range(), new_derives);
243 let attr_range = attr.syntax().text_range();
244 builder.delete(attr_range);
246 if let Some(line_break_range) = attr
248 .next_sibling_or_token()
249 .filter(|t| t.kind() == WHITESPACE)
250 .map(|t| t.text_range())
252 builder.delete(line_break_range);
259 use crate::tests::{check_assist, check_assist_not_applicable};
264 fn add_custom_impl_debug_record_struct() {
266 replace_derive_with_manual_impl,
268 //- minicore: fmt, derive
279 impl core::fmt::Debug for Foo {
280 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
281 f.debug_struct("Foo").field("bar", &self.bar).finish()
288 fn add_custom_impl_debug_tuple_struct() {
290 replace_derive_with_manual_impl,
292 //- minicore: fmt, derive
294 struct Foo(String, usize);
296 r#"struct Foo(String, usize);
298 impl core::fmt::Debug for Foo {
299 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
300 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
307 fn add_custom_impl_debug_empty_struct() {
309 replace_derive_with_manual_impl,
311 //- minicore: fmt, derive
318 impl core::fmt::Debug for Foo {
319 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
320 f.debug_struct("Foo").finish()
327 fn add_custom_impl_debug_enum() {
329 replace_derive_with_manual_impl,
331 //- minicore: fmt, derive
344 impl core::fmt::Debug for Foo {
345 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
347 Self::Bar => write!(f, "Bar"),
348 Self::Baz => write!(f, "Baz"),
357 fn add_custom_impl_debug_tuple_enum() {
359 replace_derive_with_manual_impl,
361 //- minicore: fmt, derive
374 impl core::fmt::Debug for Foo {
375 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
377 Self::Bar(arg0, arg1) => f.debug_tuple("Bar").field(arg0).field(arg1).finish(),
378 Self::Baz => write!(f, "Baz"),
386 fn add_custom_impl_debug_record_enum() {
388 replace_derive_with_manual_impl,
390 //- minicore: fmt, derive
409 impl core::fmt::Debug for Foo {
410 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
412 Self::Bar { baz, qux } => f.debug_struct("Bar").field("baz", baz).field("qux", qux).finish(),
413 Self::Baz => write!(f, "Baz"),
421 fn add_custom_impl_default_record_struct() {
423 replace_derive_with_manual_impl,
425 //- minicore: default, derive
436 impl Default for Foo {
437 $0fn default() -> Self {
438 Self { foo: Default::default() }
445 fn add_custom_impl_default_tuple_struct() {
447 replace_derive_with_manual_impl,
449 //- minicore: default, derive
456 impl Default for Foo {
457 $0fn default() -> Self {
458 Self(Default::default())
465 fn add_custom_impl_default_empty_struct() {
467 replace_derive_with_manual_impl,
469 //- minicore: default, derive
476 impl Default for Foo {
477 $0fn default() -> Self {
486 fn add_custom_impl_hash_record_struct() {
488 replace_derive_with_manual_impl,
490 //- minicore: hash, derive
503 impl core::hash::Hash for Foo {
504 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
505 self.bin.hash(state);
506 self.bar.hash(state);
514 fn add_custom_impl_hash_tuple_struct() {
516 replace_derive_with_manual_impl,
518 //- minicore: hash, derive
520 struct Foo(usize, usize);
523 struct Foo(usize, usize);
525 impl core::hash::Hash for Foo {
526 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
536 fn add_custom_impl_hash_enum() {
538 replace_derive_with_manual_impl,
540 //- minicore: hash, derive
553 impl core::hash::Hash for Foo {
554 $0fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
555 core::mem::discriminant(self).hash(state);
563 fn add_custom_impl_clone_record_struct() {
565 replace_derive_with_manual_impl,
567 //- minicore: clone, derive
581 $0fn clone(&self) -> Self {
582 Self { bin: self.bin.clone(), bar: self.bar.clone() }
590 fn add_custom_impl_clone_tuple_struct() {
592 replace_derive_with_manual_impl,
594 //- minicore: clone, derive
596 struct Foo(usize, usize);
599 struct Foo(usize, usize);
602 $0fn clone(&self) -> Self {
603 Self(self.0.clone(), self.1.clone())
611 fn add_custom_impl_clone_empty_struct() {
613 replace_derive_with_manual_impl,
615 //- minicore: clone, derive
623 $0fn clone(&self) -> Self {
632 fn add_custom_impl_clone_enum() {
634 replace_derive_with_manual_impl,
636 //- minicore: clone, derive
650 $0fn clone(&self) -> Self {
652 Self::Bar => Self::Bar,
653 Self::Baz => Self::Baz,
662 fn add_custom_impl_clone_tuple_enum() {
664 replace_derive_with_manual_impl,
666 //- minicore: clone, derive
680 $0fn clone(&self) -> Self {
682 Self::Bar(arg0) => Self::Bar(arg0.clone()),
683 Self::Baz => Self::Baz,
692 fn add_custom_impl_clone_record_enum() {
694 replace_derive_with_manual_impl,
696 //- minicore: clone, derive
714 $0fn clone(&self) -> Self {
716 Self::Bar { bin } => Self::Bar { bin: bin.clone() },
717 Self::Baz => Self::Baz,
726 fn add_custom_impl_partial_ord_record_struct() {
728 replace_derive_with_manual_impl,
730 //- minicore: ord, derive
731 #[derive(Partial$0Ord)]
741 impl PartialOrd for Foo {
742 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
743 self.bin.partial_cmp(&other.bin)
751 fn add_custom_impl_partial_ord_record_struct_multi_field() {
753 replace_derive_with_manual_impl,
755 //- minicore: ord, derive
756 #[derive(Partial$0Ord)]
770 impl PartialOrd for Foo {
771 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
772 match self.bin.partial_cmp(&other.bin) {
773 Some(core::cmp::Ordering::Equal) => {}
776 match self.bar.partial_cmp(&other.bar) {
777 Some(core::cmp::Ordering::Equal) => {}
780 self.baz.partial_cmp(&other.baz)
788 fn add_custom_impl_partial_ord_tuple_struct() {
790 replace_derive_with_manual_impl,
792 //- minicore: ord, derive
793 #[derive(Partial$0Ord)]
794 struct Foo(usize, usize, usize);
797 struct Foo(usize, usize, usize);
799 impl PartialOrd for Foo {
800 $0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
801 match self.0.partial_cmp(&other.0) {
802 Some(core::cmp::Ordering::Equal) => {}
805 match self.1.partial_cmp(&other.1) {
806 Some(core::cmp::Ordering::Equal) => {}
809 self.2.partial_cmp(&other.2)
817 fn add_custom_impl_partial_eq_record_struct() {
819 replace_derive_with_manual_impl,
821 //- minicore: eq, derive
822 #[derive(Partial$0Eq)]
834 impl PartialEq for Foo {
835 $0fn eq(&self, other: &Self) -> bool {
836 self.bin == other.bin && self.bar == other.bar
844 fn add_custom_impl_partial_eq_tuple_struct() {
846 replace_derive_with_manual_impl,
848 //- minicore: eq, derive
849 #[derive(Partial$0Eq)]
850 struct Foo(usize, usize);
853 struct Foo(usize, usize);
855 impl PartialEq for Foo {
856 $0fn eq(&self, other: &Self) -> bool {
857 self.0 == other.0 && self.1 == other.1
865 fn add_custom_impl_partial_eq_empty_struct() {
867 replace_derive_with_manual_impl,
869 //- minicore: eq, derive
870 #[derive(Partial$0Eq)]
876 impl PartialEq for Foo {
877 $0fn eq(&self, other: &Self) -> bool {
886 fn add_custom_impl_partial_eq_enum() {
888 replace_derive_with_manual_impl,
890 //- minicore: eq, derive
891 #[derive(Partial$0Eq)]
903 impl PartialEq for Foo {
904 $0fn eq(&self, other: &Self) -> bool {
905 core::mem::discriminant(self) == core::mem::discriminant(other)
913 fn add_custom_impl_partial_eq_tuple_enum() {
915 replace_derive_with_manual_impl,
917 //- minicore: eq, derive
918 #[derive(Partial$0Eq)]
930 impl PartialEq for Foo {
931 $0fn eq(&self, other: &Self) -> bool {
932 match (self, other) {
933 (Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
934 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
943 fn add_custom_impl_partial_eq_record_enum() {
945 replace_derive_with_manual_impl,
947 //- minicore: eq, derive
948 #[derive(Partial$0Eq)]
974 impl PartialEq for Foo {
975 $0fn eq(&self, other: &Self) -> bool {
976 match (self, other) {
977 (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin == r_bin,
978 (Self::Baz { qux: l_qux, fez: l_fez }, Self::Baz { qux: r_qux, fez: r_fez }) => l_qux == r_qux && l_fez == r_fez,
979 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
987 fn add_custom_impl_all() {
989 replace_derive_with_manual_impl,
995 const Baz: usize = 42;
1011 const Baz: usize = 42;
1022 impl foo::Bar for Foo {
1025 const Baz: usize = 42;
1037 fn add_custom_impl_for_unique_input_unknown() {
1039 replace_derive_with_manual_impl,
1041 //- minicore: derive
1052 impl Debug for Foo {
1060 fn add_custom_impl_for_with_visibility_modifier() {
1062 replace_derive_with_manual_impl,
1064 //- minicore: derive
1075 impl Debug for Foo {
1083 fn add_custom_impl_when_multiple_inputs() {
1085 replace_derive_with_manual_impl,
1087 //- minicore: derive
1088 #[derive(Display, Debug$0, Serialize)]
1092 #[derive(Display, Serialize)]
1095 impl Debug for Foo {
1103 fn add_custom_impl_default_generic_record_struct() {
1105 replace_derive_with_manual_impl,
1107 //- minicore: default, derive
1108 #[derive(Defau$0lt)]
1120 impl<T, U> Default for Foo<T, U> {
1121 $0fn default() -> Self {
1122 Self { foo: Default::default(), bar: Default::default() }
1130 fn add_custom_impl_clone_generic_tuple_struct_with_bounds() {
1132 replace_derive_with_manual_impl,
1134 //- minicore: clone, derive
1136 struct Foo<T: Clone>(T, usize);
1139 struct Foo<T: Clone>(T, usize);
1141 impl<T: Clone> Clone for Foo<T> {
1142 $0fn clone(&self) -> Self {
1143 Self(self.0.clone(), self.1.clone())
1151 fn test_ignore_derive_macro_without_input() {
1152 check_assist_not_applicable(
1153 replace_derive_with_manual_impl,
1155 //- minicore: derive
1163 fn test_ignore_if_cursor_on_param() {
1164 check_assist_not_applicable(
1165 replace_derive_with_manual_impl,
1167 //- minicore: derive, fmt
1173 check_assist_not_applicable(
1174 replace_derive_with_manual_impl,
1176 //- minicore: derive, fmt
1184 fn test_ignore_if_not_derive() {
1185 check_assist_not_applicable(
1186 replace_derive_with_manual_impl,
1188 //- minicore: derive
1189 #[allow(non_camel_$0case_types)]
1196 fn works_at_start_of_file() {
1197 check_assist_not_applicable(
1198 replace_derive_with_manual_impl,
1200 //- minicore: derive, fmt
1208 fn add_custom_impl_keep_path() {
1210 replace_derive_with_manual_impl,
1212 //- minicore: clone, derive
1213 #[derive(std::fmt::Debug, Clo$0ne)]
1217 #[derive(std::fmt::Debug)]
1220 impl Clone for Foo {
1221 $0fn clone(&self) -> Self {
1230 fn add_custom_impl_replace_path() {
1232 replace_derive_with_manual_impl,
1234 //- minicore: fmt, derive
1235 #[derive(core::fmt::Deb$0ug, Clone)]
1242 impl core::fmt::Debug for Foo {
1243 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1244 f.debug_struct("Foo").finish()