]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/trait_impl.rs
Merge #10477 #10482
[rust.git] / crates / ide_completion / src / completions / trait_impl.rs
1 //! Completion for associated items in a trait implementation.
2 //!
3 //! This module adds the completion items related to implementing associated
4 //! items within an `impl Trait for Struct` block. The current context node
5 //! must be within either a `FN`, `TYPE_ALIAS`, or `CONST` node
6 //! and an direct child of an `IMPL`.
7 //!
8 //! # Examples
9 //!
10 //! Considering the following trait `impl`:
11 //!
12 //! ```ignore
13 //! trait SomeTrait {
14 //!     fn foo();
15 //! }
16 //!
17 //! impl SomeTrait for () {
18 //!     fn f$0
19 //! }
20 //! ```
21 //!
22 //! may result in the completion of the following method:
23 //!
24 //! ```ignore
25 //! # trait SomeTrait {
26 //! #    fn foo();
27 //! # }
28 //!
29 //! impl SomeTrait for () {
30 //!     fn foo() {}$0
31 //! }
32 //! ```
33
34 use hir::{self, HasAttrs, HasSource};
35 use ide_db::{path_transform::PathTransform, traits::get_missing_assoc_items, SymbolKind};
36 use syntax::{
37     ast::{self, edit_in_place::AttrsOwnerEdit},
38     display::function_declaration,
39     AstNode, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, T,
40 };
41 use text_edit::TextEdit;
42
43 use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions};
44
45 #[derive(Debug, PartialEq, Eq)]
46 enum ImplCompletionKind {
47     All,
48     Fn,
49     TypeAlias,
50     Const,
51 }
52
53 pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
54     if let Some((kind, trigger, impl_def)) = completion_match(ctx.token.clone()) {
55         if let Some(hir_impl) = ctx.sema.to_def(&impl_def) {
56             get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
57                 hir::AssocItem::Function(fn_item)
58                     if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
59                 {
60                     add_function_impl(&trigger, acc, ctx, fn_item, hir_impl)
61                 }
62                 hir::AssocItem::TypeAlias(type_item)
63                     if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
64                 {
65                     add_type_alias_impl(&trigger, acc, ctx, type_item)
66                 }
67                 hir::AssocItem::Const(const_item)
68                     if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
69                 {
70                     add_const_impl(&trigger, acc, ctx, const_item, hir_impl)
71                 }
72                 _ => {}
73             });
74         }
75     }
76 }
77
78 fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
79     // For keyword without name like `impl .. { fn $0 }`, the current position is inside
80     // the whitespace token, which is outside `FN` syntax node.
81     // We need to follow the previous token in this case.
82     if token.kind() == SyntaxKind::WHITESPACE {
83         token = token.prev_token()?;
84     }
85
86     let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
87     let impl_item_offset = match token.kind() {
88         // `impl .. { const $0 }`
89         // ERROR      0
90         //   CONST_KW <- *
91         T![const] => 0,
92         // `impl .. { fn/type $0 }`
93         // FN/TYPE_ALIAS  0
94         //   FN_KW        <- *
95         T![fn] | T![type] => 0,
96         // `impl .. { fn/type/const foo$0 }`
97         // FN/TYPE_ALIAS/CONST  1
98         //  NAME                0
99         //    IDENT             <- *
100         SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
101         // `impl .. { foo$0 }`
102         // MACRO_CALL       3
103         //  PATH            2
104         //    PATH_SEGMENT  1
105         //      NAME_REF    0
106         //        IDENT     <- *
107         SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
108         _ => return None,
109     };
110
111     let impl_item = token.ancestors().nth(impl_item_offset)?;
112     // Must directly belong to an impl block.
113     // IMPL
114     //   ASSOC_ITEM_LIST
115     //     <item>
116     let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
117     let kind = match impl_item.kind() {
118         // `impl ... { const $0 fn/type/const }`
119         _ if token.kind() == T![const] => ImplCompletionKind::Const,
120         SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
121         SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
122         SyntaxKind::FN => ImplCompletionKind::Fn,
123         SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
124         _ => return None,
125     };
126     Some((kind, impl_item, impl_def))
127 }
128
129 fn add_function_impl(
130     fn_def_node: &SyntaxNode,
131     acc: &mut Completions,
132     ctx: &CompletionContext,
133     func: hir::Function,
134     impl_def: hir::Impl,
135 ) {
136     let fn_name = func.name(ctx.db).to_string();
137
138     let label = if func.assoc_fn_params(ctx.db).is_empty() {
139         format!("fn {}()", fn_name)
140     } else {
141         format!("fn {}(..)", fn_name)
142     };
143
144     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
145     item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
146
147     let completion_kind = if func.self_param(ctx.db).is_some() {
148         CompletionItemKind::Method
149     } else {
150         CompletionItemKind::SymbolKind(SymbolKind::Function)
151     };
152     let range = replacement_range(ctx, fn_def_node);
153
154     if let Some(source) = func.source(ctx.db) {
155         let assoc_item = ast::AssocItem::Fn(source.value);
156         if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
157             let transformed_fn = match transformed_item {
158                 ast::AssocItem::Fn(func) => func,
159                 _ => unreachable!(),
160             };
161
162             let function_decl = function_declaration(&transformed_fn);
163             match ctx.config.snippet_cap {
164                 Some(cap) => {
165                     let snippet = format!("{} {{\n    $0\n}}", function_decl);
166                     item.snippet_edit(cap, TextEdit::replace(range, snippet));
167                 }
168                 None => {
169                     let header = format!("{} {{", function_decl);
170                     item.text_edit(TextEdit::replace(range, header));
171                 }
172             };
173             item.kind(completion_kind);
174             item.add_to(acc);
175         }
176     }
177 }
178
179 /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
180 fn get_transformed_assoc_item(
181     ctx: &CompletionContext,
182     assoc_item: ast::AssocItem,
183     impl_def: hir::Impl,
184 ) -> Option<ast::AssocItem> {
185     let assoc_item = assoc_item.clone_for_update();
186     let trait_ = impl_def.trait_(ctx.db)?;
187     let source_scope = &ctx.sema.scope_for_def(trait_);
188     let target_scope = &ctx.sema.scope(ctx.sema.source(impl_def)?.syntax().value);
189     let transform = PathTransform::trait_impl(
190         target_scope,
191         source_scope,
192         trait_,
193         impl_def.source(ctx.db)?.value,
194     );
195
196     transform.apply(assoc_item.syntax());
197     if let ast::AssocItem::Fn(func) = &assoc_item {
198         func.remove_attrs_and_docs()
199     }
200     Some(assoc_item)
201 }
202
203 fn add_type_alias_impl(
204     type_def_node: &SyntaxNode,
205     acc: &mut Completions,
206     ctx: &CompletionContext,
207     type_alias: hir::TypeAlias,
208 ) {
209     let alias_name = type_alias.name(ctx.db).to_string();
210
211     let snippet = format!("type {} = ", alias_name);
212
213     let range = replacement_range(ctx, type_def_node);
214     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
215     item.text_edit(TextEdit::replace(range, snippet))
216         .lookup_by(alias_name)
217         .kind(SymbolKind::TypeAlias)
218         .set_documentation(type_alias.docs(ctx.db));
219     item.add_to(acc);
220 }
221
222 fn add_const_impl(
223     const_def_node: &SyntaxNode,
224     acc: &mut Completions,
225     ctx: &CompletionContext,
226     const_: hir::Const,
227     impl_def: hir::Impl,
228 ) {
229     let const_name = const_.name(ctx.db).map(|n| n.to_string());
230
231     if let Some(const_name) = const_name {
232         if let Some(source) = const_.source(ctx.db) {
233             let assoc_item = ast::AssocItem::Const(source.value);
234             if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
235                 let transformed_const = match transformed_item {
236                     ast::AssocItem::Const(const_) => const_,
237                     _ => unreachable!(),
238                 };
239
240                 let snippet = make_const_compl_syntax(&transformed_const);
241
242                 let range = replacement_range(ctx, const_def_node);
243                 let mut item =
244                     CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
245                 item.text_edit(TextEdit::replace(range, snippet))
246                     .lookup_by(const_name)
247                     .kind(SymbolKind::Const)
248                     .set_documentation(const_.docs(ctx.db));
249                 item.add_to(acc);
250             }
251         }
252     }
253 }
254
255 fn make_const_compl_syntax(const_: &ast::Const) -> String {
256     const_.remove_attrs_and_docs();
257
258     let const_start = const_.syntax().text_range().start();
259     let const_end = const_.syntax().text_range().end();
260
261     let start =
262         const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
263
264     let end = const_
265         .syntax()
266         .children_with_tokens()
267         .find(|s| s.kind() == T![;] || s.kind() == T![=])
268         .map_or(const_end, |f| f.text_range().start());
269
270     let len = end - start;
271     let range = TextRange::new(0.into(), len);
272
273     let syntax = const_.syntax().text().slice(range).to_string();
274
275     format!("{} = ", syntax.trim_end())
276 }
277
278 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
279     let first_child = item
280         .children_with_tokens()
281         .find(|child| {
282             !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
283         })
284         .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
285
286     TextRange::new(first_child.text_range().start(), ctx.source_range().end())
287 }
288
289 #[cfg(test)]
290 mod tests {
291     use expect_test::{expect, Expect};
292
293     use crate::{
294         tests::{check_edit, filtered_completion_list},
295         CompletionKind,
296     };
297
298     fn check(ra_fixture: &str, expect: Expect) {
299         let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
300         expect.assert_eq(&actual)
301     }
302
303     #[test]
304     fn no_completion_inside_fn() {
305         check(
306             r"
307 trait Test { fn test(); fn test2(); }
308 struct T;
309
310 impl Test for T {
311     fn test() {
312         t$0
313     }
314 }
315 ",
316             expect![[""]],
317         );
318
319         check(
320             r"
321 trait Test { fn test(); fn test2(); }
322 struct T;
323
324 impl Test for T {
325     fn test() {
326         fn t$0
327     }
328 }
329 ",
330             expect![[""]],
331         );
332
333         check(
334             r"
335 trait Test { fn test(); fn test2(); }
336 struct T;
337
338 impl Test for T {
339     fn test() {
340         fn $0
341     }
342 }
343 ",
344             expect![[""]],
345         );
346
347         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
348         check(
349             r"
350 trait Test { fn test(); fn test2(); }
351 struct T;
352
353 impl Test for T {
354     fn test() {
355         foo.$0
356     }
357 }
358 ",
359             expect![[""]],
360         );
361
362         check(
363             r"
364 trait Test { fn test(_: i32); fn test2(); }
365 struct T;
366
367 impl Test for T {
368     fn test(t$0)
369 }
370 ",
371             expect![[""]],
372         );
373
374         check(
375             r"
376 trait Test { fn test(_: fn()); fn test2(); }
377 struct T;
378
379 impl Test for T {
380     fn test(f: fn $0)
381 }
382 ",
383             expect![[""]],
384         );
385     }
386
387     #[test]
388     fn no_completion_inside_const() {
389         check(
390             r"
391 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
392 struct T;
393
394 impl Test for T {
395     const TEST: fn $0
396 }
397 ",
398             expect![[""]],
399         );
400
401         check(
402             r"
403 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
404 struct T;
405
406 impl Test for T {
407     const TEST: T$0
408 }
409 ",
410             expect![[""]],
411         );
412
413         check(
414             r"
415 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
416 struct T;
417
418 impl Test for T {
419     const TEST: u32 = f$0
420 }
421 ",
422             expect![[""]],
423         );
424
425         check(
426             r"
427 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
428 struct T;
429
430 impl Test for T {
431     const TEST: u32 = {
432         t$0
433     };
434 }
435 ",
436             expect![[""]],
437         );
438
439         check(
440             r"
441 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
442 struct T;
443
444 impl Test for T {
445     const TEST: u32 = {
446         fn $0
447     };
448 }
449 ",
450             expect![[""]],
451         );
452
453         check(
454             r"
455 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
456 struct T;
457
458 impl Test for T {
459     const TEST: u32 = {
460         fn t$0
461     };
462 }
463 ",
464             expect![[""]],
465         );
466     }
467
468     #[test]
469     fn no_completion_inside_type() {
470         check(
471             r"
472 trait Test { type Test; type Test2; fn test(); }
473 struct T;
474
475 impl Test for T {
476     type Test = T$0;
477 }
478 ",
479             expect![[""]],
480         );
481
482         check(
483             r"
484 trait Test { type Test; type Test2; fn test(); }
485 struct T;
486
487 impl Test for T {
488     type Test = fn $0;
489 }
490 ",
491             expect![[""]],
492         );
493     }
494
495     #[test]
496     fn name_ref_single_function() {
497         check_edit(
498             "test",
499             r#"
500 trait Test {
501     fn test();
502 }
503 struct T;
504
505 impl Test for T {
506     t$0
507 }
508 "#,
509             r#"
510 trait Test {
511     fn test();
512 }
513 struct T;
514
515 impl Test for T {
516     fn test() {
517     $0
518 }
519 }
520 "#,
521         );
522     }
523
524     #[test]
525     fn single_function() {
526         check_edit(
527             "test",
528             r#"
529 trait Test {
530     fn test();
531 }
532 struct T;
533
534 impl Test for T {
535     fn t$0
536 }
537 "#,
538             r#"
539 trait Test {
540     fn test();
541 }
542 struct T;
543
544 impl Test for T {
545     fn test() {
546     $0
547 }
548 }
549 "#,
550         );
551     }
552
553     #[test]
554     fn generic_fn() {
555         check_edit(
556             "foo",
557             r#"
558 trait Test {
559     fn foo<T>();
560 }
561 struct T;
562
563 impl Test for T {
564     fn f$0
565 }
566 "#,
567             r#"
568 trait Test {
569     fn foo<T>();
570 }
571 struct T;
572
573 impl Test for T {
574     fn foo<T>() {
575     $0
576 }
577 }
578 "#,
579         );
580         check_edit(
581             "foo",
582             r#"
583 trait Test {
584     fn foo<T>() where T: Into<String>;
585 }
586 struct T;
587
588 impl Test for T {
589     fn f$0
590 }
591 "#,
592             r#"
593 trait Test {
594     fn foo<T>() where T: Into<String>;
595 }
596 struct T;
597
598 impl Test for T {
599     fn foo<T>()
600 where T: Into<String> {
601     $0
602 }
603 }
604 "#,
605         );
606     }
607
608     #[test]
609     fn associated_type() {
610         check_edit(
611             "SomeType",
612             r#"
613 trait Test {
614     type SomeType;
615 }
616
617 impl Test for () {
618     type S$0
619 }
620 "#,
621             "
622 trait Test {
623     type SomeType;
624 }
625
626 impl Test for () {
627     type SomeType = \n\
628 }
629 ",
630         );
631     }
632
633     #[test]
634     fn associated_const() {
635         check_edit(
636             "SOME_CONST",
637             r#"
638 trait Test {
639     const SOME_CONST: u16;
640 }
641
642 impl Test for () {
643     const S$0
644 }
645 "#,
646             "
647 trait Test {
648     const SOME_CONST: u16;
649 }
650
651 impl Test for () {
652     const SOME_CONST: u16 = \n\
653 }
654 ",
655         );
656
657         check_edit(
658             "SOME_CONST",
659             r#"
660 trait Test {
661     const SOME_CONST: u16 = 92;
662 }
663
664 impl Test for () {
665     const S$0
666 }
667 "#,
668             "
669 trait Test {
670     const SOME_CONST: u16 = 92;
671 }
672
673 impl Test for () {
674     const SOME_CONST: u16 = \n\
675 }
676 ",
677         );
678     }
679
680     #[test]
681     fn complete_without_name() {
682         let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
683             check_edit(
684                 completion,
685                 &format!(
686                     r#"
687 trait Test {{
688     type Foo;
689     const CONST: u16;
690     fn bar();
691 }}
692 struct T;
693
694 impl Test for T {{
695     {}
696     {}
697 }}
698 "#,
699                     hint, next_sibling
700                 ),
701                 &format!(
702                     r#"
703 trait Test {{
704     type Foo;
705     const CONST: u16;
706     fn bar();
707 }}
708 struct T;
709
710 impl Test for T {{
711     {}
712     {}
713 }}
714 "#,
715                     completed, next_sibling
716                 ),
717             )
718         };
719
720         // Enumerate some possible next siblings.
721         for next_sibling in &[
722             "",
723             "fn other_fn() {}", // `const $0 fn` -> `const fn`
724             "type OtherType = i32;",
725             "const OTHER_CONST: i32 = 0;",
726             "async fn other_fn() {}",
727             "unsafe fn other_fn() {}",
728             "default fn other_fn() {}",
729             "default type OtherType = i32;",
730             "default const OTHER_CONST: i32 = 0;",
731         ] {
732             test("bar", "fn $0", "fn bar() {\n    $0\n}", next_sibling);
733             test("Foo", "type $0", "type Foo = ", next_sibling);
734             test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
735         }
736     }
737
738     #[test]
739     fn snippet_does_not_overwrite_comment_or_attr() {
740         let test = |completion: &str, hint: &str, completed: &str| {
741             check_edit(
742                 completion,
743                 &format!(
744                     r#"
745 trait Foo {{
746     type Type;
747     fn function();
748     const CONST: i32 = 0;
749 }}
750 struct T;
751
752 impl Foo for T {{
753     // Comment
754     #[bar]
755     {}
756 }}
757 "#,
758                     hint
759                 ),
760                 &format!(
761                     r#"
762 trait Foo {{
763     type Type;
764     fn function();
765     const CONST: i32 = 0;
766 }}
767 struct T;
768
769 impl Foo for T {{
770     // Comment
771     #[bar]
772     {}
773 }}
774 "#,
775                     completed
776                 ),
777             )
778         };
779         test("function", "fn f$0", "fn function() {\n    $0\n}");
780         test("Type", "type T$0", "type Type = ");
781         test("CONST", "const C$0", "const CONST: i32 = ");
782     }
783
784     #[test]
785     fn generics_are_inlined_in_return_type() {
786         check_edit(
787             "function",
788             r#"
789 trait Foo<T> {
790     fn function() -> T;
791 }
792 struct Bar;
793
794 impl Foo<u32> for Bar {
795     fn f$0
796 }
797 "#,
798             r#"
799 trait Foo<T> {
800     fn function() -> T;
801 }
802 struct Bar;
803
804 impl Foo<u32> for Bar {
805     fn function() -> u32 {
806     $0
807 }
808 }
809 "#,
810         )
811     }
812
813     #[test]
814     fn generics_are_inlined_in_parameter() {
815         check_edit(
816             "function",
817             r#"
818 trait Foo<T> {
819     fn function(bar: T);
820 }
821 struct Bar;
822
823 impl Foo<u32> for Bar {
824     fn f$0
825 }
826 "#,
827             r#"
828 trait Foo<T> {
829     fn function(bar: T);
830 }
831 struct Bar;
832
833 impl Foo<u32> for Bar {
834     fn function(bar: u32) {
835     $0
836 }
837 }
838 "#,
839         )
840     }
841
842     #[test]
843     fn generics_are_inlined_when_part_of_other_types() {
844         check_edit(
845             "function",
846             r#"
847 trait Foo<T> {
848     fn function(bar: Vec<T>);
849 }
850 struct Bar;
851
852 impl Foo<u32> for Bar {
853     fn f$0
854 }
855 "#,
856             r#"
857 trait Foo<T> {
858     fn function(bar: Vec<T>);
859 }
860 struct Bar;
861
862 impl Foo<u32> for Bar {
863     fn function(bar: Vec<u32>) {
864     $0
865 }
866 }
867 "#,
868         )
869     }
870
871     #[test]
872     fn generics_are_inlined_complex() {
873         check_edit(
874             "function",
875             r#"
876 trait Foo<T, U, V> {
877     fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
878 }
879 struct Bar;
880
881 impl Foo<u32, Vec<usize>, u8> for Bar {
882     fn f$0
883 }
884 "#,
885             r#"
886 trait Foo<T, U, V> {
887     fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
888 }
889 struct Bar;
890
891 impl Foo<u32, Vec<usize>, u8> for Bar {
892     fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
893     $0
894 }
895 }
896 "#,
897         )
898     }
899
900     #[test]
901     fn generics_are_inlined_in_associated_const() {
902         check_edit(
903             "BAR",
904             r#"
905 trait Foo<T> {
906     const BAR: T;
907 }
908 struct Bar;
909
910 impl Foo<u32> for Bar {
911     const B$0;
912 }
913 "#,
914             r#"
915 trait Foo<T> {
916     const BAR: T;
917 }
918 struct Bar;
919
920 impl Foo<u32> for Bar {
921     const BAR: u32 = ;
922 }
923 "#,
924         )
925     }
926
927     #[test]
928     fn generics_are_inlined_in_where_clause() {
929         check_edit(
930             "function",
931             r#"
932 trait SomeTrait<T> {}
933
934 trait Foo<T> {
935     fn function()
936     where Self: SomeTrait<T>;
937 }
938 struct Bar;
939
940 impl Foo<u32> for Bar {
941     fn f$0
942 }
943 "#,
944             r#"
945 trait SomeTrait<T> {}
946
947 trait Foo<T> {
948     fn function()
949     where Self: SomeTrait<T>;
950 }
951 struct Bar;
952
953 impl Foo<u32> for Bar {
954     fn function()
955 where Self: SomeTrait<u32> {
956     $0
957 }
958 }
959 "#,
960         )
961     }
962 }