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(_) => None,
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<()> {
282 fn gen_default_call() -> ast::Expr {
283 let trait_name = make::ext::ident_path("Default");
284 let method_name = make::ext::ident_path("default");
285 let fn_name = make::expr_path(make::path_concat(trait_name, method_name));
286 make::expr_call(fn_name, make::arg_list(None))
289 // `Debug` cannot be derived for unions, so no default impl can be provided.
290 ast::Adt::Union(_) => None,
291 // Deriving `Debug` for enums is not stable yet.
292 ast::Adt::Enum(_) => None,
293 ast::Adt::Struct(strukt) => {
294 let expr = match strukt.field_list() {
295 Some(ast::FieldList::RecordFieldList(field_list)) => {
296 let mut fields = vec![];
297 for field in field_list.fields() {
298 let method_call = gen_default_call();
299 let name_ref = make::name_ref(&field.name()?.to_string());
300 let field = make::record_expr_field(name_ref, Some(method_call));
303 let struct_name = make::ext::ident_path("Self");
304 let fields = make::record_expr_field_list(fields);
305 make::record_expr(struct_name, fields).into()
307 Some(ast::FieldList::TupleFieldList(field_list)) => {
308 let struct_name = make::expr_path(make::ext::ident_path("Self"));
309 let fields = field_list.fields().map(|_| gen_default_call());
310 make::expr_call(struct_name, make::arg_list(fields))
313 let struct_name = make::ext::ident_path("Self");
314 let fields = make::record_expr_field_list(None);
315 make::record_expr(struct_name, fields).into()
318 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
319 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
325 builder: &mut AssistBuilder,
326 input: &ast::TokenTree,
327 trait_name: &ast::NameRef,
330 let trait_name = trait_name.text();
331 let new_attr_input = input
333 .descendants_with_tokens()
334 .filter(|t| t.kind() == IDENT)
335 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
336 .filter(|t| t != &trait_name)
337 .collect::<Vec<_>>();
338 let has_more_derives = !new_attr_input.is_empty();
340 if has_more_derives {
341 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
342 builder.replace(input.syntax().text_range(), new_attr_input);
344 let attr_range = attr.syntax().text_range();
345 builder.delete(attr_range);
347 if let Some(line_break_range) = attr
349 .next_sibling_or_token()
350 .filter(|t| t.kind() == WHITESPACE)
351 .map(|t| t.text_range())
353 builder.delete(line_break_range);
360 use crate::tests::{check_assist, check_assist_not_applicable};
365 fn add_custom_impl_debug_record_struct() {
367 replace_derive_with_manual_impl,
380 impl core::fmt::Debug for Foo {
381 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
382 f.debug_struct("Foo").field("bar", &self.bar).finish()
389 fn add_custom_impl_debug_tuple_struct() {
391 replace_derive_with_manual_impl,
395 struct Foo(String, usize);
397 r#"struct Foo(String, usize);
399 impl core::fmt::Debug for Foo {
400 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
408 fn add_custom_impl_debug_empty_struct() {
410 replace_derive_with_manual_impl,
419 impl core::fmt::Debug for Foo {
420 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
421 f.debug_struct("Foo").finish()
428 fn add_custom_impl_debug_enum() {
430 replace_derive_with_manual_impl,
445 impl core::fmt::Debug for Foo {
446 $0fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
448 Self::Bar => write!(f, "Bar"),
449 Self::Baz => write!(f, "Baz"),
457 fn add_custom_impl_default_record_struct() {
459 replace_derive_with_manual_impl,
461 //- minicore: default
472 impl Default for Foo {
473 $0fn default() -> Self {
474 Self { foo: Default::default() }
481 fn add_custom_impl_default_tuple_struct() {
483 replace_derive_with_manual_impl,
485 //- minicore: default
492 impl Default for Foo {
493 $0fn default() -> Self {
494 Self(Default::default())
501 fn add_custom_impl_default_empty_struct() {
503 replace_derive_with_manual_impl,
505 //- minicore: default
512 impl Default for Foo {
513 $0fn default() -> Self {
521 fn add_custom_impl_all() {
523 replace_derive_with_manual_impl,
528 const Baz: usize = 42;
544 const Baz: usize = 42;
555 impl foo::Bar for Foo {
558 const Baz: usize = 42;
570 fn add_custom_impl_for_unique_input() {
572 replace_derive_with_manual_impl,
592 fn add_custom_impl_for_with_visibility_modifier() {
594 replace_derive_with_manual_impl,
614 fn add_custom_impl_when_multiple_inputs() {
616 replace_derive_with_manual_impl,
618 #[derive(Display, Debug$0, Serialize)]
622 #[derive(Display, Serialize)]
633 fn test_ignore_derive_macro_without_input() {
634 check_assist_not_applicable(
635 replace_derive_with_manual_impl,
644 fn test_ignore_if_cursor_on_param() {
645 check_assist_not_applicable(
646 replace_derive_with_manual_impl,
653 check_assist_not_applicable(
654 replace_derive_with_manual_impl,
663 fn test_ignore_if_not_derive() {
664 check_assist_not_applicable(
665 replace_derive_with_manual_impl,
667 #[allow(non_camel_$0case_types)]
674 fn works_at_start_of_file() {
675 cov_mark::check!(outside_of_attr_args);
676 check_assist_not_applicable(
677 replace_derive_with_manual_impl,