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, SymbolKind};
38 display::function_declaration,
39 AstNode, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, T,
41 use text_edit::TextEdit;
43 use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions};
45 #[derive(Debug, PartialEq, Eq)]
46 enum ImplCompletionKind {
53 pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
54 if let Some((kind, trigger, impl_def)) = completion_match(ctx.token.clone()) {
55 get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
56 hir::AssocItem::Function(fn_item)
57 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
59 add_function_impl(&trigger, acc, ctx, fn_item)
61 hir::AssocItem::TypeAlias(type_item)
62 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
64 add_type_alias_impl(&trigger, acc, ctx, type_item)
66 hir::AssocItem::Const(const_item)
67 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
69 add_const_impl(&trigger, acc, ctx, const_item)
76 fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
77 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
78 // the whitespace token, which is outside `FN` syntax node.
79 // We need to follow the previous token in this case.
80 if token.kind() == SyntaxKind::WHITESPACE {
81 token = token.prev_token()?;
84 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
85 let impl_item_offset = match token.kind() {
86 // `impl .. { const $0 }`
90 // `impl .. { fn/type $0 }`
93 T![fn] | T![type] => 0,
94 // `impl .. { fn/type/const foo$0 }`
95 // FN/TYPE_ALIAS/CONST 1
98 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
99 // `impl .. { foo$0 }`
105 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
109 let impl_item = token.ancestors().nth(impl_item_offset)?;
110 // Must directly belong to an impl block.
114 let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
115 let kind = match impl_item.kind() {
116 // `impl ... { const $0 fn/type/const }`
117 _ if token.kind() == T![const] => ImplCompletionKind::Const,
118 SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
119 SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
120 SyntaxKind::FN => ImplCompletionKind::Fn,
121 SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
124 Some((kind, impl_item, impl_def))
127 fn add_function_impl(
128 fn_def_node: &SyntaxNode,
129 acc: &mut Completions,
130 ctx: &CompletionContext,
133 let fn_name = func.name(ctx.db).to_string();
135 let label = if func.assoc_fn_params(ctx.db).is_empty() {
136 format!("fn {}()", fn_name)
138 format!("fn {}(..)", fn_name)
141 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
142 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
144 let completion_kind = if func.self_param(ctx.db).is_some() {
145 CompletionItemKind::Method
147 CompletionItemKind::SymbolKind(SymbolKind::Function)
149 let range = replacement_range(ctx, fn_def_node);
150 if let Some(src) = func.source(ctx.db) {
151 let function_decl = function_declaration(&src.value);
152 match ctx.config.snippet_cap {
154 let snippet = format!("{} {{\n $0\n}}", function_decl);
155 item.snippet_edit(cap, TextEdit::replace(range, snippet));
158 let header = format!("{} {{", function_decl);
159 item.text_edit(TextEdit::replace(range, header));
162 item.kind(completion_kind);
167 fn add_type_alias_impl(
168 type_def_node: &SyntaxNode,
169 acc: &mut Completions,
170 ctx: &CompletionContext,
171 type_alias: hir::TypeAlias,
173 let alias_name = type_alias.name(ctx.db).to_string();
175 let snippet = format!("type {} = ", alias_name);
177 let range = replacement_range(ctx, type_def_node);
178 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
179 item.text_edit(TextEdit::replace(range, snippet))
180 .lookup_by(alias_name)
181 .kind(SymbolKind::TypeAlias)
182 .set_documentation(type_alias.docs(ctx.db));
187 const_def_node: &SyntaxNode,
188 acc: &mut Completions,
189 ctx: &CompletionContext,
192 let const_name = const_.name(ctx.db).map(|n| n.to_string());
194 if let Some(const_name) = const_name {
195 if let Some(source) = const_.source(ctx.db) {
196 let snippet = make_const_compl_syntax(&source.value);
198 let range = replacement_range(ctx, const_def_node);
200 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
201 item.text_edit(TextEdit::replace(range, snippet))
202 .lookup_by(const_name)
203 .kind(SymbolKind::Const)
204 .set_documentation(const_.docs(ctx.db));
210 fn make_const_compl_syntax(const_: &ast::Const) -> String {
211 let const_ = edit::remove_attrs_and_docs(const_);
213 let const_start = const_.syntax().text_range().start();
214 let const_end = const_.syntax().text_range().end();
217 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
221 .children_with_tokens()
222 .find(|s| s.kind() == T![;] || s.kind() == T![=])
223 .map_or(const_end, |f| f.text_range().start());
225 let len = end - start;
226 let range = TextRange::new(0.into(), len);
228 let syntax = const_.syntax().text().slice(range).to_string();
230 format!("{} = ", syntax.trim_end())
233 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
234 let first_child = item
235 .children_with_tokens()
237 !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
239 .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
241 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
246 use expect_test::{expect, Expect};
249 tests::{check_edit, filtered_completion_list},
253 fn check(ra_fixture: &str, expect: Expect) {
254 let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
255 expect.assert_eq(&actual)
259 fn name_ref_function_type_const() {
264 const TEST_CONST: u16;
274 ta type TestType = \n\
275 ct const TEST_CONST: u16 = \n\
282 fn no_completion_inside_fn() {
285 trait Test { fn test(); fn test2(); }
299 trait Test { fn test(); fn test2(); }
313 trait Test { fn test(); fn test2(); }
325 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
328 trait Test { fn test(); fn test2(); }
342 trait Test { fn test(_: i32); fn test2(); }
354 trait Test { fn test(_: fn()); fn test2(); }
366 fn no_completion_inside_const() {
369 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
381 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
393 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
397 const TEST: u32 = f$0
405 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
419 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
433 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
447 fn no_completion_inside_type() {
450 trait Test { type Test; type Test2; fn test(); }
462 trait Test { type Test; type Test2; fn test(); }
474 fn name_ref_single_function() {
503 fn single_function() {
532 fn hide_implemented_fn() {
583 fn foo<T>() where T: Into<String>;
593 fn foo<T>() where T: Into<String>;
599 where T: Into<String> {
608 fn associated_type() {
633 fn associated_const() {
638 const SOME_CONST: u16;
647 const SOME_CONST: u16;
651 const SOME_CONST: u16 = \n\
660 const SOME_CONST: u16 = 92;
669 const SOME_CONST: u16 = 92;
673 const SOME_CONST: u16 = \n\
680 fn complete_without_name() {
681 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
714 completed, next_sibling
719 // Enumerate some possible next siblings.
720 for next_sibling in &[
722 "fn other_fn() {}", // `const $0 fn` -> `const fn`
723 "type OtherType = i32;",
724 "const OTHER_CONST: i32 = 0;",
725 "async fn other_fn() {}",
726 "unsafe fn other_fn() {}",
727 "default fn other_fn() {}",
728 "default type OtherType = i32;",
729 "default const OTHER_CONST: i32 = 0;",
731 test("bar", "fn $0", "fn bar() {\n $0\n}", next_sibling);
732 test("Foo", "type $0", "type Foo = ", next_sibling);
733 test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
738 fn snippet_does_not_overwrite_comment_or_attr() {
739 let test = |completion: &str, hint: &str, completed: &str| {
747 const CONST: i32 = 0;
764 const CONST: i32 = 0;
778 test("function", "fn f$0", "fn function() {\n $0\n}");
779 test("Type", "type T$0", "type Type = ");
780 test("CONST", "const C$0", "const CONST: i32 = ");