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_trait_body_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.
183 fn gen_trait_body_impl(
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),
191 "Default" => gen_default_impl(adt, func),
196 /// Generate a `Debug` impl based on the fields and members of the target type.
197 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn, annotated_name: &ast::Name) -> Option<()> {
199 // `Debug` cannot be derived for unions, so no default impl can be provided.
200 ast::Adt::Union(_) => Some(()),
202 // => match self { Self::Variant => write!(f, "Variant") }
203 ast::Adt::Enum(enum_) => {
204 let list = enum_.variant_list()?;
205 let mut arms = vec![];
206 for variant in list.variants() {
207 let name = variant.name()?;
208 let left = make::ext::ident_path("Self");
209 let right = make::ext::ident_path(&format!("{}", name));
210 let variant_name = make::path_pat(make::path_concat(left, right));
212 let target = make::expr_path(make::ext::ident_path("f").into());
213 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
214 let args = make::arg_list(vec![target, fmt_string]);
215 let macro_name = make::expr_path(make::ext::ident_path("write"));
216 let macro_call = make::expr_macro_call(macro_name, args);
218 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
221 let match_target = make::expr_path(make::ext::ident_path("self"));
222 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
223 let match_expr = make::expr_match(match_target, list);
225 let body = make::block_expr(None, Some(match_expr));
226 let body = body.indent(ast::edit::IndentLevel(1));
227 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
231 ast::Adt::Struct(strukt) => {
232 let name = format!("\"{}\"", annotated_name);
233 let args = make::arg_list(Some(make::expr_literal(&name).into()));
234 let target = make::expr_path(make::ext::ident_path("f"));
236 let expr = match strukt.field_list() {
237 // => f.debug_struct("Name").finish()
238 None => make::expr_method_call(target, make::name_ref("debug_struct"), args),
240 // => f.debug_struct("Name").field("foo", &self.foo).finish()
241 Some(ast::FieldList::RecordFieldList(field_list)) => {
242 let method = make::name_ref("debug_struct");
243 let mut expr = make::expr_method_call(target, method, args);
244 for field in field_list.fields() {
245 let name = field.name()?;
246 let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
247 let f_path = make::expr_path(make::ext::ident_path("self"));
248 let f_path = make::expr_ref(f_path, false);
249 let f_path = make::expr_field(f_path, &format!("{}", name)).into();
250 let args = make::arg_list(vec![f_name, f_path]);
251 expr = make::expr_method_call(expr, make::name_ref("field"), args);
256 // => f.debug_tuple("Name").field(self.0).finish()
257 Some(ast::FieldList::TupleFieldList(field_list)) => {
258 let method = make::name_ref("debug_tuple");
259 let mut expr = make::expr_method_call(target, method, args);
260 for (idx, _) in field_list.fields().enumerate() {
261 let f_path = make::expr_path(make::ext::ident_path("self"));
262 let f_path = make::expr_ref(f_path, false);
263 let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
264 let method = make::name_ref("field");
265 expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
271 let method = make::name_ref("finish");
272 let expr = make::expr_method_call(expr, method, make::arg_list(None));
273 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
274 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
280 /// Generate a `Debug` impl based on the fields and members of the target type.
281 fn gen_default_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
283 // `Debug` cannot be derived for unions, so no default impl can be provided.
284 ast::Adt::Union(_) => Some(()),
285 // Deriving `Debug` for enums is not stable yet.
286 ast::Adt::Enum(_) => Some(()),
287 ast::Adt::Struct(strukt) => {
288 let expr = match strukt.field_list() {
289 Some(ast::FieldList::RecordFieldList(field_list)) => {
290 let mut fields = vec![];
291 for field in field_list.fields() {
292 let method_call = gen_default_call();
293 let name_ref = make::name_ref(&field.name()?.to_string());
294 let field = make::record_expr_field(name_ref, Some(method_call));
297 let struct_name = make::ext::ident_path("Self");
298 let fields = make::record_expr_field_list(fields);
299 make::record_expr(struct_name, fields).into()
301 Some(ast::FieldList::TupleFieldList(field_list)) => {
302 let struct_name = make::expr_path(make::ext::ident_path("Self"));
303 let fields = field_list.fields().map(|_| gen_default_call());
304 make::expr_call(struct_name, make::arg_list(fields))
307 let struct_name = make::ext::ident_path("Self");
308 let fields = make::record_expr_field_list(None);
309 make::record_expr(struct_name, fields).into()
312 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
313 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
318 fn gen_default_call() -> ast::Expr {
319 let trait_name = make::ext::ident_path("Default");
320 let method_name = make::ext::ident_path("default");
321 let fn_name = make::expr_path(make::path_concat(trait_name, method_name));
322 make::expr_call(fn_name, make::arg_list(None))
326 builder: &mut AssistBuilder,
327 input: &ast::TokenTree,
328 trait_name: &ast::NameRef,
331 let trait_name = trait_name.text();
332 let new_attr_input = input
334 .descendants_with_tokens()
335 .filter(|t| t.kind() == IDENT)
336 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
337 .filter(|t| t != &trait_name)
338 .collect::<Vec<_>>();
339 let has_more_derives = !new_attr_input.is_empty();
341 if has_more_derives {
342 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
343 builder.replace(input.syntax().text_range(), new_attr_input);
345 let attr_range = attr.syntax().text_range();
346 builder.delete(attr_range);
348 if let Some(line_break_range) = attr
350 .next_sibling_or_token()
351 .filter(|t| t.kind() == WHITESPACE)
352 .map(|t| t.text_range())
354 builder.delete(line_break_range);
361 use crate::tests::{check_assist, check_assist_not_applicable};
366 fn add_custom_impl_debug_record_struct() {
368 replace_derive_with_manual_impl,
381 impl core::fmt::Debug for Foo {
382 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
383 f.debug_struct("Foo").field("bar", &self.bar).finish()
390 fn add_custom_impl_debug_tuple_struct() {
392 replace_derive_with_manual_impl,
396 struct Foo(String, usize);
398 r#"struct Foo(String, usize);
400 impl core::fmt::Debug for Foo {
401 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
402 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
409 fn add_custom_impl_debug_empty_struct() {
411 replace_derive_with_manual_impl,
420 impl core::fmt::Debug for Foo {
421 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
422 f.debug_struct("Foo").finish()
429 fn add_custom_impl_debug_enum() {
431 replace_derive_with_manual_impl,
446 impl core::fmt::Debug for Foo {
447 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
449 Self::Bar => write!(f, "Bar"),
450 Self::Baz => write!(f, "Baz"),
458 fn add_custom_impl_default_record_struct() {
460 replace_derive_with_manual_impl,
462 //- minicore: default
473 impl Default for Foo {
474 $0fn default() -> Self {
475 Self { foo: Default::default() }
482 fn add_custom_impl_default_tuple_struct() {
484 replace_derive_with_manual_impl,
486 //- minicore: default
493 impl Default for Foo {
494 $0fn default() -> Self {
495 Self(Default::default())
502 fn add_custom_impl_default_empty_struct() {
504 replace_derive_with_manual_impl,
506 //- minicore: default
513 impl Default for Foo {
514 $0fn default() -> Self {
522 fn add_custom_impl_all() {
524 replace_derive_with_manual_impl,
529 const Baz: usize = 42;
545 const Baz: usize = 42;
556 impl foo::Bar for Foo {
559 const Baz: usize = 42;
571 fn add_custom_impl_for_unique_input() {
573 replace_derive_with_manual_impl,
593 fn add_custom_impl_for_with_visibility_modifier() {
595 replace_derive_with_manual_impl,
615 fn add_custom_impl_when_multiple_inputs() {
617 replace_derive_with_manual_impl,
619 #[derive(Display, Debug$0, Serialize)]
623 #[derive(Display, Serialize)]
634 fn test_ignore_derive_macro_without_input() {
635 check_assist_not_applicable(
636 replace_derive_with_manual_impl,
645 fn test_ignore_if_cursor_on_param() {
646 check_assist_not_applicable(
647 replace_derive_with_manual_impl,
654 check_assist_not_applicable(
655 replace_derive_with_manual_impl,
664 fn test_ignore_if_not_derive() {
665 check_assist_not_applicable(
666 replace_derive_with_manual_impl,
668 #[allow(non_camel_$0case_types)]
675 fn works_at_start_of_file() {
676 cov_mark::check!(outside_of_attr_args);
677 check_assist_not_applicable(
678 replace_derive_with_manual_impl,