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 // need to know what kind of derive this is: if it's Derive Debug, special case it.
133 // the name of the struct
134 // list of fields of the struct
135 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
137 if m.syntax().text() == "todo!()" {
139 cursor = Cursor::Replace(placeholder.syntax());
144 builder.insert_snippet(
147 format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
155 fn impl_def_from_trait(
156 sema: &hir::Semantics<ide_db::RootDatabase>,
158 annotated_name: &ast::Name,
159 trait_: Option<hir::Trait>,
160 trait_path: &ast::Path,
161 ) -> Option<(ast::Impl, ast::AssocItem)> {
162 let trait_ = trait_?;
163 let target_scope = sema.scope(annotated_name.syntax());
164 let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
165 if trait_items.is_empty() {
169 make::impl_trait(trait_path.clone(), make::ext::ident_path(&annotated_name.text()));
170 let (impl_def, first_assoc_item) =
171 add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
173 if let ast::AssocItem::Fn(func) = &first_assoc_item {
174 if trait_path.segment().unwrap().name_ref().unwrap().text() == "Debug" {
175 gen_debug_impl(adt, func, annotated_name);
178 Some((impl_def, first_assoc_item))
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 if let Some(list) = enum_.variant_list() {
186 let mut arms = vec![];
187 for variant in list.variants() {
188 let name = variant.name().unwrap();
190 // => Self::<Variant>
191 let first = make::ext::ident_path("Self");
192 let second = make::ext::ident_path(&format!("{}", name));
193 let pat = make::path_pat(make::path_concat(first, second));
195 // => write!(f, "<Variant>")
196 let target = make::expr_path(make::ext::ident_path("f").into());
197 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
198 let args = make::arg_list(vec![target, fmt_string]);
199 let target = make::expr_path(make::ext::ident_path("write"));
200 let expr = make::expr_macro_call(target, args);
202 // => Self::<Variant> => write!(f, "<Variant>"),
203 arms.push(make::match_arm(Some(pat.into()), None, expr.into()));
206 // => match self { ... }
207 let f_path = make::expr_path(make::ext::ident_path("self"));
208 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
209 let expr = make::expr_match(f_path, list);
211 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
212 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
215 ast::Adt::Struct(strukt) => match strukt.field_list() {
216 Some(ast::FieldList::RecordFieldList(field_list)) => {
217 let name = format!("\"{}\"", annotated_name);
218 let args = make::arg_list(Some(make::expr_literal(&name).into()));
219 let target = make::expr_path(make::ext::ident_path("f"));
220 let mut expr = make::expr_method_call(target, "debug_struct", args);
221 for field in field_list.fields() {
222 if let Some(name) = field.name() {
223 let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
224 let f_path = make::expr_path(make::ext::ident_path("self"));
225 let f_path = make::expr_ref(f_path, false);
226 let f_path = make::expr_field(f_path, &format!("{}", name)).into();
227 let args = make::arg_list(vec![f_name, f_path]);
228 expr = make::expr_method_call(expr, "field", args);
231 let expr = make::expr_method_call(expr, "finish", make::arg_list(None));
232 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
233 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
235 Some(ast::FieldList::TupleFieldList(field_list)) => {
236 let name = format!("\"{}\"", annotated_name);
237 let args = make::arg_list(Some(make::expr_literal(&name).into()));
238 let target = make::expr_path(make::ext::ident_path("f"));
239 let mut expr = make::expr_method_call(target, "debug_tuple", args);
240 for (idx, _) in field_list.fields().enumerate() {
241 let f_path = make::expr_path(make::ext::ident_path("self"));
242 let f_path = make::expr_ref(f_path, false);
243 let f_path = make::expr_field(f_path, &format!("{}", idx)).into();
244 let args = make::arg_list(Some(f_path));
245 expr = make::expr_method_call(expr, "field", args);
247 let expr = make::expr_method_call(expr, "finish", make::arg_list(None));
248 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
249 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
252 let name = format!("\"{}\"", annotated_name);
253 let args = make::arg_list(Some(make::expr_literal(&name).into()));
254 let target = make::expr_path(make::ext::ident_path("f"));
255 let expr = make::expr_method_call(target, "debug_struct", args);
256 let expr = make::expr_method_call(expr, "finish", make::arg_list(None));
257 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
258 ted::replace(func.body().unwrap().syntax(), body.clone_for_update().syntax());
265 builder: &mut AssistBuilder,
266 input: &ast::TokenTree,
267 trait_name: &ast::NameRef,
270 let trait_name = trait_name.text();
271 let new_attr_input = input
273 .descendants_with_tokens()
274 .filter(|t| t.kind() == IDENT)
275 .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
276 .filter(|t| t != &trait_name)
277 .collect::<Vec<_>>();
278 let has_more_derives = !new_attr_input.is_empty();
280 if has_more_derives {
281 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
282 builder.replace(input.syntax().text_range(), new_attr_input);
284 let attr_range = attr.syntax().text_range();
285 builder.delete(attr_range);
287 if let Some(line_break_range) = attr
289 .next_sibling_or_token()
290 .filter(|t| t.kind() == WHITESPACE)
291 .map(|t| t.text_range())
293 builder.delete(line_break_range);
300 use crate::tests::{check_assist, check_assist_not_applicable};
305 fn add_custom_impl_debug_record_struct() {
307 replace_derive_with_manual_impl,
311 pub type Result = Result<(), Error>;
312 pub struct Formatter<'a>;
314 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
326 pub type Result = Result<(), Error>;
327 pub struct Formatter<'a>;
329 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
337 impl fmt::Debug for Foo {
338 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 f.debug_struct("Foo").field("bar", &self.bar).finish()
346 fn add_custom_impl_debug_tuple_struct() {
348 replace_derive_with_manual_impl,
352 pub type Result = Result<(), Error>;
353 pub struct Formatter<'a>;
355 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
360 struct Foo(String, usize);
365 pub type Result = Result<(), Error>;
366 pub struct Formatter<'a>;
368 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
372 struct Foo(String, usize);
374 impl fmt::Debug for Foo {
375 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.debug_tuple("Foo").field(&self.0).field(&self.1).finish()
383 fn add_custom_impl_debug_empty_struct() {
385 replace_derive_with_manual_impl,
389 pub type Result = Result<(), Error>;
390 pub struct Formatter<'a>;
392 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
402 pub type Result = Result<(), Error>;
403 pub struct Formatter<'a>;
405 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
411 impl fmt::Debug for Foo {
412 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 f.debug_struct("Foo").finish()
420 fn add_custom_impl_debug_enum() {
422 replace_derive_with_manual_impl,
426 pub type Result = Result<(), Error>;
427 pub struct Formatter<'a>;
429 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
442 pub type Result = Result<(), Error>;
443 pub struct Formatter<'a>;
445 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
454 impl fmt::Debug for Foo {
455 $0fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 Self::Bar => write!(f, "Bar"),
458 Self::Baz => write!(f, "Baz"),
466 fn add_custom_impl_all() {
468 replace_derive_with_manual_impl,
473 const Baz: usize = 42;
489 const Baz: usize = 42;
500 impl foo::Bar for Foo {
503 const Baz: usize = 42;
515 fn add_custom_impl_for_unique_input() {
517 replace_derive_with_manual_impl,
537 fn add_custom_impl_for_with_visibility_modifier() {
539 replace_derive_with_manual_impl,
559 fn add_custom_impl_when_multiple_inputs() {
561 replace_derive_with_manual_impl,
563 #[derive(Display, Debug$0, Serialize)]
567 #[derive(Display, Serialize)]
578 fn test_ignore_derive_macro_without_input() {
579 check_assist_not_applicable(
580 replace_derive_with_manual_impl,
589 fn test_ignore_if_cursor_on_param() {
590 check_assist_not_applicable(
591 replace_derive_with_manual_impl,
598 check_assist_not_applicable(
599 replace_derive_with_manual_impl,
608 fn test_ignore_if_not_derive() {
609 check_assist_not_applicable(
610 replace_derive_with_manual_impl,
612 #[allow(non_camel_$0case_types)]
619 fn works_at_start_of_file() {
620 cov_mark::check!(outside_of_attr_args);
621 check_assist_not_applicable(
622 replace_derive_with_manual_impl,