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(ref func) = first_assoc_item {
172 let _ = gen_default_impl(func, trait_path, adt, annotated_name);
175 Some((impl_def, first_assoc_item))
178 /// Generate custom trait bodies where possible.
180 /// Returns `Option` so that we can use `?` rather than `if let Some`. Returning
181 /// `None` means that generating a custom trait body failed, and the body will remain
182 /// as `todo!` instead.
185 trait_path: &ast::Path,
187 annotated_name: &ast::Name,
189 match trait_path.segment()?.name_ref()?.text().as_str() {
190 "Debug" => gen_debug_impl(adt, func, annotated_name),
195 /// Generate a `Debug` impl based on the fields and members of the target type.
196 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn, annotated_name: &ast::Name) -> Option<()> {
198 // `Debug` cannot be derived for unions, so no default impl can be provided.
199 ast::Adt::Union(_) => Some(()),
201 // => match self { Self::Variant => write!(f, "Variant") }
202 ast::Adt::Enum(enum_) => {
203 let list = enum_.variant_list()?;
204 let mut arms = vec![];
205 for variant in list.variants() {
206 let name = variant.name()?;
207 let left = make::ext::ident_path("Self");
208 let right = make::ext::ident_path(&format!("{}", name));
209 let variant_name = make::path_pat(make::path_concat(left, right));
211 let target = make::expr_path(make::ext::ident_path("f").into());
212 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
213 let args = make::arg_list(vec![target, fmt_string]);
214 let macro_name = make::expr_path(make::ext::ident_path("write"));
215 let macro_call = make::expr_macro_call(macro_name, args);
217 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
220 let match_target = make::expr_path(make::ext::ident_path("self"));
221 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
222 let match_expr = make::expr_match(match_target, list);
224 let body = make::block_expr(None, Some(match_expr));
225 let body = body.indent(ast::edit::IndentLevel(1));
226 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
230 ast::Adt::Struct(strukt) => {
231 let name = format!("\"{}\"", annotated_name);
232 let args = make::arg_list(Some(make::expr_literal(&name).into()));
233 let target = make::expr_path(make::ext::ident_path("f"));
235 let expr = match strukt.field_list() {
236 // => f.debug_struct("Name").finish()
237 None => make::expr_method_call(target, make::name_ref("debug_struct"), args),
239 // => f.debug_struct("Name").field("foo", &self.foo).finish()
240 Some(ast::FieldList::RecordFieldList(field_list)) => {
241 let method = make::name_ref("debug_struct");
242 let mut expr = make::expr_method_call(target, method, args);
243 for field in field_list.fields() {
244 let name = field.name()?;
245 let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
246 let f_path = make::expr_path(make::ext::ident_path("self"));
247 let f_path = make::expr_ref(f_path, false);
248 let f_path = make::expr_field(f_path, &format!("{}", name)).into();
249 let args = make::arg_list(vec![f_name, f_path]);
250 expr = make::expr_method_call(expr, make::name_ref("field"), args);
255 // => f.debug_tuple("Name").field(self.0).finish()
256 Some(ast::FieldList::TupleFieldList(field_list)) => {
257 let method = make::name_ref("debug_tuple");
258 let mut expr = make::expr_method_call(target, method, args);
259 for (idx, _) in field_list.fields().enumerate() {
260 let f_path = make::expr_path(make::ext::ident_path("self"));
261 let f_path = make::expr_ref(f_path, false);
262 let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
263 let method = make::name_ref("field");
264 expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
270 let method = make::name_ref("finish");
271 let expr = make::expr_method_call(expr, method, make::arg_list(None));
272 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
273 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
280 builder: &mut AssistBuilder,
281 input: &ast::TokenTree,
282 trait_name: &ast::NameRef,
285 let trait_name = trait_name.text();
286 let new_attr_input = input
288 .descendants_with_tokens()
289 .filter(|t| t.kind() == IDENT)
290 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
291 .filter(|t| t != &trait_name)
292 .collect::<Vec<_>>();
293 let has_more_derives = !new_attr_input.is_empty();
295 if has_more_derives {
296 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
297 builder.replace(input.syntax().text_range(), new_attr_input);
299 let attr_range = attr.syntax().text_range();
300 builder.delete(attr_range);
302 if let Some(line_break_range) = attr
304 .next_sibling_or_token()
305 .filter(|t| t.kind() == WHITESPACE)
306 .map(|t| t.text_range())
308 builder.delete(line_break_range);
315 use crate::tests::{check_assist, check_assist_not_applicable};
320 fn add_custom_impl_debug_record_struct() {
322 replace_derive_with_manual_impl,
335 impl core::fmt::Debug for Foo {
336 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
337 f.debug_struct("Foo").field("bar", &self.bar).finish()
344 fn add_custom_impl_debug_tuple_struct() {
346 replace_derive_with_manual_impl,
350 struct Foo(String, usize);
352 r#"struct Foo(String, usize);
354 impl core::fmt::Debug for Foo {
355 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
363 fn add_custom_impl_debug_empty_struct() {
365 replace_derive_with_manual_impl,
374 impl core::fmt::Debug for Foo {
375 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376 f.debug_struct("Foo").finish()
383 fn add_custom_impl_debug_enum() {
385 replace_derive_with_manual_impl,
400 impl core::fmt::Debug for Foo {
401 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
403 Self::Bar => write!(f, "Bar"),
404 Self::Baz => write!(f, "Baz"),
412 fn add_custom_impl_all() {
414 replace_derive_with_manual_impl,
419 const Baz: usize = 42;
435 const Baz: usize = 42;
446 impl foo::Bar for Foo {
449 const Baz: usize = 42;
461 fn add_custom_impl_for_unique_input() {
463 replace_derive_with_manual_impl,
483 fn add_custom_impl_for_with_visibility_modifier() {
485 replace_derive_with_manual_impl,
505 fn add_custom_impl_when_multiple_inputs() {
507 replace_derive_with_manual_impl,
509 #[derive(Display, Debug$0, Serialize)]
513 #[derive(Display, Serialize)]
524 fn test_ignore_derive_macro_without_input() {
525 check_assist_not_applicable(
526 replace_derive_with_manual_impl,
535 fn test_ignore_if_cursor_on_param() {
536 check_assist_not_applicable(
537 replace_derive_with_manual_impl,
544 check_assist_not_applicable(
545 replace_derive_with_manual_impl,
554 fn test_ignore_if_not_derive() {
555 check_assist_not_applicable(
556 replace_derive_with_manual_impl,
558 #[allow(non_camel_$0case_types)]
565 fn works_at_start_of_file() {
566 cov_mark::check!(outside_of_attr_args);
567 check_assist_not_applicable(
568 replace_derive_with_manual_impl,