1 //! Completion for associated items in a trait implementation.
3 //! This module adds the completion items related to implementing associated
4 //! items within an `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};
35 use ide_db::{path_transform::PathTransform, traits::get_missing_assoc_items, SymbolKind};
37 ast::{self, edit_in_place::AttrsOwnerEdit},
38 display::function_declaration,
39 AstNode, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, T,
41 use text_edit::TextEdit;
43 use crate::{CompletionContext, CompletionItem, CompletionItemKind, Completions};
45 #[derive(Copy, Clone, 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 if let Some(hir_impl) = ctx.sema.to_def(&impl_def) {
56 get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| {
59 hir::AssocItem::Function(fn_item),
60 ImplCompletionKind::All | ImplCompletionKind::Fn,
61 ) => add_function_impl(acc, ctx, &trigger, fn_item, hir_impl),
63 hir::AssocItem::TypeAlias(type_item),
64 ImplCompletionKind::All | ImplCompletionKind::TypeAlias,
65 ) => add_type_alias_impl(acc, ctx, &trigger, type_item),
67 hir::AssocItem::Const(const_item),
68 ImplCompletionKind::All | ImplCompletionKind::Const,
69 ) => add_const_impl(acc, ctx, &trigger, const_item, hir_impl),
77 fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
78 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
79 // the whitespace token, which is outside `FN` syntax node.
80 // We need to follow the previous token in this case.
81 if token.kind() == SyntaxKind::WHITESPACE {
82 token = token.prev_token()?;
85 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
86 let impl_item_offset = match token.kind() {
87 // `impl .. { const $0 }`
91 // `impl .. { fn/type $0 }`
94 T![fn] | T![type] => 0,
95 // `impl .. { fn/type/const foo$0 }`
96 // FN/TYPE_ALIAS/CONST 1
99 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
100 // `impl .. { foo$0 }`
106 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
110 let impl_item = token.ancestors().nth(impl_item_offset)?;
111 // Must directly belong to an impl block.
115 let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
116 let kind = match impl_item.kind() {
117 // `impl ... { const $0 fn/type/const }`
118 _ if token.kind() == T![const] => ImplCompletionKind::Const,
119 SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
120 SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
121 SyntaxKind::FN => ImplCompletionKind::Fn,
122 SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
125 Some((kind, impl_item, impl_def))
128 fn add_function_impl(
129 acc: &mut Completions,
130 ctx: &CompletionContext,
131 fn_def_node: &SyntaxNode,
135 let fn_name = func.name(ctx.db).to_smol_str();
137 let label = if func.assoc_fn_params(ctx.db).is_empty() {
138 format!("fn {}()", fn_name)
140 format!("fn {}(..)", fn_name)
143 let completion_kind = if func.self_param(ctx.db).is_some() {
144 CompletionItemKind::Method
146 CompletionItemKind::SymbolKind(SymbolKind::Function)
149 let range = replacement_range(ctx, fn_def_node);
150 let mut item = CompletionItem::new(completion_kind, range, label);
151 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
153 if let Some(source) = ctx.sema.source(func) {
154 let assoc_item = ast::AssocItem::Fn(source.value);
155 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
156 let transformed_fn = match transformed_item {
157 ast::AssocItem::Fn(func) => func,
161 let function_decl = function_declaration(&transformed_fn);
162 match ctx.config.snippet_cap {
164 let snippet = format!("{} {{\n $0\n}}", function_decl);
165 item.snippet_edit(cap, TextEdit::replace(range, snippet));
168 let header = format!("{} {{", function_decl);
169 item.text_edit(TextEdit::replace(range, header));
177 /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
178 fn get_transformed_assoc_item(
179 ctx: &CompletionContext,
180 assoc_item: ast::AssocItem,
182 ) -> Option<ast::AssocItem> {
183 let assoc_item = assoc_item.clone_for_update();
184 let trait_ = impl_def.trait_(ctx.db)?;
185 let source_scope = &ctx.sema.scope_for_def(trait_);
186 let target_scope = &ctx.sema.scope(ctx.sema.source(impl_def)?.syntax().value);
187 let transform = PathTransform::trait_impl(
191 ctx.sema.source(impl_def)?.value,
194 transform.apply(assoc_item.syntax());
195 if let ast::AssocItem::Fn(func) = &assoc_item {
196 func.remove_attrs_and_docs();
201 fn add_type_alias_impl(
202 acc: &mut Completions,
203 ctx: &CompletionContext,
204 type_def_node: &SyntaxNode,
205 type_alias: hir::TypeAlias,
207 let alias_name = type_alias.name(ctx.db).to_smol_str();
209 let snippet = format!("type {} = ", alias_name);
211 let range = replacement_range(ctx, type_def_node);
212 let mut item = CompletionItem::new(SymbolKind::TypeAlias, range, &snippet);
213 item.text_edit(TextEdit::replace(range, snippet))
214 .lookup_by(alias_name)
215 .set_documentation(type_alias.docs(ctx.db));
220 acc: &mut Completions,
221 ctx: &CompletionContext,
222 const_def_node: &SyntaxNode,
226 let const_name = const_.name(ctx.db).map(|n| n.to_smol_str());
228 if let Some(const_name) = const_name {
229 if let Some(source) = ctx.sema.source(const_) {
230 let assoc_item = ast::AssocItem::Const(source.value);
231 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
232 let transformed_const = match transformed_item {
233 ast::AssocItem::Const(const_) => const_,
237 let snippet = make_const_compl_syntax(&transformed_const);
239 let range = replacement_range(ctx, const_def_node);
240 let mut item = CompletionItem::new(SymbolKind::Const, range, &snippet);
241 item.text_edit(TextEdit::replace(range, snippet))
242 .lookup_by(const_name)
243 .set_documentation(const_.docs(ctx.db));
250 fn make_const_compl_syntax(const_: &ast::Const) -> String {
251 const_.remove_attrs_and_docs();
253 let const_start = const_.syntax().text_range().start();
254 let const_end = const_.syntax().text_range().end();
257 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
261 .children_with_tokens()
262 .find(|s| s.kind() == T![;] || s.kind() == T![=])
263 .map_or(const_end, |f| f.text_range().start());
265 let len = end - start;
266 let range = TextRange::new(0.into(), len);
268 let syntax = const_.syntax().text().slice(range).to_string();
270 format!("{} = ", syntax.trim_end())
273 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
274 let first_child = item
275 .children_with_tokens()
277 !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
279 .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
281 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
286 use expect_test::{expect, Expect};
288 use crate::tests::{check_edit, completion_list_no_kw};
290 fn check(ra_fixture: &str, expect: Expect) {
291 let actual = completion_list_no_kw(ra_fixture);
292 expect.assert_eq(&actual)
296 fn no_completion_inside_fn() {
299 trait Test { fn test(); fn test2(); }
318 trait Test { fn test(); fn test2(); }
332 trait Test { fn test(); fn test2(); }
344 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
347 trait Test { fn test(); fn test2(); }
361 trait Test { fn test(_: i32); fn test2(); }
376 trait Test { fn test(_: fn()); fn test2(); }
391 fn no_completion_inside_const() {
394 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
406 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
423 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
427 const TEST: u32 = f$0
440 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
459 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
473 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
487 fn no_completion_inside_type() {
490 trait Test { type Test; type Test2; fn test(); }
507 trait Test { type Test; type Test2; fn test(); }
524 fn name_ref_single_function() {
553 fn single_function() {
612 fn foo<T>() where T: Into<String>;
622 fn foo<T>() where T: Into<String>;
628 where T: Into<String> {
637 fn associated_type() {
662 fn associated_const() {
667 const SOME_CONST: u16;
676 const SOME_CONST: u16;
680 const SOME_CONST: u16 = \n\
689 const SOME_CONST: u16 = 92;
698 const SOME_CONST: u16 = 92;
702 const SOME_CONST: u16 = \n\
709 fn complete_without_name() {
710 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
743 completed, next_sibling
748 // Enumerate some possible next siblings.
749 for next_sibling in &[
751 "fn other_fn() {}", // `const $0 fn` -> `const fn`
752 "type OtherType = i32;",
753 "const OTHER_CONST: i32 = 0;",
754 "async fn other_fn() {}",
755 "unsafe fn other_fn() {}",
756 "default fn other_fn() {}",
757 "default type OtherType = i32;",
758 "default const OTHER_CONST: i32 = 0;",
760 test("bar", "fn $0", "fn bar() {\n $0\n}", next_sibling);
761 test("Foo", "type $0", "type Foo = ", next_sibling);
762 test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
767 fn snippet_does_not_overwrite_comment_or_attr() {
768 let test = |completion: &str, hint: &str, completed: &str| {
776 const CONST: i32 = 0;
793 const CONST: i32 = 0;
807 test("function", "fn f$0", "fn function() {\n $0\n}");
808 test("Type", "type T$0", "type Type = ");
809 test("CONST", "const C$0", "const CONST: i32 = ");
813 fn generics_are_inlined_in_return_type() {
822 impl Foo<u32> for Bar {
832 impl Foo<u32> for Bar {
833 fn function() -> u32 {
842 fn generics_are_inlined_in_parameter() {
851 impl Foo<u32> for Bar {
861 impl Foo<u32> for Bar {
862 fn function(bar: u32) {
871 fn generics_are_inlined_when_part_of_other_types() {
876 fn function(bar: Vec<T>);
880 impl Foo<u32> for Bar {
886 fn function(bar: Vec<T>);
890 impl Foo<u32> for Bar {
891 fn function(bar: Vec<u32>) {
900 fn generics_are_inlined_complex() {
905 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
909 impl Foo<u32, Vec<usize>, u8> for Bar {
915 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
919 impl Foo<u32, Vec<usize>, u8> for Bar {
920 fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
929 fn generics_are_inlined_in_associated_const() {
938 impl Foo<u32> for Bar {
948 impl Foo<u32> for Bar {
956 fn generics_are_inlined_in_where_clause() {
960 trait SomeTrait<T> {}
964 where Self: SomeTrait<T>;
968 impl Foo<u32> for Bar {
973 trait SomeTrait<T> {}
977 where Self: SomeTrait<T>;
981 impl Foo<u32> for Bar {
983 where Self: SomeTrait<u32> {