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;
8 ast::{self, make, AstNode, NameOwner},
9 SyntaxKind::{IDENT, WHITESPACE},
13 assist_context::{AssistBuilder, AssistContext, Assists},
15 add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
16 render_snippet, Cursor, DefaultMethods,
21 // Assist: replace_derive_with_manual_impl
23 // Converts a `derive` impl into a manual one.
26 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
27 // #[derive(Deb$0ug, Display)]
32 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
37 // $0fn fmt(&self, f: &mut Formatter) -> Result<()> {
38 // f.debug_struct("S").finish()
42 pub(crate) fn replace_derive_with_manual_impl(
46 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
47 let (name, args) = attr.as_simple_call()?;
52 if !args.syntax().text_range().contains(ctx.offset()) {
53 cov_mark::hit!(outside_of_attr_args);
57 let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
58 let trait_name = trait_token.text();
60 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
62 let current_module = ctx.sema.scope(adt.syntax()).module()?;
63 let current_crate = current_module.krate();
65 let found_traits = items_locator::items_with_name(
68 NameToImport::Exact(trait_name.to_string()),
69 items_locator::AssocItemSearch::Exclude,
70 Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
72 .filter_map(|item| match item.as_module_def()? {
73 ModuleDef::Trait(trait_) => Some(trait_),
78 .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
84 let mut no_traits_found = true;
85 for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
86 add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
89 let trait_path = make::ext::ident_path(trait_name);
90 add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
99 input: &ast::TokenTree,
100 trait_path: &ast::Path,
101 trait_: Option<hir::Trait>,
104 let target = attr.syntax().text_range();
105 let annotated_name = adt.name()?;
106 let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
107 let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
110 AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
114 let insert_pos = adt.syntax().text_range().end();
115 let impl_def_with_items =
116 impl_def_from_trait(&ctx.sema, adt, &annotated_name, trait_, trait_path);
117 update_attribute(builder, input, &trait_name, attr);
118 let trait_path = format!("{}", trait_path);
119 match (ctx.config.snippet_cap, impl_def_with_items) {
121 builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
123 (Some(cap), None) => builder.insert_snippet(
126 generate_trait_impl_text(adt, &trait_path, " $0"),
128 (Some(cap), Some((impl_def, first_assoc_item))) => {
129 let mut cursor = Cursor::Before(first_assoc_item.syntax());
131 if let ast::AssocItem::Fn(ref func) = first_assoc_item {
132 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
134 if m.syntax().text() == "todo!()" {
136 cursor = Cursor::Replace(placeholder.syntax());
141 builder.insert_snippet(
144 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
152 fn impl_def_from_trait(
153 sema: &hir::Semantics<ide_db::RootDatabase>,
155 annotated_name: &ast::Name,
156 trait_: Option<hir::Trait>,
157 trait_path: &ast::Path,
158 ) -> Option<(ast::Impl, ast::AssocItem)> {
159 let trait_ = trait_?;
160 let target_scope = sema.scope(annotated_name.syntax());
161 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
162 if trait_items.is_empty() {
166 make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
167 let (impl_def, first_assoc_item) =
168 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
170 // Generate a default `impl` function body for the derived trait.
171 if let ast::AssocItem::Fn(func) = &first_assoc_item {
172 match trait_path.segment().unwrap().name_ref().unwrap().text().as_str() {
173 "Debug" => gen_debug_impl(adt, func, annotated_name),
174 _ => {} // => If we don't know about the trait, the function body is left as `todo!`.
177 Some((impl_def, first_assoc_item))
180 /// Generate a `Debug` impl based on the fields and members of the target type.
181 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn, annotated_name: &ast::Name) {
183 ast::Adt::Union(_) => {} // `Debug` cannot be derived for unions, so no default impl can be provided.
184 ast::Adt::Enum(enum_) => {
185 // => match self { Self::Variant => write!(f, "Variant") }
186 if let Some(list) = enum_.variant_list() {
187 let mut arms = vec![];
188 for variant in list.variants() {
189 let name = variant.name().unwrap();
191 let left = make::ext::ident_path("Self");
192 let right = make::ext::ident_path(&format!("{}", name));
193 let variant_name = make::path_pat(make::path_concat(left, right));
195 let target = make::expr_path(make::ext::ident_path("f").into());
196 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
197 let args = make::arg_list(vec![target, fmt_string]);
198 let macro_name = make::expr_path(make::ext::ident_path("write"));
199 let macro_call = make::expr_macro_call(macro_name, args);
201 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
204 let match_target = make::expr_path(make::ext::ident_path("self"));
205 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
206 let match_expr = make::expr_match(match_target, list);
208 let body = make::block_expr(None, Some(match_expr));
209 let body = body.indent(ast::edit::IndentLevel(1));
210 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
213 ast::Adt::Struct(strukt) => {
214 let name = format!("\"{}\"", annotated_name);
215 let args = make::arg_list(Some(make::expr_literal(&name).into()));
216 let target = make::expr_path(make::ext::ident_path("f"));
218 let expr = match strukt.field_list() {
220 // => f.debug_struct("Name").finish()
221 make::expr_method_call(target, "debug_struct", args)
223 Some(ast::FieldList::RecordFieldList(field_list)) => {
224 // => f.debug_struct("Name").field("foo", &self.foo).finish()
225 let mut expr = make::expr_method_call(target, "debug_struct", args);
226 for field in field_list.fields() {
227 if let Some(name) = field.name() {
228 let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
229 let f_path = make::expr_path(make::ext::ident_path("self"));
230 let f_path = make::expr_ref(f_path, false);
231 let f_path = make::expr_field(f_path, &format!("{}", name)).into();
232 let args = make::arg_list(vec![f_name, f_path]);
233 expr = make::expr_method_call(expr, "field", args);
238 Some(ast::FieldList::TupleFieldList(field_list)) => {
239 // => f.debug_tuple("Name").field(self.0).finish()
240 let mut expr = make::expr_method_call(target, "debug_tuple", args);
241 for (idx, _) in field_list.fields().enumerate() {
242 let f_path = make::expr_path(make::ext::ident_path("self"));
243 let f_path = make::expr_ref(f_path, false);
244 let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
245 expr = make::expr_method_call(expr, "field", make::arg_list(Some(f_path)));
251 let expr = make::expr_method_call(expr, "finish", make::arg_list(None));
252 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
253 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
259 builder: &mut AssistBuilder,
260 input: &ast::TokenTree,
261 trait_name: &ast::NameRef,
264 let trait_name = trait_name.text();
265 let new_attr_input = input
267 .descendants_with_tokens()
268 .filter(|t| t.kind() == IDENT)
269 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
270 .filter(|t| t != &trait_name)
271 .collect::<Vec<_>>();
272 let has_more_derives = !new_attr_input.is_empty();
274 if has_more_derives {
275 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
276 builder.replace(input.syntax().text_range(), new_attr_input);
278 let attr_range = attr.syntax().text_range();
279 builder.delete(attr_range);
281 if let Some(line_break_range) = attr
283 .next_sibling_or_token()
284 .filter(|t| t.kind() == WHITESPACE)
285 .map(|t| t.text_range())
287 builder.delete(line_break_range);
294 use crate::tests::{check_assist, check_assist_not_applicable};
299 fn add_custom_impl_debug_record_struct() {
301 replace_derive_with_manual_impl,
305 pub type Result = Result<(), Error>;
306 pub struct Formatter<'a>;
308 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
320 pub type Result = Result<(), Error>;
321 pub struct Formatter<'a>;
323 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
331 impl fmt::Debug for Foo {
332 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 f.debug_struct("Foo").field("bar", &self.bar).finish()
340 fn add_custom_impl_debug_tuple_struct() {
342 replace_derive_with_manual_impl,
346 pub type Result = Result<(), Error>;
347 pub struct Formatter<'a>;
349 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
354 struct Foo(String, usize);
359 pub type Result = Result<(), Error>;
360 pub struct Formatter<'a>;
362 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
366 struct Foo(String, usize);
368 impl fmt::Debug for Foo {
369 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
377 fn add_custom_impl_debug_empty_struct() {
379 replace_derive_with_manual_impl,
383 pub type Result = Result<(), Error>;
384 pub struct Formatter<'a>;
386 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
396 pub type Result = Result<(), Error>;
397 pub struct Formatter<'a>;
399 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
405 impl fmt::Debug for Foo {
406 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407 f.debug_struct("Foo").finish()
414 fn add_custom_impl_debug_enum() {
416 replace_derive_with_manual_impl,
420 pub type Result = Result<(), Error>;
421 pub struct Formatter<'a>;
423 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
436 pub type Result = Result<(), Error>;
437 pub struct Formatter<'a>;
439 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
448 impl fmt::Debug for Foo {
449 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 Self::Bar => write!(f, "Bar"),
452 Self::Baz => write!(f, "Baz"),
460 fn add_custom_impl_all() {
462 replace_derive_with_manual_impl,
467 const Baz: usize = 42;
483 const Baz: usize = 42;
494 impl foo::Bar for Foo {
497 const Baz: usize = 42;
509 fn add_custom_impl_for_unique_input() {
511 replace_derive_with_manual_impl,
531 fn add_custom_impl_for_with_visibility_modifier() {
533 replace_derive_with_manual_impl,
553 fn add_custom_impl_when_multiple_inputs() {
555 replace_derive_with_manual_impl,
557 #[derive(Display, Debug$0, Serialize)]
561 #[derive(Display, Serialize)]
572 fn test_ignore_derive_macro_without_input() {
573 check_assist_not_applicable(
574 replace_derive_with_manual_impl,
583 fn test_ignore_if_cursor_on_param() {
584 check_assist_not_applicable(
585 replace_derive_with_manual_impl,
592 check_assist_not_applicable(
593 replace_derive_with_manual_impl,
602 fn test_ignore_if_not_derive() {
603 check_assist_not_applicable(
604 replace_derive_with_manual_impl,
606 #[allow(non_camel_$0case_types)]
613 fn works_at_start_of_file() {
614 cov_mark::check!(outside_of_attr_args);
615 check_assist_not_applicable(
616 replace_derive_with_manual_impl,