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},
11 assist_context::{AssistBuilder, AssistContext, Assists},
13 add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
14 render_snippet, Cursor, DefaultMethods,
19 // Assist: replace_derive_with_manual_impl
21 // Converts a `derive` impl into a manual one.
24 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
25 // #[derive(Deb$0ug, Display)]
30 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
35 // fn fmt(&self, f: &mut Formatter) -> Result<()> {
40 pub(crate) fn replace_derive_with_manual_impl(
44 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
45 let (name, args) = attr.as_simple_call()?;
50 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
51 let trait_name = trait_token.text();
53 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
55 let current_module = ctx.sema.scope(adt.syntax()).module()?;
56 let current_crate = current_module.krate();
58 let found_traits = items_locator::items_with_name(
61 NameToImport::Exact(trait_name.to_string()),
62 items_locator::AssocItemSearch::Exclude,
63 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT),
65 .filter_map(|item| match ModuleDef::from(item.as_module_def_id()?) {
66 ModuleDef::Trait(trait_) => Some(trait_),
71 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
77 let mut no_traits_found = true;
78 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
79 add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
82 let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_name)));
83 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
92 input: &ast::TokenTree,
93 trait_path: &ast::Path,
94 trait_: Option<hir::Trait>,
97 let target = attr.syntax().text_range();
98 let annotated_name = adt.name()?;
99 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
100 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
103 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
107 let insert_pos = adt.syntax().text_range().end();
108 let impl_def_with_items =
109 impl_def_from_trait(&ctx.sema, &annotated_name, trait_, trait_path);
110 update_attribute(builder, &input, &trait_name, &attr);
111 let trait_path = format!("{}", trait_path);
112 match (ctx.config.snippet_cap, impl_def_with_items) {
114 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
116 (Some(cap), None) => builder.insert_snippet(
119 generate_trait_impl_text(adt, &trait_path, " $0"),
121 (Some(cap), Some((impl_def, first_assoc_item))) => {
122 let mut cursor = Cursor::Before(first_assoc_item.syntax());
124 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
125 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
127 if m.syntax().text() == "todo!()" {
129 cursor = Cursor::Replace(placeholder.syntax());
134 builder.insert_snippet(
137 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
145 fn impl_def_from_trait(
146 sema: &hir::Semantics<ide_db::RootDatabase>,
147 annotated_name: &ast::Name,
148 trait_: Option<hir::Trait>,
149 trait_path: &ast::Path,
150 ) -> Option<(ast::Impl, ast::AssocItem)> {
151 let trait_ = trait_?;
152 let target_scope = sema.scope(annotated_name.syntax());
153 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
154 if trait_items.is_empty() {
157 let impl_def = make::impl_trait(
159 make::path_unqualified(make::path_segment(make::name_ref(&annotated_name.text()))),
161 let (impl_def, first_assoc_item) =
162 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
163 Some((impl_def, first_assoc_item))
167 builder: &mut AssistBuilder,
168 input: &ast::TokenTree,
169 trait_name: &ast::NameRef,
172 let trait_name = trait_name.text();
173 let new_attr_input = input
175 .descendants_with_tokens()
176 .filter(|t| t.kind() == IDENT)
177 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
178 .filter(|t| t != &trait_name)
179 .collect::<Vec<_>>();
180 let has_more_derives = !new_attr_input.is_empty();
182 if has_more_derives {
183 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
184 builder.replace(input.syntax().text_range(), new_attr_input);
186 let attr_range = attr.syntax().text_range();
187 builder.delete(attr_range);
189 if let Some(line_break_range) = attr
191 .next_sibling_or_token()
192 .filter(|t| t.kind() == WHITESPACE)
193 .map(|t| t.text_range())
195 builder.delete(line_break_range);
202 use crate::tests::{check_assist, check_assist_not_applicable};
207 fn add_custom_impl_debug() {
209 replace_derive_with_manual_impl,
213 pub type Result = Result<(), Error>;
214 pub struct Formatter<'a>;
216 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
228 pub type Result = Result<(), Error>;
229 pub struct Formatter<'a>;
231 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
239 impl fmt::Debug for Foo {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 fn add_custom_impl_all() {
250 replace_derive_with_manual_impl,
255 const Baz: usize = 42;
271 const Baz: usize = 42;
282 impl foo::Bar for Foo {
285 const Baz: usize = 42;
297 fn add_custom_impl_for_unique_input() {
299 replace_derive_with_manual_impl,
319 fn add_custom_impl_for_with_visibility_modifier() {
321 replace_derive_with_manual_impl,
341 fn add_custom_impl_when_multiple_inputs() {
343 replace_derive_with_manual_impl,
345 #[derive(Display, Debug$0, Serialize)]
349 #[derive(Display, Serialize)]
360 fn test_ignore_derive_macro_without_input() {
361 check_assist_not_applicable(
362 replace_derive_with_manual_impl,
371 fn test_ignore_if_cursor_on_param() {
372 check_assist_not_applicable(
373 replace_derive_with_manual_impl,
380 check_assist_not_applicable(
381 replace_derive_with_manual_impl,
390 fn test_ignore_if_not_derive() {
391 check_assist_not_applicable(
392 replace_derive_with_manual_impl,
394 #[allow(non_camel_$0case_types)]