1 //! Completion for associated items in a trait implementation.
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`.
10 //! Considering the following trait `impl`:
17 //! impl SomeTrait for () {
22 //! may result in the completion of the following method:
25 //! # trait SomeTrait {
29 //! impl SomeTrait for () {
34 use hir::{self, HasAttrs, HasSource};
35 use ide_db::traits::get_missing_assoc_items;
37 ast::{self, edit, Impl},
38 display::function_declaration,
39 AstNode, SyntaxKind, SyntaxNode, TextRange, T,
41 use text_edit::TextEdit;
49 // display::function_declaration,
52 #[derive(Debug, PartialEq, Eq)]
53 enum ImplCompletionKind {
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 =>
66 add_function_impl(&trigger, acc, ctx, fn_item)
68 hir::AssocItem::TypeAlias(type_item)
69 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
71 add_type_alias_impl(&trigger, acc, ctx, type_item)
73 hir::AssocItem::Const(const_item)
74 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
76 add_const_impl(&trigger, acc, ctx, const_item)
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()?;
92 let impl_item_offset = match token.kind() {
93 // `impl .. { const <|> }`
96 SyntaxKind::CONST_KW => 0,
97 // `impl .. { fn/type <|> }`
100 SyntaxKind::FN_KW | SyntaxKind::TYPE_KW => 0,
101 // `impl .. { fn/type/const foo<|> }`
102 // FN/TYPE_ALIAS/CONST 1
105 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
106 // `impl .. { foo<|> }`
112 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
116 let impl_item = token.ancestors().nth(impl_item_offset)?;
117 // Must directly belong to an impl block.
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,
131 Some((kind, impl_item, impl_def))
134 fn add_function_impl(
135 fn_def_node: &SyntaxNode,
136 acc: &mut Completions,
137 ctx: &CompletionContext,
140 let fn_name = func.name(ctx.db).to_string();
142 let label = if func.assoc_fn_params(ctx.db).is_empty() {
143 format!("fn {}()", fn_name)
145 format!("fn {}(..)", fn_name)
148 let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
150 .set_documentation(func.docs(ctx.db));
152 let completion_kind = if func.self_param(ctx.db).is_some() {
153 CompletionItemKind::Method
155 CompletionItemKind::Function
157 let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
160 let function_decl = function_declaration(&func.source_old(ctx.db).value);
161 match ctx.config.snippet_cap {
163 let snippet = format!("{} {{\n $0\n}}", function_decl);
164 builder.snippet_edit(cap, TextEdit::replace(range, snippet))
167 let header = format!("{} {{", function_decl);
168 builder.text_edit(TextEdit::replace(range, header))
171 .kind(completion_kind)
175 fn add_type_alias_impl(
176 type_def_node: &SyntaxNode,
177 acc: &mut Completions,
178 ctx: &CompletionContext,
179 type_alias: hir::TypeAlias,
181 let alias_name = type_alias.name(ctx.db).to_string();
183 let snippet = format!("type {} = ", alias_name);
185 let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
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))
196 const_def_node: &SyntaxNode,
197 acc: &mut Completions,
198 ctx: &CompletionContext,
201 let const_name = const_.name(ctx.db).map(|n| n.to_string());
203 if let Some(const_name) = const_name {
205 let snippet = make_const_compl_syntax(&const_.source_old(ctx.db).value);
207 let range = TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
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))
218 fn make_const_compl_syntax(const_: &ast::Const) -> String {
219 let const_ = edit::remove_attrs_and_docs(const_);
221 let const_start = const_.syntax().text_range().start();
222 let const_end = const_.syntax().text_range().end();
225 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
229 .children_with_tokens()
230 .find(|s| s.kind() == T![;] || s.kind() == T![=])
231 .map_or(const_end, |f| f.text_range().start());
233 let len = end - start;
234 let range = TextRange::new(0.into(), len);
236 let syntax = const_.syntax().text().slice(range).to_string();
238 format!("{} = ", syntax.trim_end())
243 use expect_test::{expect, Expect};
246 test_utils::{check_edit, completion_list},
250 fn check(ra_fixture: &str, expect: Expect) {
251 let actual = completion_list(ra_fixture, CompletionKind::Magic);
252 expect.assert_eq(&actual)
256 fn name_ref_function_type_const() {
261 const TEST_CONST: u16;
271 ta type TestType = \n\
272 ct const TEST_CONST: u16 = \n\
279 fn no_completion_inside_fn() {
282 trait Test { fn test(); fn test2(); }
296 trait Test { fn test(); fn test2(); }
310 trait Test { fn test(); fn test2(); }
322 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
325 trait Test { fn test(); fn test2(); }
339 trait Test { fn test(_: i32); fn test2(); }
351 trait Test { fn test(_: fn()); fn test2(); }
363 fn no_completion_inside_const() {
366 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
378 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
390 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
394 const TEST: u32 = f<|>
402 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
416 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
430 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
444 fn no_completion_inside_type() {
447 trait Test { type Test; type Test2; fn test(); }
459 trait Test { type Test; type Test2; fn test(); }
471 fn name_ref_single_function() {
500 fn single_function() {
529 fn hide_implemented_fn() {
580 fn foo<T>() where T: Into<String>;
590 fn foo<T>() where T: Into<String>;
596 where T: Into<String> {
605 fn associated_type() {
630 fn associated_const() {
635 const SOME_CONST: u16;
644 const SOME_CONST: u16;
648 const SOME_CONST: u16 = \n\
657 const SOME_CONST: u16 = 92;
666 const SOME_CONST: u16 = 92;
670 const SOME_CONST: u16 = \n\
677 fn complete_without_name() {
678 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
680 "completion='{}', hint='{}', next_sibling='{}'",
681 completion, hint, next_sibling
716 completed, next_sibling
721 // Enumerate some possible next siblings.
722 for next_sibling in &[
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;",
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);