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 if !args.syntax().text_range().contains(ctx.offset()) {
51 cov_mark::hit!(outside_of_attr_args);
55 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
56 let trait_name = trait_token.text();
58 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
60 let current_module = ctx.sema.scope(adt.syntax()).module()?;
61 let current_crate = current_module.krate();
63 let found_traits = items_locator::items_with_name(
66 NameToImport::Exact(trait_name.to_string()),
67 items_locator::AssocItemSearch::Exclude,
68 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT),
70 .filter_map(|item| match ModuleDef::from(item.as_module_def_id()?) {
71 ModuleDef::Trait(trait_) => Some(trait_),
76 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
82 let mut no_traits_found = true;
83 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
84 add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
87 let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_name)));
88 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
97 input: &ast::TokenTree,
98 trait_path: &ast::Path,
99 trait_: Option<hir::Trait>,
102 let target = attr.syntax().text_range();
103 let annotated_name = adt.name()?;
104 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
105 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
108 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
112 let insert_pos = adt.syntax().text_range().end();
113 let impl_def_with_items =
114 impl_def_from_trait(&ctx.sema, &annotated_name, trait_, trait_path);
115 update_attribute(builder, &input, &trait_name, &attr);
116 let trait_path = format!("{}", trait_path);
117 match (ctx.config.snippet_cap, impl_def_with_items) {
119 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
121 (Some(cap), None) => builder.insert_snippet(
124 generate_trait_impl_text(adt, &trait_path, " $0"),
126 (Some(cap), Some((impl_def, first_assoc_item))) => {
127 let mut cursor = Cursor::Before(first_assoc_item.syntax());
129 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
130 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
132 if m.syntax().text() == "todo!()" {
134 cursor = Cursor::Replace(placeholder.syntax());
139 builder.insert_snippet(
142 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
150 fn impl_def_from_trait(
151 sema: &hir::Semantics<ide_db::RootDatabase>,
152 annotated_name: &ast::Name,
153 trait_: Option<hir::Trait>,
154 trait_path: &ast::Path,
155 ) -> Option<(ast::Impl, ast::AssocItem)> {
156 let trait_ = trait_?;
157 let target_scope = sema.scope(annotated_name.syntax());
158 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
159 if trait_items.is_empty() {
162 let impl_def = make::impl_trait(
164 make::path_unqualified(make::path_segment(make::name_ref(&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);
168 Some((impl_def, first_assoc_item))
172 builder: &mut AssistBuilder,
173 input: &ast::TokenTree,
174 trait_name: &ast::NameRef,
177 let trait_name = trait_name.text();
178 let new_attr_input = input
180 .descendants_with_tokens()
181 .filter(|t| t.kind() == IDENT)
182 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
183 .filter(|t| t != &trait_name)
184 .collect::<Vec<_>>();
185 let has_more_derives = !new_attr_input.is_empty();
187 if has_more_derives {
188 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
189 builder.replace(input.syntax().text_range(), new_attr_input);
191 let attr_range = attr.syntax().text_range();
192 builder.delete(attr_range);
194 if let Some(line_break_range) = attr
196 .next_sibling_or_token()
197 .filter(|t| t.kind() == WHITESPACE)
198 .map(|t| t.text_range())
200 builder.delete(line_break_range);
207 use crate::tests::{check_assist, check_assist_not_applicable};
212 fn add_custom_impl_debug() {
214 replace_derive_with_manual_impl,
218 pub type Result = Result<(), Error>;
219 pub struct Formatter<'a>;
221 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
233 pub type Result = Result<(), Error>;
234 pub struct Formatter<'a>;
236 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
244 impl fmt::Debug for Foo {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 fn add_custom_impl_all() {
255 replace_derive_with_manual_impl,
260 const Baz: usize = 42;
276 const Baz: usize = 42;
287 impl foo::Bar for Foo {
290 const Baz: usize = 42;
302 fn add_custom_impl_for_unique_input() {
304 replace_derive_with_manual_impl,
324 fn add_custom_impl_for_with_visibility_modifier() {
326 replace_derive_with_manual_impl,
346 fn add_custom_impl_when_multiple_inputs() {
348 replace_derive_with_manual_impl,
350 #[derive(Display, Debug$0, Serialize)]
354 #[derive(Display, Serialize)]
365 fn test_ignore_derive_macro_without_input() {
366 check_assist_not_applicable(
367 replace_derive_with_manual_impl,
376 fn test_ignore_if_cursor_on_param() {
377 check_assist_not_applicable(
378 replace_derive_with_manual_impl,
385 check_assist_not_applicable(
386 replace_derive_with_manual_impl,
395 fn test_ignore_if_not_derive() {
396 check_assist_not_applicable(
397 replace_derive_with_manual_impl,
399 #[allow(non_camel_$0case_types)]
406 fn works_at_start_of_file() {
407 cov_mark::check!(outside_of_attr_args);
408 check_assist_not_applicable(
409 replace_derive_with_manual_impl,