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, NameOwner},
7 SyntaxKind::{IDENT, WHITESPACE},
10 use crate::utils::gen_trait_body;
12 assist_context::{AssistBuilder, AssistContext, Assists},
14 add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
15 render_snippet, Cursor, DefaultMethods,
20 // Assist: replace_derive_with_manual_impl
22 // Converts a `derive` impl into a manual one.
25 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
26 // #[derive(Deb$0ug, Display)]
31 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
36 // $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
37 // f.debug_struct("S").finish()
41 pub(crate) fn replace_derive_with_manual_impl(
45 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
46 let (name, args) = attr.as_simple_call()?;
51 if !args.syntax().text_range().contains(ctx.offset()) {
52 cov_mark::hit!(outside_of_attr_args);
56 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
57 let trait_name = trait_token.text();
59 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
61 let current_module = ctx.sema.scope(adt.syntax()).module()?;
62 let current_crate = current_module.krate();
64 let found_traits = items_locator::items_with_name(
67 NameToImport::Exact(trait_name.to_string()),
68 items_locator::AssocItemSearch::Exclude,
69 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
71 .filter_map(|item| match item.as_module_def()? {
72 ModuleDef::Trait(trait_) => Some(trait_),
77 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
83 let mut no_traits_found = true;
84 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
85 add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
88 let trait_path = make::ext::ident_path(trait_name);
89 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
98 input: &ast::TokenTree,
99 trait_path: &ast::Path,
100 trait_: Option<hir::Trait>,
103 let target = attr.syntax().text_range();
104 let annotated_name = adt.name()?;
105 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
106 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
109 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
113 let insert_pos = adt.syntax().text_range().end();
114 let impl_def_with_items =
115 impl_def_from_trait(&ctx.sema, adt, &annotated_name, trait_, trait_path);
116 update_attribute(builder, input, &trait_name, attr);
117 let trait_path = format!("{}", trait_path);
118 match (ctx.config.snippet_cap, impl_def_with_items) {
120 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
122 (Some(cap), None) => builder.insert_snippet(
125 generate_trait_impl_text(adt, &trait_path, " $0"),
127 (Some(cap), Some((impl_def, first_assoc_item))) => {
128 let mut cursor = Cursor::Before(first_assoc_item.syntax());
130 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
131 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
133 if m.syntax().text() == "todo!()" {
135 cursor = Cursor::Replace(placeholder.syntax());
140 builder.insert_snippet(
143 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
151 fn impl_def_from_trait(
152 sema: &hir::Semantics<ide_db::RootDatabase>,
154 annotated_name: &ast::Name,
155 trait_: Option<hir::Trait>,
156 trait_path: &ast::Path,
157 ) -> Option<(ast::Impl, ast::AssocItem)> {
158 let trait_ = trait_?;
159 let target_scope = sema.scope(annotated_name.syntax());
160 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
161 if trait_items.is_empty() {
165 make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
166 let (impl_def, first_assoc_item) =
167 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
169 // Generate a default `impl` function body for the derived trait.
170 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
171 let _ = gen_trait_body(func, trait_path, adt);
174 Some((impl_def, first_assoc_item))
178 builder: &mut AssistBuilder,
179 input: &ast::TokenTree,
180 trait_name: &ast::NameRef,
183 let trait_name = trait_name.text();
184 let new_attr_input = input
186 .descendants_with_tokens()
187 .filter(|t| t.kind() == IDENT)
188 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
189 .filter(|t| t != &trait_name)
190 .collect::<Vec<_>>();
191 let has_more_derives = !new_attr_input.is_empty();
193 if has_more_derives {
194 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
195 builder.replace(input.syntax().text_range(), new_attr_input);
197 let attr_range = attr.syntax().text_range();
198 builder.delete(attr_range);
200 if let Some(line_break_range) = attr
202 .next_sibling_or_token()
203 .filter(|t| t.kind() == WHITESPACE)
204 .map(|t| t.text_range())
206 builder.delete(line_break_range);
213 use crate::tests::{check_assist, check_assist_not_applicable};
218 fn add_custom_impl_debug_record_struct() {
220 replace_derive_with_manual_impl,
233 impl core::fmt::Debug for Foo {
234 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
235 f.debug_struct("Foo").field("bar", &self.bar).finish()
242 fn add_custom_impl_debug_tuple_struct() {
244 replace_derive_with_manual_impl,
248 struct Foo(String, usize);
250 r#"struct Foo(String, usize);
252 impl core::fmt::Debug for Foo {
253 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
254 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
261 fn add_custom_impl_debug_empty_struct() {
263 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").finish()
281 fn add_custom_impl_debug_enum() {
283 replace_derive_with_manual_impl,
298 impl core::fmt::Debug for Foo {
299 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
301 Self::Bar => write!(f, "Bar"),
302 Self::Baz => write!(f, "Baz"),
310 fn add_custom_impl_default_record_struct() {
312 replace_derive_with_manual_impl,
314 //- minicore: default
325 impl Default for Foo {
326 $0fn default() -> Self {
327 Self { foo: Default::default() }
334 fn add_custom_impl_default_tuple_struct() {
336 replace_derive_with_manual_impl,
338 //- minicore: default
345 impl Default for Foo {
346 $0fn default() -> Self {
347 Self(Default::default())
354 fn add_custom_impl_default_empty_struct() {
356 replace_derive_with_manual_impl,
358 //- minicore: default
365 impl Default for Foo {
366 $0fn default() -> Self {
374 fn add_custom_impl_all() {
376 replace_derive_with_manual_impl,
381 const Baz: usize = 42;
397 const Baz: usize = 42;
408 impl foo::Bar for Foo {
411 const Baz: usize = 42;
423 fn add_custom_impl_for_unique_input() {
425 replace_derive_with_manual_impl,
445 fn add_custom_impl_for_with_visibility_modifier() {
447 replace_derive_with_manual_impl,
467 fn add_custom_impl_when_multiple_inputs() {
469 replace_derive_with_manual_impl,
471 #[derive(Display, Debug$0, Serialize)]
475 #[derive(Display, Serialize)]
486 fn test_ignore_derive_macro_without_input() {
487 check_assist_not_applicable(
488 replace_derive_with_manual_impl,
497 fn test_ignore_if_cursor_on_param() {
498 check_assist_not_applicable(
499 replace_derive_with_manual_impl,
506 check_assist_not_applicable(
507 replace_derive_with_manual_impl,
516 fn test_ignore_if_not_derive() {
517 check_assist_not_applicable(
518 replace_derive_with_manual_impl,
520 #[allow(non_camel_$0case_types)]
527 fn works_at_start_of_file() {
528 cov_mark::check!(outside_of_attr_args);
529 check_assist_not_applicable(
530 replace_derive_with_manual_impl,