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 assists::utils::get_missing_assoc_items;
35 use hir::{self, HasAttrs, HasSource};
37 ast::{self, edit, Impl},
38 AstNode, SyntaxKind, SyntaxNode, TextRange, T,
40 use text_edit::TextEdit;
44 CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
46 display::function_declaration,
49 #[derive(Debug, PartialEq, Eq)]
50 enum ImplCompletionKind {
57 pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
58 if let Some((kind, trigger, impl_def)) = completion_match(ctx) {
59 get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
60 hir::AssocItem::Function(fn_item)
61 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
63 add_function_impl(&trigger, acc, ctx, fn_item)
65 hir::AssocItem::TypeAlias(type_item)
66 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
68 add_type_alias_impl(&trigger, acc, ctx, type_item)
70 hir::AssocItem::Const(const_item)
71 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
73 add_const_impl(&trigger, acc, ctx, const_item)
80 fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
81 let mut token = ctx.token.clone();
82 // For keywork without name like `impl .. { fn <|> }`, the current position is inside
83 // the whitespace token, which is outside `FN` syntax node.
84 // We need to follow the previous token in this case.
85 if token.kind() == SyntaxKind::WHITESPACE {
86 token = token.prev_token()?;
89 let impl_item_offset = match token.kind() {
90 // `impl .. { const <|> }`
93 SyntaxKind::CONST_KW => 0,
94 // `impl .. { fn/type <|> }`
97 SyntaxKind::FN_KW | SyntaxKind::TYPE_KW => 0,
98 // `impl .. { fn/type/const foo<|> }`
99 // FN/TYPE_ALIAS/CONST 1
102 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
103 // `impl .. { foo<|> }`
109 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
113 let impl_item = token.ancestors().nth(impl_item_offset)?;
114 // Must directly belong to an impl block.
118 let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
119 let kind = match impl_item.kind() {
120 // `impl ... { const <|> fn/type/const }`
121 _ if token.kind() == SyntaxKind::CONST_KW => ImplCompletionKind::Const,
122 SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
123 SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
124 SyntaxKind::FN => ImplCompletionKind::Fn,
125 SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
128 Some((kind, impl_item, impl_def))
131 fn add_function_impl(
132 fn_def_node: &SyntaxNode,
133 acc: &mut Completions,
134 ctx: &CompletionContext,
137 let fn_name = func.name(ctx.db).to_string();
139 let label = if func.params(ctx.db).is_empty() {
140 format!("fn {}()", fn_name)
142 format!("fn {}(..)", fn_name)
145 let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
147 .set_documentation(func.docs(ctx.db));
149 let completion_kind = if func.self_param(ctx.db).is_some() {
150 CompletionItemKind::Method
152 CompletionItemKind::Function
154 let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
156 let function_decl = function_declaration(&func.source(ctx.db).value);
157 match ctx.config.snippet_cap {
159 let snippet = format!("{} {{\n $0\n}}", function_decl);
160 builder.snippet_edit(cap, TextEdit::replace(range, snippet))
163 let header = format!("{} {{", function_decl);
164 builder.text_edit(TextEdit::replace(range, header))
167 .kind(completion_kind)
171 fn add_type_alias_impl(
172 type_def_node: &SyntaxNode,
173 acc: &mut Completions,
174 ctx: &CompletionContext,
175 type_alias: hir::TypeAlias,
177 let alias_name = type_alias.name(ctx.db).to_string();
179 let snippet = format!("type {} = ", alias_name);
181 let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
183 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
184 .text_edit(TextEdit::replace(range, snippet))
185 .lookup_by(alias_name)
186 .kind(CompletionItemKind::TypeAlias)
187 .set_documentation(type_alias.docs(ctx.db))
192 const_def_node: &SyntaxNode,
193 acc: &mut Completions,
194 ctx: &CompletionContext,
197 let const_name = const_.name(ctx.db).map(|n| n.to_string());
199 if let Some(const_name) = const_name {
200 let snippet = make_const_compl_syntax(&const_.source(ctx.db).value);
202 let range = TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
204 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
205 .text_edit(TextEdit::replace(range, snippet))
206 .lookup_by(const_name)
207 .kind(CompletionItemKind::Const)
208 .set_documentation(const_.docs(ctx.db))
213 fn make_const_compl_syntax(const_: &ast::Const) -> String {
214 let const_ = edit::remove_attrs_and_docs(const_);
216 let const_start = const_.syntax().text_range().start();
217 let const_end = const_.syntax().text_range().end();
220 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
224 .children_with_tokens()
225 .find(|s| s.kind() == T![;] || s.kind() == T![=])
226 .map_or(const_end, |f| f.text_range().start());
228 let len = end - start;
229 let range = TextRange::new(0.into(), len);
231 let syntax = const_.syntax().text().slice(range).to_string();
233 format!("{} = ", syntax.trim_end())
238 use expect_test::{expect, Expect};
240 use crate::completion::{
241 test_utils::{check_edit, completion_list},
245 fn check(ra_fixture: &str, expect: Expect) {
246 let actual = completion_list(ra_fixture, CompletionKind::Magic);
247 expect.assert_eq(&actual)
251 fn name_ref_function_type_const() {
256 const TEST_CONST: u16;
266 ct const TEST_CONST: u16 = \n\
268 ta type TestType = \n\
274 fn no_completion_inside_fn() {
277 trait Test { fn test(); fn test2(); }
291 trait Test { fn test(); fn test2(); }
305 trait Test { fn test(); fn test2(); }
317 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
320 trait Test { fn test(); fn test2(); }
334 trait Test { fn test(_: i32); fn test2(); }
346 trait Test { fn test(_: fn()); fn test2(); }
358 fn no_completion_inside_const() {
361 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
373 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
385 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
389 const TEST: u32 = f<|>
397 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
411 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
425 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
439 fn no_completion_inside_type() {
442 trait Test { type Test; type Test2; fn test(); }
454 trait Test { type Test; type Test2; fn test(); }
466 fn name_ref_single_function() {
495 fn single_function() {
524 fn hide_implemented_fn() {
575 fn foo<T>() where T: Into<String>;
585 fn foo<T>() where T: Into<String>;
591 where T: Into<String> {
600 fn associated_type() {
625 fn associated_const() {
630 const SOME_CONST: u16;
639 const SOME_CONST: u16;
643 const SOME_CONST: u16 = \n\
652 const SOME_CONST: u16 = 92;
661 const SOME_CONST: u16 = 92;
665 const SOME_CONST: u16 = \n\
672 fn complete_without_name() {
673 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
675 "completion='{}', hint='{}', next_sibling='{}'",
676 completion, hint, next_sibling
711 completed, next_sibling
716 // Enumerate some possible next siblings.
717 for next_sibling in &[
719 "fn other_fn() {}", // `const <|> fn` -> `const fn`
720 "type OtherType = i32;",
721 "const OTHER_CONST: i32 = 0;",
722 "async fn other_fn() {}",
723 "unsafe fn other_fn() {}",
724 "default fn other_fn() {}",
725 "default type OtherType = i32;",
726 "default const OTHER_CONST: i32 = 0;",
728 test("bar", "fn <|>", "fn bar() {\n $0\n}", next_sibling);
729 test("Foo", "type <|>", "type Foo = ", next_sibling);
730 test("CONST", "const <|>", "const CONST: u16 = ", next_sibling);