]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/add_missing_impl_members.rs
fix: insert whitespaces into assoc items for assist when macro generated
[rust.git] / crates / ide_assists / src / handlers / add_missing_impl_members.rs
1 use hir::HasSource;
2 use ide_db::{helpers::insert_whitespace_into_node::insert_ws_into, traits::resolve_target_trait};
3 use syntax::ast::{self, make, AstNode};
4
5 use crate::{
6     assist_context::{AssistContext, Assists},
7     utils::{
8         add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body, render_snippet,
9         Cursor, DefaultMethods,
10     },
11     AssistId, AssistKind,
12 };
13
14 // Assist: add_impl_missing_members
15 //
16 // Adds scaffold for required impl members.
17 //
18 // ```
19 // trait Trait<T> {
20 //     type X;
21 //     fn foo(&self) -> T;
22 //     fn bar(&self) {}
23 // }
24 //
25 // impl Trait<u32> for () {$0
26 //
27 // }
28 // ```
29 // ->
30 // ```
31 // trait Trait<T> {
32 //     type X;
33 //     fn foo(&self) -> T;
34 //     fn bar(&self) {}
35 // }
36 //
37 // impl Trait<u32> for () {
38 //     $0type X;
39 //
40 //     fn foo(&self) -> u32 {
41 //         todo!()
42 //     }
43 // }
44 // ```
45 pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
46     add_missing_impl_members_inner(
47         acc,
48         ctx,
49         DefaultMethods::No,
50         "add_impl_missing_members",
51         "Implement missing members",
52     )
53 }
54
55 // Assist: add_impl_default_members
56 //
57 // Adds scaffold for overriding default impl members.
58 //
59 // ```
60 // trait Trait {
61 //     type X;
62 //     fn foo(&self);
63 //     fn bar(&self) {}
64 // }
65 //
66 // impl Trait for () {
67 //     type X = ();
68 //     fn foo(&self) {}$0
69 // }
70 // ```
71 // ->
72 // ```
73 // trait Trait {
74 //     type X;
75 //     fn foo(&self);
76 //     fn bar(&self) {}
77 // }
78 //
79 // impl Trait for () {
80 //     type X = ();
81 //     fn foo(&self) {}
82 //
83 //     $0fn bar(&self) {}
84 // }
85 // ```
86 pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
87     add_missing_impl_members_inner(
88         acc,
89         ctx,
90         DefaultMethods::Only,
91         "add_impl_default_members",
92         "Implement default members",
93     )
94 }
95
96 fn add_missing_impl_members_inner(
97     acc: &mut Assists,
98     ctx: &AssistContext,
99     mode: DefaultMethods,
100     assist_id: &'static str,
101     label: &'static str,
102 ) -> Option<()> {
103     let _p = profile::span("add_missing_impl_members_inner");
104     let impl_def = ctx.find_node_at_offset::<ast::Impl>()?;
105     let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?;
106
107     let missing_items = filter_assoc_items(
108         &ctx.sema,
109         &ide_db::traits::get_missing_assoc_items(&ctx.sema, &impl_def),
110         mode,
111     );
112
113     if missing_items.is_empty() {
114         return None;
115     }
116
117     let target = impl_def.syntax().text_range();
118     acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| {
119         let target_scope = ctx.sema.scope(impl_def.syntax());
120         let missing_items = missing_items
121             .into_iter()
122             .map(|it| {
123                 if ctx.sema.hir_file_for(it.syntax()).is_macro() {
124                     if let Some(it) = ast::AssocItem::cast(insert_ws_into(it.syntax().clone())) {
125                         return it;
126                     }
127                 }
128                 it.clone_for_update()
129             })
130             .collect();
131         let (new_impl_def, first_new_item) = add_trait_assoc_items_to_impl(
132             &ctx.sema,
133             missing_items,
134             trait_,
135             impl_def.clone(),
136             target_scope,
137         );
138         match ctx.config.snippet_cap {
139             None => builder.replace(target, new_impl_def.to_string()),
140             Some(cap) => {
141                 let mut cursor = Cursor::Before(first_new_item.syntax());
142                 let placeholder;
143                 if let ast::AssocItem::Fn(func) = &first_new_item {
144                     if try_gen_trait_body(ctx, func, &trait_, &impl_def).is_none() {
145                         if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
146                         {
147                             if m.syntax().text() == "todo!()" {
148                                 placeholder = m;
149                                 cursor = Cursor::Replace(placeholder.syntax());
150                             }
151                         }
152                     }
153                 }
154                 builder.replace_snippet(
155                     cap,
156                     target,
157                     render_snippet(cap, new_impl_def.syntax(), cursor),
158                 )
159             }
160         };
161     })
162 }
163
164 fn try_gen_trait_body(
165     ctx: &AssistContext,
166     func: &ast::Fn,
167     trait_: &hir::Trait,
168     impl_def: &ast::Impl,
169 ) -> Option<()> {
170     let trait_path = make::ext::ident_path(&trait_.name(ctx.db()).to_string());
171     let hir_ty = ctx.sema.resolve_type(&impl_def.self_ty()?)?;
172     let adt = hir_ty.as_adt()?.source(ctx.db())?;
173     gen_trait_fn_body(func, &trait_path, &adt.value)
174 }
175
176 #[cfg(test)]
177 mod tests {
178     use crate::tests::{check_assist, check_assist_not_applicable};
179
180     use super::*;
181
182     #[test]
183     fn test_add_missing_impl_members() {
184         check_assist(
185             add_missing_impl_members,
186             r#"
187 trait Foo {
188     type Output;
189
190     const CONST: usize = 42;
191
192     fn foo(&self);
193     fn bar(&self);
194     fn baz(&self);
195 }
196
197 struct S;
198
199 impl Foo for S {
200     fn bar(&self) {}
201 $0
202 }"#,
203             r#"
204 trait Foo {
205     type Output;
206
207     const CONST: usize = 42;
208
209     fn foo(&self);
210     fn bar(&self);
211     fn baz(&self);
212 }
213
214 struct S;
215
216 impl Foo for S {
217     fn bar(&self) {}
218
219     $0type Output;
220
221     const CONST: usize = 42;
222
223     fn foo(&self) {
224         todo!()
225     }
226
227     fn baz(&self) {
228         todo!()
229     }
230
231 }"#,
232         );
233     }
234
235     #[test]
236     fn test_copied_overriden_members() {
237         check_assist(
238             add_missing_impl_members,
239             r#"
240 trait Foo {
241     fn foo(&self);
242     fn bar(&self) -> bool { true }
243     fn baz(&self) -> u32 { 42 }
244 }
245
246 struct S;
247
248 impl Foo for S {
249     fn bar(&self) {}
250 $0
251 }"#,
252             r#"
253 trait Foo {
254     fn foo(&self);
255     fn bar(&self) -> bool { true }
256     fn baz(&self) -> u32 { 42 }
257 }
258
259 struct S;
260
261 impl Foo for S {
262     fn bar(&self) {}
263
264     fn foo(&self) {
265         ${0:todo!()}
266     }
267
268 }"#,
269         );
270     }
271
272     #[test]
273     fn test_empty_impl_def() {
274         check_assist(
275             add_missing_impl_members,
276             r#"
277 trait Foo { fn foo(&self); }
278 struct S;
279 impl Foo for S { $0 }"#,
280             r#"
281 trait Foo { fn foo(&self); }
282 struct S;
283 impl Foo for S {
284     fn foo(&self) {
285         ${0:todo!()}
286     }
287 }"#,
288         );
289     }
290
291     #[test]
292     fn test_impl_def_without_braces() {
293         check_assist(
294             add_missing_impl_members,
295             r#"
296 trait Foo { fn foo(&self); }
297 struct S;
298 impl Foo for S$0"#,
299             r#"
300 trait Foo { fn foo(&self); }
301 struct S;
302 impl Foo for S {
303     fn foo(&self) {
304         ${0:todo!()}
305     }
306 }"#,
307         );
308     }
309
310     #[test]
311     fn fill_in_type_params_1() {
312         check_assist(
313             add_missing_impl_members,
314             r#"
315 trait Foo<T> { fn foo(&self, t: T) -> &T; }
316 struct S;
317 impl Foo<u32> for S { $0 }"#,
318             r#"
319 trait Foo<T> { fn foo(&self, t: T) -> &T; }
320 struct S;
321 impl Foo<u32> for S {
322     fn foo(&self, t: u32) -> &u32 {
323         ${0:todo!()}
324     }
325 }"#,
326         );
327     }
328
329     #[test]
330     fn fill_in_type_params_2() {
331         check_assist(
332             add_missing_impl_members,
333             r#"
334 trait Foo<T> { fn foo(&self, t: T) -> &T; }
335 struct S;
336 impl<U> Foo<U> for S { $0 }"#,
337             r#"
338 trait Foo<T> { fn foo(&self, t: T) -> &T; }
339 struct S;
340 impl<U> Foo<U> for S {
341     fn foo(&self, t: U) -> &U {
342         ${0:todo!()}
343     }
344 }"#,
345         );
346     }
347
348     #[test]
349     fn test_cursor_after_empty_impl_def() {
350         check_assist(
351             add_missing_impl_members,
352             r#"
353 trait Foo { fn foo(&self); }
354 struct S;
355 impl Foo for S {}$0"#,
356             r#"
357 trait Foo { fn foo(&self); }
358 struct S;
359 impl Foo for S {
360     fn foo(&self) {
361         ${0:todo!()}
362     }
363 }"#,
364         )
365     }
366
367     #[test]
368     fn test_qualify_path_1() {
369         check_assist(
370             add_missing_impl_members,
371             r#"
372 mod foo {
373     pub struct Bar;
374     trait Foo { fn foo(&self, bar: Bar); }
375 }
376 struct S;
377 impl foo::Foo for S { $0 }"#,
378             r#"
379 mod foo {
380     pub struct Bar;
381     trait Foo { fn foo(&self, bar: Bar); }
382 }
383 struct S;
384 impl foo::Foo for S {
385     fn foo(&self, bar: foo::Bar) {
386         ${0:todo!()}
387     }
388 }"#,
389         );
390     }
391
392     #[test]
393     fn test_qualify_path_2() {
394         check_assist(
395             add_missing_impl_members,
396             r#"
397 mod foo {
398     pub mod bar {
399         pub struct Bar;
400         pub trait Foo { fn foo(&self, bar: Bar); }
401     }
402 }
403
404 use foo::bar;
405
406 struct S;
407 impl bar::Foo for S { $0 }"#,
408             r#"
409 mod foo {
410     pub mod bar {
411         pub struct Bar;
412         pub trait Foo { fn foo(&self, bar: Bar); }
413     }
414 }
415
416 use foo::bar;
417
418 struct S;
419 impl bar::Foo for S {
420     fn foo(&self, bar: bar::Bar) {
421         ${0:todo!()}
422     }
423 }"#,
424         );
425     }
426
427     #[test]
428     fn test_qualify_path_generic() {
429         check_assist(
430             add_missing_impl_members,
431             r#"
432 mod foo {
433     pub struct Bar<T>;
434     trait Foo { fn foo(&self, bar: Bar<u32>); }
435 }
436 struct S;
437 impl foo::Foo for S { $0 }"#,
438             r#"
439 mod foo {
440     pub struct Bar<T>;
441     trait Foo { fn foo(&self, bar: Bar<u32>); }
442 }
443 struct S;
444 impl foo::Foo for S {
445     fn foo(&self, bar: foo::Bar<u32>) {
446         ${0:todo!()}
447     }
448 }"#,
449         );
450     }
451
452     #[test]
453     fn test_qualify_path_and_substitute_param() {
454         check_assist(
455             add_missing_impl_members,
456             r#"
457 mod foo {
458     pub struct Bar<T>;
459     trait Foo<T> { fn foo(&self, bar: Bar<T>); }
460 }
461 struct S;
462 impl foo::Foo<u32> for S { $0 }"#,
463             r#"
464 mod foo {
465     pub struct Bar<T>;
466     trait Foo<T> { fn foo(&self, bar: Bar<T>); }
467 }
468 struct S;
469 impl foo::Foo<u32> for S {
470     fn foo(&self, bar: foo::Bar<u32>) {
471         ${0:todo!()}
472     }
473 }"#,
474         );
475     }
476
477     #[test]
478     fn test_substitute_param_no_qualify() {
479         // when substituting params, the substituted param should not be qualified!
480         check_assist(
481             add_missing_impl_members,
482             r#"
483 mod foo {
484     trait Foo<T> { fn foo(&self, bar: T); }
485     pub struct Param;
486 }
487 struct Param;
488 struct S;
489 impl foo::Foo<Param> for S { $0 }"#,
490             r#"
491 mod foo {
492     trait Foo<T> { fn foo(&self, bar: T); }
493     pub struct Param;
494 }
495 struct Param;
496 struct S;
497 impl foo::Foo<Param> for S {
498     fn foo(&self, bar: Param) {
499         ${0:todo!()}
500     }
501 }"#,
502         );
503     }
504
505     #[test]
506     fn test_qualify_path_associated_item() {
507         check_assist(
508             add_missing_impl_members,
509             r#"
510 mod foo {
511     pub struct Bar<T>;
512     impl Bar<T> { type Assoc = u32; }
513     trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
514 }
515 struct S;
516 impl foo::Foo for S { $0 }"#,
517             r#"
518 mod foo {
519     pub struct Bar<T>;
520     impl Bar<T> { type Assoc = u32; }
521     trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
522 }
523 struct S;
524 impl foo::Foo for S {
525     fn foo(&self, bar: foo::Bar<u32>::Assoc) {
526         ${0:todo!()}
527     }
528 }"#,
529         );
530     }
531
532     #[test]
533     fn test_qualify_path_nested() {
534         check_assist(
535             add_missing_impl_members,
536             r#"
537 mod foo {
538     pub struct Bar<T>;
539     pub struct Baz;
540     trait Foo { fn foo(&self, bar: Bar<Baz>); }
541 }
542 struct S;
543 impl foo::Foo for S { $0 }"#,
544             r#"
545 mod foo {
546     pub struct Bar<T>;
547     pub struct Baz;
548     trait Foo { fn foo(&self, bar: Bar<Baz>); }
549 }
550 struct S;
551 impl foo::Foo for S {
552     fn foo(&self, bar: foo::Bar<foo::Baz>) {
553         ${0:todo!()}
554     }
555 }"#,
556         );
557     }
558
559     #[test]
560     fn test_qualify_path_fn_trait_notation() {
561         check_assist(
562             add_missing_impl_members,
563             r#"
564 mod foo {
565     pub trait Fn<Args> { type Output; }
566     trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
567 }
568 struct S;
569 impl foo::Foo for S { $0 }"#,
570             r#"
571 mod foo {
572     pub trait Fn<Args> { type Output; }
573     trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
574 }
575 struct S;
576 impl foo::Foo for S {
577     fn foo(&self, bar: dyn Fn(u32) -> i32) {
578         ${0:todo!()}
579     }
580 }"#,
581         );
582     }
583
584     #[test]
585     fn test_empty_trait() {
586         check_assist_not_applicable(
587             add_missing_impl_members,
588             r#"
589 trait Foo;
590 struct S;
591 impl Foo for S { $0 }"#,
592         )
593     }
594
595     #[test]
596     fn test_ignore_unnamed_trait_members_and_default_methods() {
597         check_assist_not_applicable(
598             add_missing_impl_members,
599             r#"
600 trait Foo {
601     fn (arg: u32);
602     fn valid(some: u32) -> bool { false }
603 }
604 struct S;
605 impl Foo for S { $0 }"#,
606         )
607     }
608
609     #[test]
610     fn test_with_docstring_and_attrs() {
611         check_assist(
612             add_missing_impl_members,
613             r#"
614 #[doc(alias = "test alias")]
615 trait Foo {
616     /// doc string
617     type Output;
618
619     #[must_use]
620     fn foo(&self);
621 }
622 struct S;
623 impl Foo for S {}$0"#,
624             r#"
625 #[doc(alias = "test alias")]
626 trait Foo {
627     /// doc string
628     type Output;
629
630     #[must_use]
631     fn foo(&self);
632 }
633 struct S;
634 impl Foo for S {
635     $0type Output;
636
637     fn foo(&self) {
638         todo!()
639     }
640 }"#,
641         )
642     }
643
644     #[test]
645     fn test_default_methods() {
646         check_assist(
647             add_missing_default_members,
648             r#"
649 trait Foo {
650     type Output;
651
652     const CONST: usize = 42;
653
654     fn valid(some: u32) -> bool { false }
655     fn foo(some: u32) -> bool;
656 }
657 struct S;
658 impl Foo for S { $0 }"#,
659             r#"
660 trait Foo {
661     type Output;
662
663     const CONST: usize = 42;
664
665     fn valid(some: u32) -> bool { false }
666     fn foo(some: u32) -> bool;
667 }
668 struct S;
669 impl Foo for S {
670     $0fn valid(some: u32) -> bool { false }
671 }"#,
672         )
673     }
674
675     #[test]
676     fn test_generic_single_default_parameter() {
677         check_assist(
678             add_missing_impl_members,
679             r#"
680 trait Foo<T = Self> {
681     fn bar(&self, other: &T);
682 }
683
684 struct S;
685 impl Foo for S { $0 }"#,
686             r#"
687 trait Foo<T = Self> {
688     fn bar(&self, other: &T);
689 }
690
691 struct S;
692 impl Foo for S {
693     fn bar(&self, other: &Self) {
694         ${0:todo!()}
695     }
696 }"#,
697         )
698     }
699
700     #[test]
701     fn test_generic_default_parameter_is_second() {
702         check_assist(
703             add_missing_impl_members,
704             r#"
705 trait Foo<T1, T2 = Self> {
706     fn bar(&self, this: &T1, that: &T2);
707 }
708
709 struct S<T>;
710 impl Foo<T> for S<T> { $0 }"#,
711             r#"
712 trait Foo<T1, T2 = Self> {
713     fn bar(&self, this: &T1, that: &T2);
714 }
715
716 struct S<T>;
717 impl Foo<T> for S<T> {
718     fn bar(&self, this: &T, that: &Self) {
719         ${0:todo!()}
720     }
721 }"#,
722         )
723     }
724
725     #[test]
726     fn test_assoc_type_bounds_are_removed() {
727         check_assist(
728             add_missing_impl_members,
729             r#"
730 trait Tr {
731     type Ty: Copy + 'static;
732 }
733
734 impl Tr for ()$0 {
735 }"#,
736             r#"
737 trait Tr {
738     type Ty: Copy + 'static;
739 }
740
741 impl Tr for () {
742     $0type Ty;
743 }"#,
744         )
745     }
746
747     #[test]
748     fn test_whitespace_fixup_preserves_bad_tokens() {
749         check_assist(
750             add_missing_impl_members,
751             r#"
752 trait Tr {
753     fn foo();
754 }
755
756 impl Tr for ()$0 {
757     +++
758 }"#,
759             r#"
760 trait Tr {
761     fn foo();
762 }
763
764 impl Tr for () {
765     fn foo() {
766         ${0:todo!()}
767     }
768     +++
769 }"#,
770         )
771     }
772
773     #[test]
774     fn test_whitespace_fixup_preserves_comments() {
775         check_assist(
776             add_missing_impl_members,
777             r#"
778 trait Tr {
779     fn foo();
780 }
781
782 impl Tr for ()$0 {
783     // very important
784 }"#,
785             r#"
786 trait Tr {
787     fn foo();
788 }
789
790 impl Tr for () {
791     fn foo() {
792         ${0:todo!()}
793     }
794     // very important
795 }"#,
796         )
797     }
798
799     #[test]
800     fn weird_path() {
801         check_assist(
802             add_missing_impl_members,
803             r#"
804 trait Test {
805     fn foo(&self, x: crate)
806 }
807 impl Test for () {
808     $0
809 }
810 "#,
811             r#"
812 trait Test {
813     fn foo(&self, x: crate)
814 }
815 impl Test for () {
816     fn foo(&self, x: crate) {
817         ${0:todo!()}
818     }
819 }
820 "#,
821         )
822     }
823
824     #[test]
825     fn missing_generic_type() {
826         check_assist(
827             add_missing_impl_members,
828             r#"
829 trait Foo<BAR> {
830     fn foo(&self, bar: BAR);
831 }
832 impl Foo for () {
833     $0
834 }
835 "#,
836             r#"
837 trait Foo<BAR> {
838     fn foo(&self, bar: BAR);
839 }
840 impl Foo for () {
841     fn foo(&self, bar: BAR) {
842         ${0:todo!()}
843     }
844 }
845 "#,
846         )
847     }
848
849     #[test]
850     fn does_not_requalify_self_as_crate() {
851         check_assist(
852             add_missing_default_members,
853             r"
854 struct Wrapper<T>(T);
855
856 trait T {
857     fn f(self) -> Wrapper<Self> {
858         Wrapper(self)
859     }
860 }
861
862 impl T for () {
863     $0
864 }
865 ",
866             r"
867 struct Wrapper<T>(T);
868
869 trait T {
870     fn f(self) -> Wrapper<Self> {
871         Wrapper(self)
872     }
873 }
874
875 impl T for () {
876     $0fn f(self) -> Wrapper<Self> {
877         Wrapper(self)
878     }
879 }
880 ",
881         );
882     }
883
884     #[test]
885     fn test_default_body_generation() {
886         check_assist(
887             add_missing_impl_members,
888             r#"
889 //- minicore: default
890 struct Foo(usize);
891
892 impl Default for Foo {
893     $0
894 }
895 "#,
896             r#"
897 struct Foo(usize);
898
899 impl Default for Foo {
900     $0fn default() -> Self {
901         Self(Default::default())
902     }
903 }
904 "#,
905         )
906     }
907
908     #[test]
909     fn test_from_macro() {
910         check_assist(
911             add_missing_default_members,
912             r#"
913 macro_rules! foo {
914     () => {
915         trait FooB {
916             fn foo<'lt>(&'lt self) {}
917         }
918     }
919 }
920 foo!();
921 struct Foo(usize);
922
923 impl FooB for Foo {
924     $0
925 }
926 "#,
927             r#"
928 macro_rules! foo {
929     () => {
930         trait FooB {
931             fn foo<'lt>(&'lt self) {}
932         }
933     }
934 }
935 foo!();
936 struct Foo(usize);
937
938 impl FooB for Foo {
939     $0fn foo< 'lt>(& 'lt self){}
940
941 }
942 "#,
943         )
944     }
945 }