]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/trait_impl.rs
Merge #8042
[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 keyword 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 parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
93     let impl_item_offset = match token.kind() {
94         // `impl .. { const $0 }`
95         // ERROR      0
96         //   CONST_KW <- *
97         T![const] => 0,
98         // `impl .. { fn/type $0 }`
99         // FN/TYPE_ALIAS  0
100         //   FN_KW        <- *
101         T![fn] | T![type] => 0,
102         // `impl .. { fn/type/const foo$0 }`
103         // FN/TYPE_ALIAS/CONST  1
104         //  NAME                0
105         //    IDENT             <- *
106         SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
107         // `impl .. { foo$0 }`
108         // MACRO_CALL       3
109         //  PATH            2
110         //    PATH_SEGMENT  1
111         //      NAME_REF    0
112         //        IDENT     <- *
113         SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
114         _ => return None,
115     };
116
117     let impl_item = token.ancestors().nth(impl_item_offset)?;
118     // Must directly belong to an impl block.
119     // IMPL
120     //   ASSOC_ITEM_LIST
121     //     <item>
122     let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
123     let kind = match impl_item.kind() {
124         // `impl ... { const $0 fn/type/const }`
125         _ if token.kind() == T![const] => ImplCompletionKind::Const,
126         SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
127         SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
128         SyntaxKind::FN => ImplCompletionKind::Fn,
129         SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
130         _ => return None,
131     };
132     Some((kind, impl_item, impl_def))
133 }
134
135 fn add_function_impl(
136     fn_def_node: &SyntaxNode,
137     acc: &mut Completions,
138     ctx: &CompletionContext,
139     func: hir::Function,
140 ) {
141     let fn_name = func.name(ctx.db).to_string();
142
143     let label = if func.assoc_fn_params(ctx.db).is_empty() {
144         format!("fn {}()", fn_name)
145     } else {
146         format!("fn {}(..)", fn_name)
147     };
148
149     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
150     item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
151
152     let completion_kind = if func.self_param(ctx.db).is_some() {
153         CompletionItemKind::Method
154     } else {
155         CompletionItemKind::SymbolKind(SymbolKind::Function)
156     };
157     let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
158
159     if let Some(src) = func.source(ctx.db) {
160         let function_decl = function_declaration(&src.value);
161         match ctx.config.snippet_cap {
162             Some(cap) => {
163                 let snippet = format!("{} {{\n    $0\n}}", function_decl);
164                 item.snippet_edit(cap, TextEdit::replace(range, snippet));
165             }
166             None => {
167                 let header = format!("{} {{", function_decl);
168                 item.text_edit(TextEdit::replace(range, header));
169             }
170         };
171         item.kind(completion_kind);
172         item.add_to(acc);
173     }
174 }
175
176 fn add_type_alias_impl(
177     type_def_node: &SyntaxNode,
178     acc: &mut Completions,
179     ctx: &CompletionContext,
180     type_alias: hir::TypeAlias,
181 ) {
182     let alias_name = type_alias.name(ctx.db).to_string();
183
184     let snippet = format!("type {} = ", alias_name);
185
186     let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
187
188     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
189     item.text_edit(TextEdit::replace(range, snippet))
190         .lookup_by(alias_name)
191         .kind(SymbolKind::TypeAlias)
192         .set_documentation(type_alias.docs(ctx.db));
193     item.add_to(acc);
194 }
195
196 fn add_const_impl(
197     const_def_node: &SyntaxNode,
198     acc: &mut Completions,
199     ctx: &CompletionContext,
200     const_: hir::Const,
201 ) {
202     let const_name = const_.name(ctx.db).map(|n| n.to_string());
203
204     if let Some(const_name) = const_name {
205         if let Some(source) = const_.source(ctx.db) {
206             let snippet = make_const_compl_syntax(&source.value);
207
208             let range =
209                 TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
210
211             let mut item =
212                 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
213             item.text_edit(TextEdit::replace(range, snippet))
214                 .lookup_by(const_name)
215                 .kind(SymbolKind::Const)
216                 .set_documentation(const_.docs(ctx.db));
217             item.add_to(acc);
218         }
219     }
220 }
221
222 fn make_const_compl_syntax(const_: &ast::Const) -> String {
223     let const_ = edit::remove_attrs_and_docs(const_);
224
225     let const_start = const_.syntax().text_range().start();
226     let const_end = const_.syntax().text_range().end();
227
228     let start =
229         const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
230
231     let end = const_
232         .syntax()
233         .children_with_tokens()
234         .find(|s| s.kind() == T![;] || s.kind() == T![=])
235         .map_or(const_end, |f| f.text_range().start());
236
237     let len = end - start;
238     let range = TextRange::new(0.into(), len);
239
240     let syntax = const_.syntax().text().slice(range).to_string();
241
242     format!("{} = ", syntax.trim_end())
243 }
244
245 #[cfg(test)]
246 mod tests {
247     use expect_test::{expect, Expect};
248
249     use crate::{
250         test_utils::{check_edit, completion_list},
251         CompletionKind,
252     };
253
254     fn check(ra_fixture: &str, expect: Expect) {
255         let actual = completion_list(ra_fixture, CompletionKind::Magic);
256         expect.assert_eq(&actual)
257     }
258
259     #[test]
260     fn name_ref_function_type_const() {
261         check(
262             r#"
263 trait Test {
264     type TestType;
265     const TEST_CONST: u16;
266     fn test();
267 }
268 struct T;
269
270 impl Test for T {
271     t$0
272 }
273 "#,
274             expect![["
275 ta type TestType = \n\
276 ct const TEST_CONST: u16 = \n\
277 fn fn test()
278 "]],
279         );
280     }
281
282     #[test]
283     fn no_completion_inside_fn() {
284         check(
285             r"
286 trait Test { fn test(); fn test2(); }
287 struct T;
288
289 impl Test for T {
290     fn test() {
291         t$0
292     }
293 }
294 ",
295             expect![[""]],
296         );
297
298         check(
299             r"
300 trait Test { fn test(); fn test2(); }
301 struct T;
302
303 impl Test for T {
304     fn test() {
305         fn t$0
306     }
307 }
308 ",
309             expect![[""]],
310         );
311
312         check(
313             r"
314 trait Test { fn test(); fn test2(); }
315 struct T;
316
317 impl Test for T {
318     fn test() {
319         fn $0
320     }
321 }
322 ",
323             expect![[""]],
324         );
325
326         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
327         check(
328             r"
329 trait Test { fn test(); fn test2(); }
330 struct T;
331
332 impl Test for T {
333     fn test() {
334         foo.$0
335     }
336 }
337 ",
338             expect![[""]],
339         );
340
341         check(
342             r"
343 trait Test { fn test(_: i32); fn test2(); }
344 struct T;
345
346 impl Test for T {
347     fn test(t$0)
348 }
349 ",
350             expect![[""]],
351         );
352
353         check(
354             r"
355 trait Test { fn test(_: fn()); fn test2(); }
356 struct T;
357
358 impl Test for T {
359     fn test(f: fn $0)
360 }
361 ",
362             expect![[""]],
363         );
364     }
365
366     #[test]
367     fn no_completion_inside_const() {
368         check(
369             r"
370 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
371 struct T;
372
373 impl Test for T {
374     const TEST: fn $0
375 }
376 ",
377             expect![[""]],
378         );
379
380         check(
381             r"
382 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
383 struct T;
384
385 impl Test for T {
386     const TEST: T$0
387 }
388 ",
389             expect![[""]],
390         );
391
392         check(
393             r"
394 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
395 struct T;
396
397 impl Test for T {
398     const TEST: u32 = f$0
399 }
400 ",
401             expect![[""]],
402         );
403
404         check(
405             r"
406 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
407 struct T;
408
409 impl Test for T {
410     const TEST: u32 = {
411         t$0
412     };
413 }
414 ",
415             expect![[""]],
416         );
417
418         check(
419             r"
420 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
421 struct T;
422
423 impl Test for T {
424     const TEST: u32 = {
425         fn $0
426     };
427 }
428 ",
429             expect![[""]],
430         );
431
432         check(
433             r"
434 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
435 struct T;
436
437 impl Test for T {
438     const TEST: u32 = {
439         fn t$0
440     };
441 }
442 ",
443             expect![[""]],
444         );
445     }
446
447     #[test]
448     fn no_completion_inside_type() {
449         check(
450             r"
451 trait Test { type Test; type Test2; fn test(); }
452 struct T;
453
454 impl Test for T {
455     type Test = T$0;
456 }
457 ",
458             expect![[""]],
459         );
460
461         check(
462             r"
463 trait Test { type Test; type Test2; fn test(); }
464 struct T;
465
466 impl Test for T {
467     type Test = fn $0;
468 }
469 ",
470             expect![[""]],
471         );
472     }
473
474     #[test]
475     fn name_ref_single_function() {
476         check_edit(
477             "test",
478             r#"
479 trait Test {
480     fn test();
481 }
482 struct T;
483
484 impl Test for T {
485     t$0
486 }
487 "#,
488             r#"
489 trait Test {
490     fn test();
491 }
492 struct T;
493
494 impl Test for T {
495     fn test() {
496     $0
497 }
498 }
499 "#,
500         );
501     }
502
503     #[test]
504     fn single_function() {
505         check_edit(
506             "test",
507             r#"
508 trait Test {
509     fn test();
510 }
511 struct T;
512
513 impl Test for T {
514     fn t$0
515 }
516 "#,
517             r#"
518 trait Test {
519     fn test();
520 }
521 struct T;
522
523 impl Test for T {
524     fn test() {
525     $0
526 }
527 }
528 "#,
529         );
530     }
531
532     #[test]
533     fn hide_implemented_fn() {
534         check(
535             r#"
536 trait Test {
537     fn foo();
538     fn foo_bar();
539 }
540 struct T;
541
542 impl Test for T {
543     fn foo() {}
544     fn f$0
545 }
546 "#,
547             expect![[r#"
548                 fn fn foo_bar()
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 }