]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/completions/trait_impl.rs
Mark HasSource::source_old as deprecated but allow at all call sites
[rust.git] / crates / 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<|>
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() {}<|>
31 //! }
32 //! ```
33
34 use hir::{self, HasAttrs, HasSource};
35 use ide_db::traits::get_missing_assoc_items;
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 <|> }`, 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 <|> }`
94         // ERROR      0
95         //   CONST_KW <- *
96         SyntaxKind::CONST_KW => 0,
97         // `impl .. { fn/type <|> }`
98         // FN/TYPE_ALIAS  0
99         //   FN_KW        <- *
100         SyntaxKind::FN_KW | SyntaxKind::TYPE_KW => 0,
101         // `impl .. { fn/type/const foo<|> }`
102         // FN/TYPE_ALIAS/CONST  1
103         //  NAME                0
104         //    IDENT             <- *
105         SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
106         // `impl .. { foo<|> }`
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 <|> fn/type/const }`
124         _ if token.kind() == SyntaxKind::CONST_KW => 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 builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
149         .lookup_by(fn_name)
150         .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::Function
156     };
157     let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
158
159     #[allow(deprecated)]
160     let function_decl = function_declaration(&func.source_old(ctx.db).value);
161     match ctx.config.snippet_cap {
162         Some(cap) => {
163             let snippet = format!("{} {{\n    $0\n}}", function_decl);
164             builder.snippet_edit(cap, TextEdit::replace(range, snippet))
165         }
166         None => {
167             let header = format!("{} {{", function_decl);
168             builder.text_edit(TextEdit::replace(range, header))
169         }
170     }
171     .kind(completion_kind)
172     .add_to(acc);
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     CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
188         .text_edit(TextEdit::replace(range, snippet))
189         .lookup_by(alias_name)
190         .kind(CompletionItemKind::TypeAlias)
191         .set_documentation(type_alias.docs(ctx.db))
192         .add_to(acc);
193 }
194
195 fn add_const_impl(
196     const_def_node: &SyntaxNode,
197     acc: &mut Completions,
198     ctx: &CompletionContext,
199     const_: hir::Const,
200 ) {
201     let const_name = const_.name(ctx.db).map(|n| n.to_string());
202
203     if let Some(const_name) = const_name {
204         #[allow(deprecated)]
205         let snippet = make_const_compl_syntax(&const_.source_old(ctx.db).value);
206
207         let range = TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
208
209         CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
210             .text_edit(TextEdit::replace(range, snippet))
211             .lookup_by(const_name)
212             .kind(CompletionItemKind::Const)
213             .set_documentation(const_.docs(ctx.db))
214             .add_to(acc);
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 #[cfg(test)]
242 mod tests {
243     use expect_test::{expect, Expect};
244
245     use crate::{
246         test_utils::{check_edit, completion_list},
247         CompletionKind,
248     };
249
250     fn check(ra_fixture: &str, expect: Expect) {
251         let actual = completion_list(ra_fixture, CompletionKind::Magic);
252         expect.assert_eq(&actual)
253     }
254
255     #[test]
256     fn name_ref_function_type_const() {
257         check(
258             r#"
259 trait Test {
260     type TestType;
261     const TEST_CONST: u16;
262     fn test();
263 }
264 struct T;
265
266 impl Test for T {
267     t<|>
268 }
269 "#,
270             expect![["
271 ta type TestType = \n\
272 ct const TEST_CONST: u16 = \n\
273 fn fn test()
274 "]],
275         );
276     }
277
278     #[test]
279     fn no_completion_inside_fn() {
280         check(
281             r"
282 trait Test { fn test(); fn test2(); }
283 struct T;
284
285 impl Test for T {
286     fn test() {
287         t<|>
288     }
289 }
290 ",
291             expect![[""]],
292         );
293
294         check(
295             r"
296 trait Test { fn test(); fn test2(); }
297 struct T;
298
299 impl Test for T {
300     fn test() {
301         fn t<|>
302     }
303 }
304 ",
305             expect![[""]],
306         );
307
308         check(
309             r"
310 trait Test { fn test(); fn test2(); }
311 struct T;
312
313 impl Test for T {
314     fn test() {
315         fn <|>
316     }
317 }
318 ",
319             expect![[""]],
320         );
321
322         // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
323         check(
324             r"
325 trait Test { fn test(); fn test2(); }
326 struct T;
327
328 impl Test for T {
329     fn test() {
330         foo.<|>
331     }
332 }
333 ",
334             expect![[""]],
335         );
336
337         check(
338             r"
339 trait Test { fn test(_: i32); fn test2(); }
340 struct T;
341
342 impl Test for T {
343     fn test(t<|>)
344 }
345 ",
346             expect![[""]],
347         );
348
349         check(
350             r"
351 trait Test { fn test(_: fn()); fn test2(); }
352 struct T;
353
354 impl Test for T {
355     fn test(f: fn <|>)
356 }
357 ",
358             expect![[""]],
359         );
360     }
361
362     #[test]
363     fn no_completion_inside_const() {
364         check(
365             r"
366 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
367 struct T;
368
369 impl Test for T {
370     const TEST: fn <|>
371 }
372 ",
373             expect![[""]],
374         );
375
376         check(
377             r"
378 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
379 struct T;
380
381 impl Test for T {
382     const TEST: T<|>
383 }
384 ",
385             expect![[""]],
386         );
387
388         check(
389             r"
390 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
391 struct T;
392
393 impl Test for T {
394     const TEST: u32 = f<|>
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: u32 = {
407         t<|>
408     };
409 }
410 ",
411             expect![[""]],
412         );
413
414         check(
415             r"
416 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
417 struct T;
418
419 impl Test for T {
420     const TEST: u32 = {
421         fn <|>
422     };
423 }
424 ",
425             expect![[""]],
426         );
427
428         check(
429             r"
430 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
431 struct T;
432
433 impl Test for T {
434     const TEST: u32 = {
435         fn t<|>
436     };
437 }
438 ",
439             expect![[""]],
440         );
441     }
442
443     #[test]
444     fn no_completion_inside_type() {
445         check(
446             r"
447 trait Test { type Test; type Test2; fn test(); }
448 struct T;
449
450 impl Test for T {
451     type Test = T<|>;
452 }
453 ",
454             expect![[""]],
455         );
456
457         check(
458             r"
459 trait Test { type Test; type Test2; fn test(); }
460 struct T;
461
462 impl Test for T {
463     type Test = fn <|>;
464 }
465 ",
466             expect![[""]],
467         );
468     }
469
470     #[test]
471     fn name_ref_single_function() {
472         check_edit(
473             "test",
474             r#"
475 trait Test {
476     fn test();
477 }
478 struct T;
479
480 impl Test for T {
481     t<|>
482 }
483 "#,
484             r#"
485 trait Test {
486     fn test();
487 }
488 struct T;
489
490 impl Test for T {
491     fn test() {
492     $0
493 }
494 }
495 "#,
496         );
497     }
498
499     #[test]
500     fn single_function() {
501         check_edit(
502             "test",
503             r#"
504 trait Test {
505     fn test();
506 }
507 struct T;
508
509 impl Test for T {
510     fn t<|>
511 }
512 "#,
513             r#"
514 trait Test {
515     fn test();
516 }
517 struct T;
518
519 impl Test for T {
520     fn test() {
521     $0
522 }
523 }
524 "#,
525         );
526     }
527
528     #[test]
529     fn hide_implemented_fn() {
530         check(
531             r#"
532 trait Test {
533     fn foo();
534     fn foo_bar();
535 }
536 struct T;
537
538 impl Test for T {
539     fn foo() {}
540     fn f<|>
541 }
542 "#,
543             expect![[r#"
544                 fn fn foo_bar()
545             "#]],
546         );
547     }
548
549     #[test]
550     fn generic_fn() {
551         check_edit(
552             "foo",
553             r#"
554 trait Test {
555     fn foo<T>();
556 }
557 struct T;
558
559 impl Test for T {
560     fn f<|>
561 }
562 "#,
563             r#"
564 trait Test {
565     fn foo<T>();
566 }
567 struct T;
568
569 impl Test for T {
570     fn foo<T>() {
571     $0
572 }
573 }
574 "#,
575         );
576         check_edit(
577             "foo",
578             r#"
579 trait Test {
580     fn foo<T>() where T: Into<String>;
581 }
582 struct T;
583
584 impl Test for T {
585     fn f<|>
586 }
587 "#,
588             r#"
589 trait Test {
590     fn foo<T>() where T: Into<String>;
591 }
592 struct T;
593
594 impl Test for T {
595     fn foo<T>()
596 where T: Into<String> {
597     $0
598 }
599 }
600 "#,
601         );
602     }
603
604     #[test]
605     fn associated_type() {
606         check_edit(
607             "SomeType",
608             r#"
609 trait Test {
610     type SomeType;
611 }
612
613 impl Test for () {
614     type S<|>
615 }
616 "#,
617             "
618 trait Test {
619     type SomeType;
620 }
621
622 impl Test for () {
623     type SomeType = \n\
624 }
625 ",
626         );
627     }
628
629     #[test]
630     fn associated_const() {
631         check_edit(
632             "SOME_CONST",
633             r#"
634 trait Test {
635     const SOME_CONST: u16;
636 }
637
638 impl Test for () {
639     const S<|>
640 }
641 "#,
642             "
643 trait Test {
644     const SOME_CONST: u16;
645 }
646
647 impl Test for () {
648     const SOME_CONST: u16 = \n\
649 }
650 ",
651         );
652
653         check_edit(
654             "SOME_CONST",
655             r#"
656 trait Test {
657     const SOME_CONST: u16 = 92;
658 }
659
660 impl Test for () {
661     const S<|>
662 }
663 "#,
664             "
665 trait Test {
666     const SOME_CONST: u16 = 92;
667 }
668
669 impl Test for () {
670     const SOME_CONST: u16 = \n\
671 }
672 ",
673         );
674     }
675
676     #[test]
677     fn complete_without_name() {
678         let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
679             println!(
680                 "completion='{}', hint='{}', next_sibling='{}'",
681                 completion, hint, next_sibling
682             );
683
684             check_edit(
685                 completion,
686                 &format!(
687                     r#"
688 trait Test {{
689     type Foo;
690     const CONST: u16;
691     fn bar();
692 }}
693 struct T;
694
695 impl Test for T {{
696     {}
697     {}
698 }}
699 "#,
700                     hint, next_sibling
701                 ),
702                 &format!(
703                     r#"
704 trait Test {{
705     type Foo;
706     const CONST: u16;
707     fn bar();
708 }}
709 struct T;
710
711 impl Test for T {{
712     {}
713     {}
714 }}
715 "#,
716                     completed, next_sibling
717                 ),
718             )
719         };
720
721         // Enumerate some possible next siblings.
722         for next_sibling in &[
723             "",
724             "fn other_fn() {}", // `const <|> fn` -> `const fn`
725             "type OtherType = i32;",
726             "const OTHER_CONST: i32 = 0;",
727             "async fn other_fn() {}",
728             "unsafe fn other_fn() {}",
729             "default fn other_fn() {}",
730             "default type OtherType = i32;",
731             "default const OTHER_CONST: i32 = 0;",
732         ] {
733             test("bar", "fn <|>", "fn bar() {\n    $0\n}", next_sibling);
734             test("Foo", "type <|>", "type Foo = ", next_sibling);
735             test("CONST", "const <|>", "const CONST: u16 = ", next_sibling);
736         }
737     }
738 }