]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/trait_impl.rs
Clarify what the outline test module is for
[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 a `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},
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(impl_def.source(ctx.db)?.syntax().value);
189     let transform = PathTransform {
190         subst: (trait_, impl_def.source(ctx.db)?.value),
191         source_scope,
192         target_scope,
193     };
194
195     transform.apply(assoc_item.clone());
196     Some(match assoc_item {
197         ast::AssocItem::Fn(func) => ast::AssocItem::Fn(edit::remove_attrs_and_docs(&func)),
198         _ => assoc_item,
199     })
200 }
201
202 fn add_type_alias_impl(
203     type_def_node: &SyntaxNode,
204     acc: &mut Completions,
205     ctx: &CompletionContext,
206     type_alias: hir::TypeAlias,
207 ) {
208     let alias_name = type_alias.name(ctx.db).to_string();
209
210     let snippet = format!("type {} = ", alias_name);
211
212     let range = replacement_range(ctx, type_def_node);
213     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
214     item.text_edit(TextEdit::replace(range, snippet))
215         .lookup_by(alias_name)
216         .kind(SymbolKind::TypeAlias)
217         .set_documentation(type_alias.docs(ctx.db));
218     item.add_to(acc);
219 }
220
221 fn add_const_impl(
222     const_def_node: &SyntaxNode,
223     acc: &mut Completions,
224     ctx: &CompletionContext,
225     const_: hir::Const,
226     impl_def: hir::Impl,
227 ) {
228     let const_name = const_.name(ctx.db).map(|n| n.to_string());
229
230     if let Some(const_name) = const_name {
231         if let Some(source) = const_.source(ctx.db) {
232             let assoc_item = ast::AssocItem::Const(source.value);
233             if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
234                 let transformed_const = match transformed_item {
235                     ast::AssocItem::Const(const_) => const_,
236                     _ => unreachable!(),
237                 };
238
239                 let snippet = make_const_compl_syntax(&transformed_const);
240
241                 let range = replacement_range(ctx, const_def_node);
242                 let mut item =
243                     CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
244                 item.text_edit(TextEdit::replace(range, snippet))
245                     .lookup_by(const_name)
246                     .kind(SymbolKind::Const)
247                     .set_documentation(const_.docs(ctx.db));
248                 item.add_to(acc);
249             }
250         }
251     }
252 }
253
254 fn make_const_compl_syntax(const_: &ast::Const) -> String {
255     let const_ = edit::remove_attrs_and_docs(const_);
256
257     let const_start = const_.syntax().text_range().start();
258     let const_end = const_.syntax().text_range().end();
259
260     let start =
261         const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
262
263     let end = const_
264         .syntax()
265         .children_with_tokens()
266         .find(|s| s.kind() == T![;] || s.kind() == T![=])
267         .map_or(const_end, |f| f.text_range().start());
268
269     let len = end - start;
270     let range = TextRange::new(0.into(), len);
271
272     let syntax = const_.syntax().text().slice(range).to_string();
273
274     format!("{} = ", syntax.trim_end())
275 }
276
277 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
278     let first_child = item
279         .children_with_tokens()
280         .find(|child| {
281             !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
282         })
283         .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
284
285     TextRange::new(first_child.text_range().start(), ctx.source_range().end())
286 }
287
288 #[cfg(test)]
289 mod tests {
290     use expect_test::{expect, Expect};
291
292     use crate::{
293         tests::{check_edit, filtered_completion_list},
294         CompletionKind,
295     };
296
297     fn check(ra_fixture: &str, expect: Expect) {
298         let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
299         expect.assert_eq(&actual)
300     }
301
302     #[test]
303     fn no_completion_inside_fn() {
304         check(
305             r"
306 trait Test { fn test(); fn test2(); }
307 struct T;
308
309 impl Test for T {
310     fn test() {
311         t$0
312     }
313 }
314 ",
315             expect![[""]],
316         );
317
318         check(
319             r"
320 trait Test { fn test(); fn test2(); }
321 struct T;
322
323 impl Test for T {
324     fn test() {
325         fn t$0
326     }
327 }
328 ",
329             expect![[""]],
330         );
331
332         check(
333             r"
334 trait Test { fn test(); fn test2(); }
335 struct T;
336
337 impl Test for T {
338     fn test() {
339         fn $0
340     }
341 }
342 ",
343             expect![[""]],
344         );
345
346         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
347         check(
348             r"
349 trait Test { fn test(); fn test2(); }
350 struct T;
351
352 impl Test for T {
353     fn test() {
354         foo.$0
355     }
356 }
357 ",
358             expect![[""]],
359         );
360
361         check(
362             r"
363 trait Test { fn test(_: i32); fn test2(); }
364 struct T;
365
366 impl Test for T {
367     fn test(t$0)
368 }
369 ",
370             expect![[""]],
371         );
372
373         check(
374             r"
375 trait Test { fn test(_: fn()); fn test2(); }
376 struct T;
377
378 impl Test for T {
379     fn test(f: fn $0)
380 }
381 ",
382             expect![[""]],
383         );
384     }
385
386     #[test]
387     fn no_completion_inside_const() {
388         check(
389             r"
390 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
391 struct T;
392
393 impl Test for T {
394     const TEST: fn $0
395 }
396 ",
397             expect![[""]],
398         );
399
400         check(
401             r"
402 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
403 struct T;
404
405 impl Test for T {
406     const TEST: T$0
407 }
408 ",
409             expect![[""]],
410         );
411
412         check(
413             r"
414 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
415 struct T;
416
417 impl Test for T {
418     const TEST: u32 = f$0
419 }
420 ",
421             expect![[""]],
422         );
423
424         check(
425             r"
426 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
427 struct T;
428
429 impl Test for T {
430     const TEST: u32 = {
431         t$0
432     };
433 }
434 ",
435             expect![[""]],
436         );
437
438         check(
439             r"
440 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
441 struct T;
442
443 impl Test for T {
444     const TEST: u32 = {
445         fn $0
446     };
447 }
448 ",
449             expect![[""]],
450         );
451
452         check(
453             r"
454 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
455 struct T;
456
457 impl Test for T {
458     const TEST: u32 = {
459         fn t$0
460     };
461 }
462 ",
463             expect![[""]],
464         );
465     }
466
467     #[test]
468     fn no_completion_inside_type() {
469         check(
470             r"
471 trait Test { type Test; type Test2; fn test(); }
472 struct T;
473
474 impl Test for T {
475     type Test = T$0;
476 }
477 ",
478             expect![[""]],
479         );
480
481         check(
482             r"
483 trait Test { type Test; type Test2; fn test(); }
484 struct T;
485
486 impl Test for T {
487     type Test = fn $0;
488 }
489 ",
490             expect![[""]],
491         );
492     }
493
494     #[test]
495     fn name_ref_single_function() {
496         check_edit(
497             "test",
498             r#"
499 trait Test {
500     fn test();
501 }
502 struct T;
503
504 impl Test for T {
505     t$0
506 }
507 "#,
508             r#"
509 trait Test {
510     fn test();
511 }
512 struct T;
513
514 impl Test for T {
515     fn test() {
516     $0
517 }
518 }
519 "#,
520         );
521     }
522
523     #[test]
524     fn single_function() {
525         check_edit(
526             "test",
527             r#"
528 trait Test {
529     fn test();
530 }
531 struct T;
532
533 impl Test for T {
534     fn t$0
535 }
536 "#,
537             r#"
538 trait Test {
539     fn test();
540 }
541 struct T;
542
543 impl Test for T {
544     fn test() {
545     $0
546 }
547 }
548 "#,
549         );
550     }
551
552     #[test]
553     fn generic_fn() {
554         check_edit(
555             "foo",
556             r#"
557 trait Test {
558     fn foo<T>();
559 }
560 struct T;
561
562 impl Test for T {
563     fn f$0
564 }
565 "#,
566             r#"
567 trait Test {
568     fn foo<T>();
569 }
570 struct T;
571
572 impl Test for T {
573     fn foo<T>() {
574     $0
575 }
576 }
577 "#,
578         );
579         check_edit(
580             "foo",
581             r#"
582 trait Test {
583     fn foo<T>() where T: Into<String>;
584 }
585 struct T;
586
587 impl Test for T {
588     fn f$0
589 }
590 "#,
591             r#"
592 trait Test {
593     fn foo<T>() where T: Into<String>;
594 }
595 struct T;
596
597 impl Test for T {
598     fn foo<T>()
599 where T: Into<String> {
600     $0
601 }
602 }
603 "#,
604         );
605     }
606
607     #[test]
608     fn associated_type() {
609         check_edit(
610             "SomeType",
611             r#"
612 trait Test {
613     type SomeType;
614 }
615
616 impl Test for () {
617     type S$0
618 }
619 "#,
620             "
621 trait Test {
622     type SomeType;
623 }
624
625 impl Test for () {
626     type SomeType = \n\
627 }
628 ",
629         );
630     }
631
632     #[test]
633     fn associated_const() {
634         check_edit(
635             "SOME_CONST",
636             r#"
637 trait Test {
638     const SOME_CONST: u16;
639 }
640
641 impl Test for () {
642     const S$0
643 }
644 "#,
645             "
646 trait Test {
647     const SOME_CONST: u16;
648 }
649
650 impl Test for () {
651     const SOME_CONST: u16 = \n\
652 }
653 ",
654         );
655
656         check_edit(
657             "SOME_CONST",
658             r#"
659 trait Test {
660     const SOME_CONST: u16 = 92;
661 }
662
663 impl Test for () {
664     const S$0
665 }
666 "#,
667             "
668 trait Test {
669     const SOME_CONST: u16 = 92;
670 }
671
672 impl Test for () {
673     const SOME_CONST: u16 = \n\
674 }
675 ",
676         );
677     }
678
679     #[test]
680     fn complete_without_name() {
681         let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
682             check_edit(
683                 completion,
684                 &format!(
685                     r#"
686 trait Test {{
687     type Foo;
688     const CONST: u16;
689     fn bar();
690 }}
691 struct T;
692
693 impl Test for T {{
694     {}
695     {}
696 }}
697 "#,
698                     hint, next_sibling
699                 ),
700                 &format!(
701                     r#"
702 trait Test {{
703     type Foo;
704     const CONST: u16;
705     fn bar();
706 }}
707 struct T;
708
709 impl Test for T {{
710     {}
711     {}
712 }}
713 "#,
714                     completed, next_sibling
715                 ),
716             )
717         };
718
719         // Enumerate some possible next siblings.
720         for next_sibling in &[
721             "",
722             "fn other_fn() {}", // `const $0 fn` -> `const fn`
723             "type OtherType = i32;",
724             "const OTHER_CONST: i32 = 0;",
725             "async fn other_fn() {}",
726             "unsafe fn other_fn() {}",
727             "default fn other_fn() {}",
728             "default type OtherType = i32;",
729             "default const OTHER_CONST: i32 = 0;",
730         ] {
731             test("bar", "fn $0", "fn bar() {\n    $0\n}", next_sibling);
732             test("Foo", "type $0", "type Foo = ", next_sibling);
733             test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
734         }
735     }
736
737     #[test]
738     fn snippet_does_not_overwrite_comment_or_attr() {
739         let test = |completion: &str, hint: &str, completed: &str| {
740             check_edit(
741                 completion,
742                 &format!(
743                     r#"
744 trait Foo {{
745     type Type;
746     fn function();
747     const CONST: i32 = 0;
748 }}
749 struct T;
750
751 impl Foo for T {{
752     // Comment
753     #[bar]
754     {}
755 }}
756 "#,
757                     hint
758                 ),
759                 &format!(
760                     r#"
761 trait Foo {{
762     type Type;
763     fn function();
764     const CONST: i32 = 0;
765 }}
766 struct T;
767
768 impl Foo for T {{
769     // Comment
770     #[bar]
771     {}
772 }}
773 "#,
774                     completed
775                 ),
776             )
777         };
778         test("function", "fn f$0", "fn function() {\n    $0\n}");
779         test("Type", "type T$0", "type Type = ");
780         test("CONST", "const C$0", "const CONST: i32 = ");
781     }
782
783     #[test]
784     fn generics_are_inlined_in_return_type() {
785         check_edit(
786             "function",
787             r#"
788 trait Foo<T> {
789     fn function() -> T;
790 }
791 struct Bar;
792
793 impl Foo<u32> for Bar {
794     fn f$0
795 }
796 "#,
797             r#"
798 trait Foo<T> {
799     fn function() -> T;
800 }
801 struct Bar;
802
803 impl Foo<u32> for Bar {
804     fn function() -> u32 {
805     $0
806 }
807 }
808 "#,
809         )
810     }
811
812     #[test]
813     fn generics_are_inlined_in_parameter() {
814         check_edit(
815             "function",
816             r#"
817 trait Foo<T> {
818     fn function(bar: T);
819 }
820 struct Bar;
821
822 impl Foo<u32> for Bar {
823     fn f$0
824 }
825 "#,
826             r#"
827 trait Foo<T> {
828     fn function(bar: T);
829 }
830 struct Bar;
831
832 impl Foo<u32> for Bar {
833     fn function(bar: u32) {
834     $0
835 }
836 }
837 "#,
838         )
839     }
840
841     #[test]
842     fn generics_are_inlined_when_part_of_other_types() {
843         check_edit(
844             "function",
845             r#"
846 trait Foo<T> {
847     fn function(bar: Vec<T>);
848 }
849 struct Bar;
850
851 impl Foo<u32> for Bar {
852     fn f$0
853 }
854 "#,
855             r#"
856 trait Foo<T> {
857     fn function(bar: Vec<T>);
858 }
859 struct Bar;
860
861 impl Foo<u32> for Bar {
862     fn function(bar: Vec<u32>) {
863     $0
864 }
865 }
866 "#,
867         )
868     }
869
870     #[test]
871     fn generics_are_inlined_complex() {
872         check_edit(
873             "function",
874             r#"
875 trait Foo<T, U, V> {
876     fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
877 }
878 struct Bar;
879
880 impl Foo<u32, Vec<usize>, u8> for Bar {
881     fn f$0
882 }
883 "#,
884             r#"
885 trait Foo<T, U, V> {
886     fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
887 }
888 struct Bar;
889
890 impl Foo<u32, Vec<usize>, u8> for Bar {
891     fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
892     $0
893 }
894 }
895 "#,
896         )
897     }
898
899     #[test]
900     fn generics_are_inlined_in_associated_const() {
901         check_edit(
902             "BAR",
903             r#"
904 trait Foo<T> {
905     const BAR: T;
906 }
907 struct Bar;
908
909 impl Foo<u32> for Bar {
910     const B$0;
911 }
912 "#,
913             r#"
914 trait Foo<T> {
915     const BAR: T;
916 }
917 struct Bar;
918
919 impl Foo<u32> for Bar {
920     const BAR: u32 = ;
921 }
922 "#,
923         )
924     }
925
926     #[test]
927     fn generics_are_inlined_in_where_clause() {
928         check_edit(
929             "function",
930             r#"
931 trait SomeTrait<T> {}
932
933 trait Foo<T> {
934     fn function()
935     where Self: SomeTrait<T>;
936 }
937 struct Bar;
938
939 impl Foo<u32> for Bar {
940     fn f$0
941 }
942 "#,
943             r#"
944 trait SomeTrait<T> {}
945
946 trait Foo<T> {
947     fn function()
948     where Self: SomeTrait<T>;
949 }
950 struct Bar;
951
952 impl Foo<u32> for Bar {
953     fn function()
954 where Self: SomeTrait<u32> {
955     $0
956 }
957 }
958 "#,
959         )
960     }
961 }