]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/trait_impl.rs
use references in CompletionItem's builder
[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::{traits::get_missing_assoc_items, SymbolKind};
36 use syntax::{
37     ast::{self, edit, Impl},
38     display::function_declaration,
39     AstNode, SyntaxKind, SyntaxNode, TextRange, T,
40 };
41 use text_edit::TextEdit;
42
43 use crate::{
44     CompletionContext,
45     CompletionItem,
46     CompletionItemKind,
47     CompletionKind,
48     Completions,
49     // display::function_declaration,
50 };
51
52 #[derive(Debug, PartialEq, Eq)]
53 enum ImplCompletionKind {
54     All,
55     Fn,
56     TypeAlias,
57     Const,
58 }
59
60 pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
61     if let Some((kind, trigger, impl_def)) = completion_match(ctx) {
62         get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
63             hir::AssocItem::Function(fn_item)
64                 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
65             {
66                 add_function_impl(&trigger, acc, ctx, fn_item)
67             }
68             hir::AssocItem::TypeAlias(type_item)
69                 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
70             {
71                 add_type_alias_impl(&trigger, acc, ctx, type_item)
72             }
73             hir::AssocItem::Const(const_item)
74                 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
75             {
76                 add_const_impl(&trigger, acc, ctx, const_item)
77             }
78             _ => {}
79         });
80     }
81 }
82
83 fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
84     let mut token = ctx.token.clone();
85     // For keywork without name like `impl .. { fn $0 }`, the current position is inside
86     // the whitespace token, which is outside `FN` syntax node.
87     // We need to follow the previous token in this case.
88     if token.kind() == SyntaxKind::WHITESPACE {
89         token = token.prev_token()?;
90     }
91
92     let impl_item_offset = match token.kind() {
93         // `impl .. { const $0 }`
94         // ERROR      0
95         //   CONST_KW <- *
96         T![const] => 0,
97         // `impl .. { fn/type $0 }`
98         // FN/TYPE_ALIAS  0
99         //   FN_KW        <- *
100         T![fn] | T![type] => 0,
101         // `impl .. { fn/type/const foo$0 }`
102         // FN/TYPE_ALIAS/CONST  1
103         //  NAME                0
104         //    IDENT             <- *
105         SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
106         // `impl .. { foo$0 }`
107         // MACRO_CALL       3
108         //  PATH            2
109         //    PATH_SEGMENT  1
110         //      NAME_REF    0
111         //        IDENT     <- *
112         SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
113         _ => return None,
114     };
115
116     let impl_item = token.ancestors().nth(impl_item_offset)?;
117     // Must directly belong to an impl block.
118     // IMPL
119     //   ASSOC_ITEM_LIST
120     //     <item>
121     let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
122     let kind = match impl_item.kind() {
123         // `impl ... { const $0 fn/type/const }`
124         _ if token.kind() == T![const] => ImplCompletionKind::Const,
125         SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
126         SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
127         SyntaxKind::FN => ImplCompletionKind::Fn,
128         SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
129         _ => return None,
130     };
131     Some((kind, impl_item, impl_def))
132 }
133
134 fn add_function_impl(
135     fn_def_node: &SyntaxNode,
136     acc: &mut Completions,
137     ctx: &CompletionContext,
138     func: hir::Function,
139 ) {
140     let fn_name = func.name(ctx.db).to_string();
141
142     let label = if func.assoc_fn_params(ctx.db).is_empty() {
143         format!("fn {}()", fn_name)
144     } else {
145         format!("fn {}(..)", fn_name)
146     };
147
148     let mut builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
149     builder.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
150
151     let completion_kind = if func.self_param(ctx.db).is_some() {
152         CompletionItemKind::Method
153     } else {
154         CompletionItemKind::SymbolKind(SymbolKind::Function)
155     };
156     let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
157
158     if let Some(src) = func.source(ctx.db) {
159         let function_decl = function_declaration(&src.value);
160         match ctx.config.snippet_cap {
161             Some(cap) => {
162                 let snippet = format!("{} {{\n    $0\n}}", function_decl);
163                 builder.snippet_edit(cap, TextEdit::replace(range, snippet));
164             }
165             None => {
166                 let header = format!("{} {{", function_decl);
167                 builder.text_edit(TextEdit::replace(range, header));
168             }
169         };
170         builder.kind(completion_kind);
171         builder.add_to(acc);
172     }
173 }
174
175 fn add_type_alias_impl(
176     type_def_node: &SyntaxNode,
177     acc: &mut Completions,
178     ctx: &CompletionContext,
179     type_alias: hir::TypeAlias,
180 ) {
181     let alias_name = type_alias.name(ctx.db).to_string();
182
183     let snippet = format!("type {} = ", alias_name);
184
185     let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
186
187     let mut builder =
188         CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
189     builder
190         .text_edit(TextEdit::replace(range, snippet))
191         .lookup_by(alias_name)
192         .kind(SymbolKind::TypeAlias)
193         .set_documentation(type_alias.docs(ctx.db));
194     builder.add_to(acc);
195 }
196
197 fn add_const_impl(
198     const_def_node: &SyntaxNode,
199     acc: &mut Completions,
200     ctx: &CompletionContext,
201     const_: hir::Const,
202 ) {
203     let const_name = const_.name(ctx.db).map(|n| n.to_string());
204
205     if let Some(const_name) = const_name {
206         if let Some(source) = const_.source(ctx.db) {
207             let snippet = make_const_compl_syntax(&source.value);
208
209             let range =
210                 TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
211
212             let mut builder =
213                 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
214             builder
215                 .text_edit(TextEdit::replace(range, snippet))
216                 .lookup_by(const_name)
217                 .kind(SymbolKind::Const)
218                 .set_documentation(const_.docs(ctx.db));
219             builder.add_to(acc);
220         }
221     }
222 }
223
224 fn make_const_compl_syntax(const_: &ast::Const) -> String {
225     let const_ = edit::remove_attrs_and_docs(const_);
226
227     let const_start = const_.syntax().text_range().start();
228     let const_end = const_.syntax().text_range().end();
229
230     let start =
231         const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
232
233     let end = const_
234         .syntax()
235         .children_with_tokens()
236         .find(|s| s.kind() == T![;] || s.kind() == T![=])
237         .map_or(const_end, |f| f.text_range().start());
238
239     let len = end - start;
240     let range = TextRange::new(0.into(), len);
241
242     let syntax = const_.syntax().text().slice(range).to_string();
243
244     format!("{} = ", syntax.trim_end())
245 }
246
247 #[cfg(test)]
248 mod tests {
249     use expect_test::{expect, Expect};
250
251     use crate::{
252         test_utils::{check_edit, completion_list},
253         CompletionKind,
254     };
255
256     fn check(ra_fixture: &str, expect: Expect) {
257         let actual = completion_list(ra_fixture, CompletionKind::Magic);
258         expect.assert_eq(&actual)
259     }
260
261     #[test]
262     fn name_ref_function_type_const() {
263         check(
264             r#"
265 trait Test {
266     type TestType;
267     const TEST_CONST: u16;
268     fn test();
269 }
270 struct T;
271
272 impl Test for T {
273     t$0
274 }
275 "#,
276             expect![["
277 ta type TestType = \n\
278 ct const TEST_CONST: u16 = \n\
279 fn fn test()
280 "]],
281         );
282     }
283
284     #[test]
285     fn no_completion_inside_fn() {
286         check(
287             r"
288 trait Test { fn test(); fn test2(); }
289 struct T;
290
291 impl Test for T {
292     fn test() {
293         t$0
294     }
295 }
296 ",
297             expect![[""]],
298         );
299
300         check(
301             r"
302 trait Test { fn test(); fn test2(); }
303 struct T;
304
305 impl Test for T {
306     fn test() {
307         fn t$0
308     }
309 }
310 ",
311             expect![[""]],
312         );
313
314         check(
315             r"
316 trait Test { fn test(); fn test2(); }
317 struct T;
318
319 impl Test for T {
320     fn test() {
321         fn $0
322     }
323 }
324 ",
325             expect![[""]],
326         );
327
328         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
329         check(
330             r"
331 trait Test { fn test(); fn test2(); }
332 struct T;
333
334 impl Test for T {
335     fn test() {
336         foo.$0
337     }
338 }
339 ",
340             expect![[""]],
341         );
342
343         check(
344             r"
345 trait Test { fn test(_: i32); fn test2(); }
346 struct T;
347
348 impl Test for T {
349     fn test(t$0)
350 }
351 ",
352             expect![[""]],
353         );
354
355         check(
356             r"
357 trait Test { fn test(_: fn()); fn test2(); }
358 struct T;
359
360 impl Test for T {
361     fn test(f: fn $0)
362 }
363 ",
364             expect![[""]],
365         );
366     }
367
368     #[test]
369     fn no_completion_inside_const() {
370         check(
371             r"
372 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
373 struct T;
374
375 impl Test for T {
376     const TEST: fn $0
377 }
378 ",
379             expect![[""]],
380         );
381
382         check(
383             r"
384 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
385 struct T;
386
387 impl Test for T {
388     const TEST: T$0
389 }
390 ",
391             expect![[""]],
392         );
393
394         check(
395             r"
396 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
397 struct T;
398
399 impl Test for T {
400     const TEST: u32 = f$0
401 }
402 ",
403             expect![[""]],
404         );
405
406         check(
407             r"
408 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
409 struct T;
410
411 impl Test for T {
412     const TEST: u32 = {
413         t$0
414     };
415 }
416 ",
417             expect![[""]],
418         );
419
420         check(
421             r"
422 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
423 struct T;
424
425 impl Test for T {
426     const TEST: u32 = {
427         fn $0
428     };
429 }
430 ",
431             expect![[""]],
432         );
433
434         check(
435             r"
436 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
437 struct T;
438
439 impl Test for T {
440     const TEST: u32 = {
441         fn t$0
442     };
443 }
444 ",
445             expect![[""]],
446         );
447     }
448
449     #[test]
450     fn no_completion_inside_type() {
451         check(
452             r"
453 trait Test { type Test; type Test2; fn test(); }
454 struct T;
455
456 impl Test for T {
457     type Test = T$0;
458 }
459 ",
460             expect![[""]],
461         );
462
463         check(
464             r"
465 trait Test { type Test; type Test2; fn test(); }
466 struct T;
467
468 impl Test for T {
469     type Test = fn $0;
470 }
471 ",
472             expect![[""]],
473         );
474     }
475
476     #[test]
477     fn name_ref_single_function() {
478         check_edit(
479             "test",
480             r#"
481 trait Test {
482     fn test();
483 }
484 struct T;
485
486 impl Test for T {
487     t$0
488 }
489 "#,
490             r#"
491 trait Test {
492     fn test();
493 }
494 struct T;
495
496 impl Test for T {
497     fn test() {
498     $0
499 }
500 }
501 "#,
502         );
503     }
504
505     #[test]
506     fn single_function() {
507         check_edit(
508             "test",
509             r#"
510 trait Test {
511     fn test();
512 }
513 struct T;
514
515 impl Test for T {
516     fn t$0
517 }
518 "#,
519             r#"
520 trait Test {
521     fn test();
522 }
523 struct T;
524
525 impl Test for T {
526     fn test() {
527     $0
528 }
529 }
530 "#,
531         );
532     }
533
534     #[test]
535     fn hide_implemented_fn() {
536         check(
537             r#"
538 trait Test {
539     fn foo();
540     fn foo_bar();
541 }
542 struct T;
543
544 impl Test for T {
545     fn foo() {}
546     fn f$0
547 }
548 "#,
549             expect![[r#"
550                 fn fn foo_bar()
551             "#]],
552         );
553     }
554
555     #[test]
556     fn generic_fn() {
557         check_edit(
558             "foo",
559             r#"
560 trait Test {
561     fn foo<T>();
562 }
563 struct T;
564
565 impl Test for T {
566     fn f$0
567 }
568 "#,
569             r#"
570 trait Test {
571     fn foo<T>();
572 }
573 struct T;
574
575 impl Test for T {
576     fn foo<T>() {
577     $0
578 }
579 }
580 "#,
581         );
582         check_edit(
583             "foo",
584             r#"
585 trait Test {
586     fn foo<T>() where T: Into<String>;
587 }
588 struct T;
589
590 impl Test for T {
591     fn f$0
592 }
593 "#,
594             r#"
595 trait Test {
596     fn foo<T>() where T: Into<String>;
597 }
598 struct T;
599
600 impl Test for T {
601     fn foo<T>()
602 where T: Into<String> {
603     $0
604 }
605 }
606 "#,
607         );
608     }
609
610     #[test]
611     fn associated_type() {
612         check_edit(
613             "SomeType",
614             r#"
615 trait Test {
616     type SomeType;
617 }
618
619 impl Test for () {
620     type S$0
621 }
622 "#,
623             "
624 trait Test {
625     type SomeType;
626 }
627
628 impl Test for () {
629     type SomeType = \n\
630 }
631 ",
632         );
633     }
634
635     #[test]
636     fn associated_const() {
637         check_edit(
638             "SOME_CONST",
639             r#"
640 trait Test {
641     const SOME_CONST: u16;
642 }
643
644 impl Test for () {
645     const S$0
646 }
647 "#,
648             "
649 trait Test {
650     const SOME_CONST: u16;
651 }
652
653 impl Test for () {
654     const SOME_CONST: u16 = \n\
655 }
656 ",
657         );
658
659         check_edit(
660             "SOME_CONST",
661             r#"
662 trait Test {
663     const SOME_CONST: u16 = 92;
664 }
665
666 impl Test for () {
667     const S$0
668 }
669 "#,
670             "
671 trait Test {
672     const SOME_CONST: u16 = 92;
673 }
674
675 impl Test for () {
676     const SOME_CONST: u16 = \n\
677 }
678 ",
679         );
680     }
681
682     #[test]
683     fn complete_without_name() {
684         let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
685             check_edit(
686                 completion,
687                 &format!(
688                     r#"
689 trait Test {{
690     type Foo;
691     const CONST: u16;
692     fn bar();
693 }}
694 struct T;
695
696 impl Test for T {{
697     {}
698     {}
699 }}
700 "#,
701                     hint, next_sibling
702                 ),
703                 &format!(
704                     r#"
705 trait Test {{
706     type Foo;
707     const CONST: u16;
708     fn bar();
709 }}
710 struct T;
711
712 impl Test for T {{
713     {}
714     {}
715 }}
716 "#,
717                     completed, next_sibling
718                 ),
719             )
720         };
721
722         // Enumerate some possible next siblings.
723         for next_sibling in &[
724             "",
725             "fn other_fn() {}", // `const $0 fn` -> `const fn`
726             "type OtherType = i32;",
727             "const OTHER_CONST: i32 = 0;",
728             "async fn other_fn() {}",
729             "unsafe fn other_fn() {}",
730             "default fn other_fn() {}",
731             "default type OtherType = i32;",
732             "default const OTHER_CONST: i32 = 0;",
733         ] {
734             test("bar", "fn $0", "fn bar() {\n    $0\n}", next_sibling);
735             test("Foo", "type $0", "type Foo = ", next_sibling);
736             test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
737         }
738     }
739 }