2 use ide_db::helpers::{import_assets::NameToImport, mod_path_to_ast};
3 use ide_db::items_locator;
4 use itertools::Itertools;
5 use syntax::ast::edit::AstNodeEdit;
9 ast::{self, make, AstNode, NameOwner},
10 SyntaxKind::{IDENT, WHITESPACE},
14 assist_context::{AssistBuilder, AssistContext, Assists},
16 add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
17 render_snippet, Cursor, DefaultMethods,
22 // Assist: replace_derive_with_manual_impl
24 // Converts a `derive` impl into a manual one.
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 // fn fmt(&self, f: &mut Formatter) -> Result<()> {
43 pub(crate) fn replace_derive_with_manual_impl(
47 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
48 let (name, args) = attr.as_simple_call()?;
53 if !args.syntax().text_range().contains(ctx.offset()) {
54 cov_mark::hit!(outside_of_attr_args);
58 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
59 let trait_name = trait_token.text();
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(trait_name.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 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
87 add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
90 let trait_path = make::ext::ident_path(trait_name);
91 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
100 input: &ast::TokenTree,
101 trait_path: &ast::Path,
102 trait_: Option<hir::Trait>,
105 let target = attr.syntax().text_range();
106 let annotated_name = adt.name()?;
107 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
108 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
111 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
115 let insert_pos = adt.syntax().text_range().end();
116 let impl_def_with_items =
117 impl_def_from_trait(&ctx.sema, &annotated_name, trait_, trait_path);
118 update_attribute(builder, input, &trait_name, attr);
119 let trait_path = format!("{}", trait_path);
120 match (ctx.config.snippet_cap, impl_def_with_items) {
122 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
124 (Some(cap), None) => builder.insert_snippet(
127 generate_trait_impl_text(adt, &trait_path, " $0"),
129 (Some(cap), Some((impl_def, first_assoc_item))) => {
130 let mut cursor = Cursor::Before(first_assoc_item.syntax());
132 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
133 // need to know what kind of derive this is: if it's Derive Debug, special case it.
134 // the name of the struct
135 // list of fields of the struct
136 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
138 if m.syntax().text() == "todo!()" {
140 cursor = Cursor::Replace(placeholder.syntax());
145 builder.insert_snippet(
148 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
156 fn impl_def_from_trait(
157 sema: &hir::Semantics<ide_db::RootDatabase>,
158 annotated_name: &ast::Name,
159 trait_: Option<hir::Trait>,
160 trait_path: &ast::Path,
161 ) -> Option<(ast::Impl, ast::AssocItem)> {
162 let trait_ = trait_?;
163 let target_scope = sema.scope(annotated_name.syntax());
164 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
165 if trait_items.is_empty() {
169 make::impl_trait(trait_path.clone(), make::ext::ident_path(&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 if let ast::AssocItem::Fn(fn_) = &first_assoc_item {
173 if trait_path.segment().unwrap().name_ref().unwrap().text() == "Debug" {
174 let f_expr = make::expr_path(make::ext::ident_path("f"));
175 let args = make::arg_list(Some(make::expr_path(make::ext::ident_path(
176 annotated_name.text().as_str(),
179 make::block_expr(None, Some(make::expr_method_call(f_expr, "debug_struct", args)))
180 .indent(ast::edit::IndentLevel(1));
183 fn_.body().unwrap().tail_expr().unwrap().syntax(),
184 body.clone_for_update().syntax(),
188 Some((impl_def, first_assoc_item))
192 builder: &mut AssistBuilder,
193 input: &ast::TokenTree,
194 trait_name: &ast::NameRef,
197 let trait_name = trait_name.text();
198 let new_attr_input = input
200 .descendants_with_tokens()
201 .filter(|t| t.kind() == IDENT)
202 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
203 .filter(|t| t != &trait_name)
204 .collect::<Vec<_>>();
205 let has_more_derives = !new_attr_input.is_empty();
207 if has_more_derives {
208 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
209 builder.replace(input.syntax().text_range(), new_attr_input);
211 let attr_range = attr.syntax().text_range();
212 builder.delete(attr_range);
214 if let Some(line_break_range) = attr
216 .next_sibling_or_token()
217 .filter(|t| t.kind() == WHITESPACE)
218 .map(|t| t.text_range())
220 builder.delete(line_break_range);
227 use crate::tests::{check_assist, check_assist_not_applicable};
232 fn add_custom_impl_debug() {
234 replace_derive_with_manual_impl,
238 pub type Result = Result<(), Error>;
239 pub struct Formatter<'a>;
241 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
253 pub type Result = Result<(), Error>;
254 pub struct Formatter<'a>;
256 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
264 impl fmt::Debug for Foo {
265 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.debug_struct("Foo").field("bar", &self.bar).finish()
273 fn add_custom_impl_all() {
275 replace_derive_with_manual_impl,
280 const Baz: usize = 42;
296 const Baz: usize = 42;
307 impl foo::Bar for Foo {
310 const Baz: usize = 42;
322 fn add_custom_impl_for_unique_input() {
324 replace_derive_with_manual_impl,
344 fn add_custom_impl_for_with_visibility_modifier() {
346 replace_derive_with_manual_impl,
366 fn add_custom_impl_when_multiple_inputs() {
368 replace_derive_with_manual_impl,
370 #[derive(Display, Debug$0, Serialize)]
374 #[derive(Display, Serialize)]
385 fn test_ignore_derive_macro_without_input() {
386 check_assist_not_applicable(
387 replace_derive_with_manual_impl,
396 fn test_ignore_if_cursor_on_param() {
397 check_assist_not_applicable(
398 replace_derive_with_manual_impl,
405 check_assist_not_applicable(
406 replace_derive_with_manual_impl,
415 fn test_ignore_if_not_derive() {
416 check_assist_not_applicable(
417 replace_derive_with_manual_impl,
419 #[allow(non_camel_$0case_types)]
426 fn works_at_start_of_file() {
427 cov_mark::check!(outside_of_attr_args);
428 check_assist_not_applicable(
429 replace_derive_with_manual_impl,