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};
37 ast::{self, edit, Impl},
38 display::function_declaration,
39 AstNode, SyntaxElement, 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 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()?;
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 }`
98 // `impl .. { fn/type $0 }`
101 T![fn] | T![type] => 0,
102 // `impl .. { fn/type/const foo$0 }`
103 // FN/TYPE_ALIAS/CONST 1
106 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
107 // `impl .. { foo$0 }`
113 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
117 let impl_item = token.ancestors().nth(impl_item_offset)?;
118 // Must directly belong to an impl block.
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,
132 Some((kind, impl_item, impl_def))
135 fn add_function_impl(
136 fn_def_node: &SyntaxNode,
137 acc: &mut Completions,
138 ctx: &CompletionContext,
141 let fn_name = func.name(ctx.db).to_string();
143 let label = if func.assoc_fn_params(ctx.db).is_empty() {
144 format!("fn {}()", fn_name)
146 format!("fn {}(..)", fn_name)
149 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
150 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
152 let completion_kind = if func.self_param(ctx.db).is_some() {
153 CompletionItemKind::Method
155 CompletionItemKind::SymbolKind(SymbolKind::Function)
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 {
162 let snippet = format!("{} {{\n $0\n}}", function_decl);
163 item.snippet_edit(cap, TextEdit::replace(range, snippet));
166 let header = format!("{} {{", function_decl);
167 item.text_edit(TextEdit::replace(range, header));
170 item.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 = 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));
195 const_def_node: &SyntaxNode,
196 acc: &mut Completions,
197 ctx: &CompletionContext,
200 let const_name = const_.name(ctx.db).map(|n| n.to_string());
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);
206 let range = replacement_range(ctx, const_def_node);
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));
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())
241 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
242 let first_child = item
243 .children_with_tokens()
245 let kind = child.kind();
247 SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR => false,
251 .unwrap_or(SyntaxElement::Node(item.clone()));
253 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
258 use expect_test::{expect, Expect};
261 test_utils::{check_edit, completion_list},
265 fn check(ra_fixture: &str, expect: Expect) {
266 let actual = completion_list(ra_fixture, CompletionKind::Magic);
267 expect.assert_eq(&actual)
271 fn name_ref_function_type_const() {
276 const TEST_CONST: u16;
286 ta type TestType = \n\
287 ct const TEST_CONST: u16 = \n\
294 fn no_completion_inside_fn() {
297 trait Test { fn test(); fn test2(); }
311 trait Test { fn test(); fn test2(); }
325 trait Test { fn test(); fn test2(); }
337 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
340 trait Test { fn test(); fn test2(); }
354 trait Test { fn test(_: i32); fn test2(); }
366 trait Test { fn test(_: fn()); fn test2(); }
378 fn no_completion_inside_const() {
381 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
393 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
405 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
409 const TEST: u32 = f$0
417 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
431 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
445 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
459 fn no_completion_inside_type() {
462 trait Test { type Test; type Test2; fn test(); }
474 trait Test { type Test; type Test2; fn test(); }
486 fn name_ref_single_function() {
515 fn single_function() {
544 fn hide_implemented_fn() {
595 fn foo<T>() where T: Into<String>;
605 fn foo<T>() where T: Into<String>;
611 where T: Into<String> {
620 fn associated_type() {
645 fn associated_const() {
650 const SOME_CONST: u16;
659 const SOME_CONST: u16;
663 const SOME_CONST: u16 = \n\
672 const SOME_CONST: u16 = 92;
681 const SOME_CONST: u16 = 92;
685 const SOME_CONST: u16 = \n\
692 fn complete_without_name() {
693 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
726 completed, next_sibling
731 // Enumerate some possible next siblings.
732 for next_sibling in &[
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;",
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);
750 fn snippet_does_not_overwrite_comment_or_attr() {
751 let test = |completion: &str, hint: &str, completed: &str| {
759 const CONST: i32 = 0;
776 const CONST: i32 = 0;
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 = ");