]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/trait_impl.rs
Fix: Do not overwrite comments and attrs in trait impl completion
[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, SyntaxElement, 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 = replacement_range(ctx, fn_def_node);
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                 item.snippet_edit(cap, TextEdit::replace(range, snippet));
164             }
165             None => {
166                 let header = format!("{} {{", function_decl);
167                 item.text_edit(TextEdit::replace(range, header));
168             }
169         };
170         item.kind(completion_kind);
171         item.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 = replacement_range(ctx, type_def_node);
186     let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
187     item.text_edit(TextEdit::replace(range, snippet))
188         .lookup_by(alias_name)
189         .kind(SymbolKind::TypeAlias)
190         .set_documentation(type_alias.docs(ctx.db));
191     item.add_to(acc);
192 }
193
194 fn add_const_impl(
195     const_def_node: &SyntaxNode,
196     acc: &mut Completions,
197     ctx: &CompletionContext,
198     const_: hir::Const,
199 ) {
200     let const_name = const_.name(ctx.db).map(|n| n.to_string());
201
202     if let Some(const_name) = const_name {
203         if let Some(source) = const_.source(ctx.db) {
204             let snippet = make_const_compl_syntax(&source.value);
205
206             let range = replacement_range(ctx, const_def_node);
207             let mut item =
208                 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
209             item.text_edit(TextEdit::replace(range, snippet))
210                 .lookup_by(const_name)
211                 .kind(SymbolKind::Const)
212                 .set_documentation(const_.docs(ctx.db));
213             item.add_to(acc);
214         }
215     }
216 }
217
218 fn make_const_compl_syntax(const_: &ast::Const) -> String {
219     let const_ = edit::remove_attrs_and_docs(const_);
220
221     let const_start = const_.syntax().text_range().start();
222     let const_end = const_.syntax().text_range().end();
223
224     let start =
225         const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
226
227     let end = const_
228         .syntax()
229         .children_with_tokens()
230         .find(|s| s.kind() == T![;] || s.kind() == T![=])
231         .map_or(const_end, |f| f.text_range().start());
232
233     let len = end - start;
234     let range = TextRange::new(0.into(), len);
235
236     let syntax = const_.syntax().text().slice(range).to_string();
237
238     format!("{} = ", syntax.trim_end())
239 }
240
241 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
242     let first_child = item
243         .children_with_tokens()
244         .find(|child| {
245             let kind = child.kind();
246             match kind {
247                 SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR => false,
248                 _ => true,
249             }
250         })
251         .unwrap_or(SyntaxElement::Node(item.clone()));
252
253     TextRange::new(first_child.text_range().start(), ctx.source_range().end())
254 }
255
256 #[cfg(test)]
257 mod tests {
258     use expect_test::{expect, Expect};
259
260     use crate::{
261         test_utils::{check_edit, completion_list},
262         CompletionKind,
263     };
264
265     fn check(ra_fixture: &str, expect: Expect) {
266         let actual = completion_list(ra_fixture, CompletionKind::Magic);
267         expect.assert_eq(&actual)
268     }
269
270     #[test]
271     fn name_ref_function_type_const() {
272         check(
273             r#"
274 trait Test {
275     type TestType;
276     const TEST_CONST: u16;
277     fn test();
278 }
279 struct T;
280
281 impl Test for T {
282     t$0
283 }
284 "#,
285             expect![["
286 ta type TestType = \n\
287 ct const TEST_CONST: u16 = \n\
288 fn fn test()
289 "]],
290         );
291     }
292
293     #[test]
294     fn no_completion_inside_fn() {
295         check(
296             r"
297 trait Test { fn test(); fn test2(); }
298 struct T;
299
300 impl Test for T {
301     fn test() {
302         t$0
303     }
304 }
305 ",
306             expect![[""]],
307         );
308
309         check(
310             r"
311 trait Test { fn test(); fn test2(); }
312 struct T;
313
314 impl Test for T {
315     fn test() {
316         fn t$0
317     }
318 }
319 ",
320             expect![[""]],
321         );
322
323         check(
324             r"
325 trait Test { fn test(); fn test2(); }
326 struct T;
327
328 impl Test for T {
329     fn test() {
330         fn $0
331     }
332 }
333 ",
334             expect![[""]],
335         );
336
337         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
338         check(
339             r"
340 trait Test { fn test(); fn test2(); }
341 struct T;
342
343 impl Test for T {
344     fn test() {
345         foo.$0
346     }
347 }
348 ",
349             expect![[""]],
350         );
351
352         check(
353             r"
354 trait Test { fn test(_: i32); fn test2(); }
355 struct T;
356
357 impl Test for T {
358     fn test(t$0)
359 }
360 ",
361             expect![[""]],
362         );
363
364         check(
365             r"
366 trait Test { fn test(_: fn()); fn test2(); }
367 struct T;
368
369 impl Test for T {
370     fn test(f: fn $0)
371 }
372 ",
373             expect![[""]],
374         );
375     }
376
377     #[test]
378     fn no_completion_inside_const() {
379         check(
380             r"
381 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
382 struct T;
383
384 impl Test for T {
385     const TEST: fn $0
386 }
387 ",
388             expect![[""]],
389         );
390
391         check(
392             r"
393 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
394 struct T;
395
396 impl Test for T {
397     const TEST: T$0
398 }
399 ",
400             expect![[""]],
401         );
402
403         check(
404             r"
405 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
406 struct T;
407
408 impl Test for T {
409     const TEST: u32 = f$0
410 }
411 ",
412             expect![[""]],
413         );
414
415         check(
416             r"
417 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
418 struct T;
419
420 impl Test for T {
421     const TEST: u32 = {
422         t$0
423     };
424 }
425 ",
426             expect![[""]],
427         );
428
429         check(
430             r"
431 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
432 struct T;
433
434 impl Test for T {
435     const TEST: u32 = {
436         fn $0
437     };
438 }
439 ",
440             expect![[""]],
441         );
442
443         check(
444             r"
445 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
446 struct T;
447
448 impl Test for T {
449     const TEST: u32 = {
450         fn t$0
451     };
452 }
453 ",
454             expect![[""]],
455         );
456     }
457
458     #[test]
459     fn no_completion_inside_type() {
460         check(
461             r"
462 trait Test { type Test; type Test2; fn test(); }
463 struct T;
464
465 impl Test for T {
466     type Test = T$0;
467 }
468 ",
469             expect![[""]],
470         );
471
472         check(
473             r"
474 trait Test { type Test; type Test2; fn test(); }
475 struct T;
476
477 impl Test for T {
478     type Test = fn $0;
479 }
480 ",
481             expect![[""]],
482         );
483     }
484
485     #[test]
486     fn name_ref_single_function() {
487         check_edit(
488             "test",
489             r#"
490 trait Test {
491     fn test();
492 }
493 struct T;
494
495 impl Test for T {
496     t$0
497 }
498 "#,
499             r#"
500 trait Test {
501     fn test();
502 }
503 struct T;
504
505 impl Test for T {
506     fn test() {
507     $0
508 }
509 }
510 "#,
511         );
512     }
513
514     #[test]
515     fn single_function() {
516         check_edit(
517             "test",
518             r#"
519 trait Test {
520     fn test();
521 }
522 struct T;
523
524 impl Test for T {
525     fn t$0
526 }
527 "#,
528             r#"
529 trait Test {
530     fn test();
531 }
532 struct T;
533
534 impl Test for T {
535     fn test() {
536     $0
537 }
538 }
539 "#,
540         );
541     }
542
543     #[test]
544     fn hide_implemented_fn() {
545         check(
546             r#"
547 trait Test {
548     fn foo();
549     fn foo_bar();
550 }
551 struct T;
552
553 impl Test for T {
554     fn foo() {}
555     fn f$0
556 }
557 "#,
558             expect![[r#"
559                 fn fn foo_bar()
560             "#]],
561         );
562     }
563
564     #[test]
565     fn generic_fn() {
566         check_edit(
567             "foo",
568             r#"
569 trait Test {
570     fn foo<T>();
571 }
572 struct T;
573
574 impl Test for T {
575     fn f$0
576 }
577 "#,
578             r#"
579 trait Test {
580     fn foo<T>();
581 }
582 struct T;
583
584 impl Test for T {
585     fn foo<T>() {
586     $0
587 }
588 }
589 "#,
590         );
591         check_edit(
592             "foo",
593             r#"
594 trait Test {
595     fn foo<T>() where T: Into<String>;
596 }
597 struct T;
598
599 impl Test for T {
600     fn f$0
601 }
602 "#,
603             r#"
604 trait Test {
605     fn foo<T>() where T: Into<String>;
606 }
607 struct T;
608
609 impl Test for T {
610     fn foo<T>()
611 where T: Into<String> {
612     $0
613 }
614 }
615 "#,
616         );
617     }
618
619     #[test]
620     fn associated_type() {
621         check_edit(
622             "SomeType",
623             r#"
624 trait Test {
625     type SomeType;
626 }
627
628 impl Test for () {
629     type S$0
630 }
631 "#,
632             "
633 trait Test {
634     type SomeType;
635 }
636
637 impl Test for () {
638     type SomeType = \n\
639 }
640 ",
641         );
642     }
643
644     #[test]
645     fn associated_const() {
646         check_edit(
647             "SOME_CONST",
648             r#"
649 trait Test {
650     const SOME_CONST: u16;
651 }
652
653 impl Test for () {
654     const S$0
655 }
656 "#,
657             "
658 trait Test {
659     const SOME_CONST: u16;
660 }
661
662 impl Test for () {
663     const SOME_CONST: u16 = \n\
664 }
665 ",
666         );
667
668         check_edit(
669             "SOME_CONST",
670             r#"
671 trait Test {
672     const SOME_CONST: u16 = 92;
673 }
674
675 impl Test for () {
676     const S$0
677 }
678 "#,
679             "
680 trait Test {
681     const SOME_CONST: u16 = 92;
682 }
683
684 impl Test for () {
685     const SOME_CONST: u16 = \n\
686 }
687 ",
688         );
689     }
690
691     #[test]
692     fn complete_without_name() {
693         let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
694             check_edit(
695                 completion,
696                 &format!(
697                     r#"
698 trait Test {{
699     type Foo;
700     const CONST: u16;
701     fn bar();
702 }}
703 struct T;
704
705 impl Test for T {{
706     {}
707     {}
708 }}
709 "#,
710                     hint, next_sibling
711                 ),
712                 &format!(
713                     r#"
714 trait Test {{
715     type Foo;
716     const CONST: u16;
717     fn bar();
718 }}
719 struct T;
720
721 impl Test for T {{
722     {}
723     {}
724 }}
725 "#,
726                     completed, next_sibling
727                 ),
728             )
729         };
730
731         // Enumerate some possible next siblings.
732         for next_sibling in &[
733             "",
734             "fn other_fn() {}", // `const $0 fn` -> `const fn`
735             "type OtherType = i32;",
736             "const OTHER_CONST: i32 = 0;",
737             "async fn other_fn() {}",
738             "unsafe fn other_fn() {}",
739             "default fn other_fn() {}",
740             "default type OtherType = i32;",
741             "default const OTHER_CONST: i32 = 0;",
742         ] {
743             test("bar", "fn $0", "fn bar() {\n    $0\n}", next_sibling);
744             test("Foo", "type $0", "type Foo = ", next_sibling);
745             test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
746         }
747     }
748
749     #[test]
750     fn snippet_does_not_overwrite_comment_or_attr() {
751         let test = |completion: &str, hint: &str, completed: &str| {
752             check_edit(
753                 completion,
754                 &format!(
755                     r#"
756 trait Foo {{
757     type Type;
758     fn function();
759     const CONST: i32 = 0;
760 }}
761 struct T;
762
763 impl Foo for T {{
764     // Comment
765     #[bar]
766     {}
767 }}
768 "#,
769                     hint
770                 ),
771                 &format!(
772                     r#"
773 trait Foo {{
774     type Type;
775     fn function();
776     const CONST: i32 = 0;
777 }}
778 struct T;
779
780 impl Foo for T {{
781     // Comment
782     #[bar]
783     {}
784 }}
785 "#,
786                     completed
787                 ),
788             )
789         };
790         test("function", "fn f$0", "fn function() {\n    $0\n}");
791         test("Type", "type T$0", "type Type = ");
792         test("CONST", "const C$0", "const CONST: i32 = ");
793     }
794 }