]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_derive_with_manual_impl.rs
Merge #8600
[rust.git] / crates / ide_assists / src / handlers / replace_derive_with_manual_impl.rs
1 use hir::ModuleDef;
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::{
6     ast::{self, make, AstNode, NameOwner},
7     SyntaxKind::{IDENT, WHITESPACE},
8 };
9
10 use crate::{
11     assist_context::{AssistBuilder, AssistContext, Assists},
12     utils::{
13         add_trait_assoc_items_to_impl, filter_assoc_items, generate_trait_impl_text,
14         render_snippet, Cursor, DefaultMethods,
15     },
16     AssistId, AssistKind,
17 };
18
19 // Assist: replace_derive_with_manual_impl
20 //
21 // Converts a `derive` impl into a manual one.
22 //
23 // ```
24 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
25 // #[derive(Deb$0ug, Display)]
26 // struct S;
27 // ```
28 // ->
29 // ```
30 // # trait Debug { fn fmt(&self, f: &mut Formatter) -> Result<()>; }
31 // #[derive(Display)]
32 // struct S;
33 //
34 // impl Debug for S {
35 //     fn fmt(&self, f: &mut Formatter) -> Result<()> {
36 //         ${0:todo!()}
37 //     }
38 // }
39 // ```
40 pub(crate) fn replace_derive_with_manual_impl(
41     acc: &mut Assists,
42     ctx: &AssistContext,
43 ) -> Option<()> {
44     let attr = ctx.find_node_at_offset::<ast::Attr>()?;
45     let (name, args) = attr.as_simple_call()?;
46     if name != "derive" {
47         return None;
48     }
49
50     if !args.syntax().text_range().contains(ctx.offset()) {
51         cov_mark::hit!(outside_of_attr_args);
52         return None;
53     }
54
55     let trait_token = args.syntax().token_at_offset(ctx.offset()).find(|t| t.kind() == IDENT)?;
56     let trait_name = trait_token.text();
57
58     let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
59
60     let current_module = ctx.sema.scope(adt.syntax()).module()?;
61     let current_crate = current_module.krate();
62
63     let found_traits = items_locator::items_with_name(
64         &ctx.sema,
65         current_crate,
66         NameToImport::Exact(trait_name.to_string()),
67         items_locator::AssocItemSearch::Exclude,
68         Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT),
69     )
70     .filter_map(|item| match ModuleDef::from(item.as_module_def_id()?) {
71         ModuleDef::Trait(trait_) => Some(trait_),
72         _ => None,
73     })
74     .flat_map(|trait_| {
75         current_module
76             .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_))
77             .as_ref()
78             .map(mod_path_to_ast)
79             .zip(Some(trait_))
80     });
81
82     let mut no_traits_found = true;
83     for (trait_path, trait_) in found_traits.inspect(|_| no_traits_found = false) {
84         add_assist(acc, ctx, &attr, &args, &trait_path, Some(trait_), &adt)?;
85     }
86     if no_traits_found {
87         let trait_path = make::path_unqualified(make::path_segment(make::name_ref(trait_name)));
88         add_assist(acc, ctx, &attr, &args, &trait_path, None, &adt)?;
89     }
90     Some(())
91 }
92
93 fn add_assist(
94     acc: &mut Assists,
95     ctx: &AssistContext,
96     attr: &ast::Attr,
97     input: &ast::TokenTree,
98     trait_path: &ast::Path,
99     trait_: Option<hir::Trait>,
100     adt: &ast::Adt,
101 ) -> Option<()> {
102     let target = attr.syntax().text_range();
103     let annotated_name = adt.name()?;
104     let label = format!("Convert to manual `impl {} for {}`", trait_path, annotated_name);
105     let trait_name = trait_path.segment().and_then(|seg| seg.name_ref())?;
106
107     acc.add(
108         AssistId("replace_derive_with_manual_impl", AssistKind::Refactor),
109         label,
110         target,
111         |builder| {
112             let insert_pos = adt.syntax().text_range().end();
113             let impl_def_with_items =
114                 impl_def_from_trait(&ctx.sema, &annotated_name, trait_, trait_path);
115             update_attribute(builder, &input, &trait_name, &attr);
116             let trait_path = format!("{}", trait_path);
117             match (ctx.config.snippet_cap, impl_def_with_items) {
118                 (None, _) => {
119                     builder.insert(insert_pos, generate_trait_impl_text(adt, &trait_path, ""))
120                 }
121                 (Some(cap), None) => builder.insert_snippet(
122                     cap,
123                     insert_pos,
124                     generate_trait_impl_text(adt, &trait_path, "    $0"),
125                 ),
126                 (Some(cap), Some((impl_def, first_assoc_item))) => {
127                     let mut cursor = Cursor::Before(first_assoc_item.syntax());
128                     let placeholder;
129                     if let ast::AssocItem::Fn(ref func) = first_assoc_item {
130                         if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
131                         {
132                             if m.syntax().text() == "todo!()" {
133                                 placeholder = m;
134                                 cursor = Cursor::Replace(placeholder.syntax());
135                             }
136                         }
137                     }
138
139                     builder.insert_snippet(
140                         cap,
141                         insert_pos,
142                         format!("\n\n{}", render_snippet(cap, impl_def.syntax(), cursor)),
143                     )
144                 }
145             };
146         },
147     )
148 }
149
150 fn impl_def_from_trait(
151     sema: &hir::Semantics<ide_db::RootDatabase>,
152     annotated_name: &ast::Name,
153     trait_: Option<hir::Trait>,
154     trait_path: &ast::Path,
155 ) -> Option<(ast::Impl, ast::AssocItem)> {
156     let trait_ = trait_?;
157     let target_scope = sema.scope(annotated_name.syntax());
158     let trait_items = filter_assoc_items(sema.db, &trait_.items(sema.db), DefaultMethods::No);
159     if trait_items.is_empty() {
160         return None;
161     }
162     let impl_def = make::impl_trait(
163         trait_path.clone(),
164         make::path_unqualified(make::path_segment(make::name_ref(&annotated_name.text()))),
165     );
166     let (impl_def, first_assoc_item) =
167         add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
168     Some((impl_def, first_assoc_item))
169 }
170
171 fn update_attribute(
172     builder: &mut AssistBuilder,
173     input: &ast::TokenTree,
174     trait_name: &ast::NameRef,
175     attr: &ast::Attr,
176 ) {
177     let trait_name = trait_name.text();
178     let new_attr_input = input
179         .syntax()
180         .descendants_with_tokens()
181         .filter(|t| t.kind() == IDENT)
182         .filter_map(|t| t.into_token().map(|t| t.text().to_string()))
183         .filter(|t| t != &trait_name)
184         .collect::<Vec<_>>();
185     let has_more_derives = !new_attr_input.is_empty();
186
187     if has_more_derives {
188         let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
189         builder.replace(input.syntax().text_range(), new_attr_input);
190     } else {
191         let attr_range = attr.syntax().text_range();
192         builder.delete(attr_range);
193
194         if let Some(line_break_range) = attr
195             .syntax()
196             .next_sibling_or_token()
197             .filter(|t| t.kind() == WHITESPACE)
198             .map(|t| t.text_range())
199         {
200             builder.delete(line_break_range);
201         }
202     }
203 }
204
205 #[cfg(test)]
206 mod tests {
207     use crate::tests::{check_assist, check_assist_not_applicable};
208
209     use super::*;
210
211     #[test]
212     fn add_custom_impl_debug() {
213         check_assist(
214             replace_derive_with_manual_impl,
215             r#"
216 mod fmt {
217     pub struct Error;
218     pub type Result = Result<(), Error>;
219     pub struct Formatter<'a>;
220     pub trait Debug {
221         fn fmt(&self, f: &mut Formatter<'_>) -> Result;
222     }
223 }
224
225 #[derive(Debu$0g)]
226 struct Foo {
227     bar: String,
228 }
229 "#,
230             r#"
231 mod fmt {
232     pub struct Error;
233     pub type Result = Result<(), Error>;
234     pub struct Formatter<'a>;
235     pub trait Debug {
236         fn fmt(&self, f: &mut Formatter<'_>) -> Result;
237     }
238 }
239
240 struct Foo {
241     bar: String,
242 }
243
244 impl fmt::Debug for Foo {
245     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246         ${0:todo!()}
247     }
248 }
249 "#,
250         )
251     }
252     #[test]
253     fn add_custom_impl_all() {
254         check_assist(
255             replace_derive_with_manual_impl,
256             r#"
257 mod foo {
258     pub trait Bar {
259         type Qux;
260         const Baz: usize = 42;
261         const Fez: usize;
262         fn foo();
263         fn bar() {}
264     }
265 }
266
267 #[derive($0Bar)]
268 struct Foo {
269     bar: String,
270 }
271 "#,
272             r#"
273 mod foo {
274     pub trait Bar {
275         type Qux;
276         const Baz: usize = 42;
277         const Fez: usize;
278         fn foo();
279         fn bar() {}
280     }
281 }
282
283 struct Foo {
284     bar: String,
285 }
286
287 impl foo::Bar for Foo {
288     $0type Qux;
289
290     const Baz: usize = 42;
291
292     const Fez: usize;
293
294     fn foo() {
295         todo!()
296     }
297 }
298 "#,
299         )
300     }
301     #[test]
302     fn add_custom_impl_for_unique_input() {
303         check_assist(
304             replace_derive_with_manual_impl,
305             r#"
306 #[derive(Debu$0g)]
307 struct Foo {
308     bar: String,
309 }
310             "#,
311             r#"
312 struct Foo {
313     bar: String,
314 }
315
316 impl Debug for Foo {
317     $0
318 }
319             "#,
320         )
321     }
322
323     #[test]
324     fn add_custom_impl_for_with_visibility_modifier() {
325         check_assist(
326             replace_derive_with_manual_impl,
327             r#"
328 #[derive(Debug$0)]
329 pub struct Foo {
330     bar: String,
331 }
332             "#,
333             r#"
334 pub struct Foo {
335     bar: String,
336 }
337
338 impl Debug for Foo {
339     $0
340 }
341             "#,
342         )
343     }
344
345     #[test]
346     fn add_custom_impl_when_multiple_inputs() {
347         check_assist(
348             replace_derive_with_manual_impl,
349             r#"
350 #[derive(Display, Debug$0, Serialize)]
351 struct Foo {}
352             "#,
353             r#"
354 #[derive(Display, Serialize)]
355 struct Foo {}
356
357 impl Debug for Foo {
358     $0
359 }
360             "#,
361         )
362     }
363
364     #[test]
365     fn test_ignore_derive_macro_without_input() {
366         check_assist_not_applicable(
367             replace_derive_with_manual_impl,
368             r#"
369 #[derive($0)]
370 struct Foo {}
371             "#,
372         )
373     }
374
375     #[test]
376     fn test_ignore_if_cursor_on_param() {
377         check_assist_not_applicable(
378             replace_derive_with_manual_impl,
379             r#"
380 #[derive$0(Debug)]
381 struct Foo {}
382             "#,
383         );
384
385         check_assist_not_applicable(
386             replace_derive_with_manual_impl,
387             r#"
388 #[derive(Debug)$0]
389 struct Foo {}
390             "#,
391         )
392     }
393
394     #[test]
395     fn test_ignore_if_not_derive() {
396         check_assist_not_applicable(
397             replace_derive_with_manual_impl,
398             r#"
399 #[allow(non_camel_$0case_types)]
400 struct Foo {}
401             "#,
402         )
403     }
404
405     #[test]
406     fn works_at_start_of_file() {
407         cov_mark::check!(outside_of_attr_args);
408         check_assist_not_applicable(
409             replace_derive_with_manual_impl,
410             r#"
411 $0#[derive(Debug)]
412 struct S;
413             "#,
414         );
415     }
416 }