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},
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 // fn fmt(&self, f: &mut Formatter) -> Result<()> {
41 pub(crate) fn replace_derive_with_manual_impl(
45 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
49 .descendants_with_tokens()
50 .filter(|t| t.kind() == IDENT)
51 .find_map(syntax::NodeOrToken::into_token)
52 .filter(|t| t.text() == "derive")
58 let trait_token = ctx.token_at_offset().find(|t| t.kind() == IDENT && t.text() != "derive")?;
59 let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_token.text())));
61 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
62 let annotated_name = adt.name()?;
63 let insert_pos = adt.syntax().text_range().end();
65 let current_module = ctx.sema.scope(annotated_name.syntax()).module()?;
66 let current_crate = current_module.krate();
68 let found_traits = items_locator::items_with_name(
71 NameToImport::Exact(trait_token.text().to_string()),
72 items_locator::AssocItemSearch::Exclude,
73 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT),
75 .filter_map(|item| match ModuleDef::from(item.as_module_def_id()?) {
76 ModuleDef::Trait(trait_) => Some(trait_),
81 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
87 let mut no_traits_found = true;
88 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
89 add_assist(acc, ctx, &attr, &trait_path, Some(trait_), &adt, &annotated_name, insert_pos)?;
92 add_assist(acc, ctx, &attr, &trait_path, None, &adt, &annotated_name, insert_pos)?;
101 trait_path: &ast::Path,
102 trait_: Option<hir::Trait>,
104 annotated_name: &ast::Name,
105 insert_pos: TextSize,
107 let target = attr.syntax().text_range();
108 let input = attr.token_tree()?;
109 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
110 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
113 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
117 let impl_def_with_items =
118 impl_def_from_trait(&ctx.sema, annotated_name, trait_, trait_path);
119 update_attribute(builder, &input, &trait_name, &attr);
120 let trait_path = format!("{}", trait_path);
121 match (ctx.config.snippet_cap, impl_def_with_items) {
123 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
125 (Some(cap), None) => builder.insert_snippet(
128 generate_trait_impl_text(adt, &trait_path, " $0"),
130 (Some(cap), Some((impl_def, first_assoc_item))) => {
131 let mut cursor = Cursor::Before(first_assoc_item.syntax());
133 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
134 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
136 if m.syntax().text() == "todo!()" {
138 cursor = Cursor::Replace(placeholder.syntax());
143 builder.insert_snippet(
146 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
154 fn impl_def_from_trait(
155 sema: &hir::Semantics<ide_db::RootDatabase>,
156 annotated_name: &ast::Name,
157 trait_: Option<hir::Trait>,
158 trait_path: &ast::Path,
159 ) -> Option<(ast::Impl, ast::AssocItem)> {
160 let trait_ = trait_?;
161 let target_scope = sema.scope(annotated_name.syntax());
162 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
163 if trait_items.is_empty() {
166 let impl_def = make::impl_trait(
168 make::path_unqualified(make::path_segment(make::name_ref(&annotated_name.text()))),
170 let (impl_def, first_assoc_item) =
171 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
172 Some((impl_def, first_assoc_item))
176 builder: &mut AssistBuilder,
177 input: &ast::TokenTree,
178 trait_name: &ast::NameRef,
181 let trait_name = trait_name.text();
182 let new_attr_input = input
184 .descendants_with_tokens()
185 .filter(|t| t.kind() == IDENT)
186 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
187 .filter(|t| t != &trait_name)
188 .collect::<Vec<_>>();
189 let has_more_derives = !new_attr_input.is_empty();
191 if has_more_derives {
192 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
193 builder.replace(input.syntax().text_range(), new_attr_input);
195 let attr_range = attr.syntax().text_range();
196 builder.delete(attr_range);
198 if let Some(line_break_range) = attr
200 .next_sibling_or_token()
201 .filter(|t| t.kind() == WHITESPACE)
202 .map(|t| t.text_range())
204 builder.delete(line_break_range);
211 use crate::tests::{check_assist, check_assist_not_applicable};
216 fn add_custom_impl_debug() {
218 replace_derive_with_manual_impl,
222 pub type Result = Result<(), Error>;
223 pub struct Formatter<'a>;
225 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
237 pub type Result = Result<(), Error>;
238 pub struct Formatter<'a>;
240 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
248 impl fmt::Debug for Foo {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 fn add_custom_impl_all() {
259 replace_derive_with_manual_impl,
264 const Baz: usize = 42;
280 const Baz: usize = 42;
291 impl foo::Bar for Foo {
294 const Baz: usize = 42;
306 fn add_custom_impl_for_unique_input() {
308 replace_derive_with_manual_impl,
328 fn add_custom_impl_for_with_visibility_modifier() {
330 replace_derive_with_manual_impl,
350 fn add_custom_impl_when_multiple_inputs() {
352 replace_derive_with_manual_impl,
354 #[derive(Display, Debug$0, Serialize)]
358 #[derive(Display, Serialize)]
369 fn test_ignore_derive_macro_without_input() {
370 check_assist_not_applicable(
371 replace_derive_with_manual_impl,
380 fn test_ignore_if_cursor_on_param() {
381 check_assist_not_applicable(
382 replace_derive_with_manual_impl,
389 check_assist_not_applicable(
390 replace_derive_with_manual_impl,
399 fn test_ignore_if_not_derive() {
400 check_assist_not_applicable(
401 replace_derive_with_manual_impl,
403 #[allow(non_camel_$0case_types)]