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::{path_transform::PathTransform, 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 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| match item {
57 hir::AssocItem::Function(fn_item)
58 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
60 add_function_impl(&trigger, acc, ctx, fn_item, hir_impl)
62 hir::AssocItem::TypeAlias(type_item)
63 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
65 add_type_alias_impl(&trigger, acc, ctx, type_item)
67 hir::AssocItem::Const(const_item)
68 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
70 add_const_impl(&trigger, acc, ctx, const_item, hir_impl)
78 fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
79 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
80 // the whitespace token, which is outside `FN` syntax node.
81 // We need to follow the previous token in this case.
82 if token.kind() == SyntaxKind::WHITESPACE {
83 token = token.prev_token()?;
86 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
87 let impl_item_offset = match token.kind() {
88 // `impl .. { const $0 }`
92 // `impl .. { fn/type $0 }`
95 T![fn] | T![type] => 0,
96 // `impl .. { fn/type/const foo$0 }`
97 // FN/TYPE_ALIAS/CONST 1
100 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
101 // `impl .. { foo$0 }`
107 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
111 let impl_item = token.ancestors().nth(impl_item_offset)?;
112 // Must directly belong to an impl block.
116 let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
117 let kind = match impl_item.kind() {
118 // `impl ... { const $0 fn/type/const }`
119 _ if token.kind() == T![const] => ImplCompletionKind::Const,
120 SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
121 SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
122 SyntaxKind::FN => ImplCompletionKind::Fn,
123 SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
126 Some((kind, impl_item, impl_def))
129 fn add_function_impl(
130 fn_def_node: &SyntaxNode,
131 acc: &mut Completions,
132 ctx: &CompletionContext,
136 let fn_name = func.name(ctx.db).to_string();
138 let label = if func.assoc_fn_params(ctx.db).is_empty() {
139 format!("fn {}()", fn_name)
141 format!("fn {}(..)", fn_name)
144 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
145 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
147 let completion_kind = if func.self_param(ctx.db).is_some() {
148 CompletionItemKind::Method
150 CompletionItemKind::SymbolKind(SymbolKind::Function)
152 let range = replacement_range(ctx, fn_def_node);
154 if let Some(source) = func.source(ctx.db) {
155 let assoc_item = ast::AssocItem::Fn(source.value);
156 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
157 let transformed_fn = match transformed_item {
158 ast::AssocItem::Fn(func) => func,
162 let function_decl = function_declaration(&transformed_fn);
163 match ctx.config.snippet_cap {
165 let snippet = format!("{} {{\n $0\n}}", function_decl);
166 item.snippet_edit(cap, TextEdit::replace(range, snippet));
169 let header = format!("{} {{", function_decl);
170 item.text_edit(TextEdit::replace(range, header));
173 item.kind(completion_kind);
179 /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
180 fn get_transformed_assoc_item(
181 ctx: &CompletionContext,
182 assoc_item: ast::AssocItem,
184 ) -> Option<ast::AssocItem> {
185 let assoc_item = assoc_item.clone_for_update();
186 let trait_ = impl_def.trait_(ctx.db)?;
187 let source_scope = &ctx.sema.scope_for_def(trait_);
188 let target_scope = &ctx.sema.scope(impl_def.source(ctx.db)?.syntax().value);
189 let transform = PathTransform::trait_impl(
193 impl_def.source(ctx.db)?.value,
196 transform.apply(assoc_item.syntax());
197 if let ast::AssocItem::Fn(func) = &assoc_item {
198 edit::remove_attrs_and_docs(func)
203 fn add_type_alias_impl(
204 type_def_node: &SyntaxNode,
205 acc: &mut Completions,
206 ctx: &CompletionContext,
207 type_alias: hir::TypeAlias,
209 let alias_name = type_alias.name(ctx.db).to_string();
211 let snippet = format!("type {} = ", alias_name);
213 let range = replacement_range(ctx, type_def_node);
214 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
215 item.text_edit(TextEdit::replace(range, snippet))
216 .lookup_by(alias_name)
217 .kind(SymbolKind::TypeAlias)
218 .set_documentation(type_alias.docs(ctx.db));
223 const_def_node: &SyntaxNode,
224 acc: &mut Completions,
225 ctx: &CompletionContext,
229 let const_name = const_.name(ctx.db).map(|n| n.to_string());
231 if let Some(const_name) = const_name {
232 if let Some(source) = const_.source(ctx.db) {
233 let assoc_item = ast::AssocItem::Const(source.value);
234 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
235 let transformed_const = match transformed_item {
236 ast::AssocItem::Const(const_) => const_,
240 let snippet = make_const_compl_syntax(&transformed_const);
242 let range = replacement_range(ctx, const_def_node);
244 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
245 item.text_edit(TextEdit::replace(range, snippet))
246 .lookup_by(const_name)
247 .kind(SymbolKind::Const)
248 .set_documentation(const_.docs(ctx.db));
255 fn make_const_compl_syntax(const_: &ast::Const) -> String {
256 edit::remove_attrs_and_docs(const_);
258 let const_start = const_.syntax().text_range().start();
259 let const_end = const_.syntax().text_range().end();
262 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
266 .children_with_tokens()
267 .find(|s| s.kind() == T![;] || s.kind() == T![=])
268 .map_or(const_end, |f| f.text_range().start());
270 let len = end - start;
271 let range = TextRange::new(0.into(), len);
273 let syntax = const_.syntax().text().slice(range).to_string();
275 format!("{} = ", syntax.trim_end())
278 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
279 let first_child = item
280 .children_with_tokens()
282 !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
284 .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
286 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
291 use expect_test::{expect, Expect};
294 tests::{check_edit, filtered_completion_list},
298 fn check(ra_fixture: &str, expect: Expect) {
299 let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
300 expect.assert_eq(&actual)
304 fn no_completion_inside_fn() {
307 trait Test { fn test(); fn test2(); }
321 trait Test { fn test(); fn test2(); }
335 trait Test { fn test(); fn test2(); }
347 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
350 trait Test { fn test(); fn test2(); }
364 trait Test { fn test(_: i32); fn test2(); }
376 trait Test { fn test(_: fn()); fn test2(); }
388 fn no_completion_inside_const() {
391 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
403 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
415 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
419 const TEST: u32 = f$0
427 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
441 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
455 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
469 fn no_completion_inside_type() {
472 trait Test { type Test; type Test2; fn test(); }
484 trait Test { type Test; type Test2; fn test(); }
496 fn name_ref_single_function() {
525 fn single_function() {
584 fn foo<T>() where T: Into<String>;
594 fn foo<T>() where T: Into<String>;
600 where T: Into<String> {
609 fn associated_type() {
634 fn associated_const() {
639 const SOME_CONST: u16;
648 const SOME_CONST: u16;
652 const SOME_CONST: u16 = \n\
661 const SOME_CONST: u16 = 92;
670 const SOME_CONST: u16 = 92;
674 const SOME_CONST: u16 = \n\
681 fn complete_without_name() {
682 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
715 completed, next_sibling
720 // Enumerate some possible next siblings.
721 for next_sibling in &[
723 "fn other_fn() {}", // `const $0 fn` -> `const fn`
724 "type OtherType = i32;",
725 "const OTHER_CONST: i32 = 0;",
726 "async fn other_fn() {}",
727 "unsafe fn other_fn() {}",
728 "default fn other_fn() {}",
729 "default type OtherType = i32;",
730 "default const OTHER_CONST: i32 = 0;",
732 test("bar", "fn $0", "fn bar() {\n $0\n}", next_sibling);
733 test("Foo", "type $0", "type Foo = ", next_sibling);
734 test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
739 fn snippet_does_not_overwrite_comment_or_attr() {
740 let test = |completion: &str, hint: &str, completed: &str| {
748 const CONST: i32 = 0;
765 const CONST: i32 = 0;
779 test("function", "fn f$0", "fn function() {\n $0\n}");
780 test("Type", "type T$0", "type Type = ");
781 test("CONST", "const C$0", "const CONST: i32 = ");
785 fn generics_are_inlined_in_return_type() {
794 impl Foo<u32> for Bar {
804 impl Foo<u32> for Bar {
805 fn function() -> u32 {
814 fn generics_are_inlined_in_parameter() {
823 impl Foo<u32> for Bar {
833 impl Foo<u32> for Bar {
834 fn function(bar: u32) {
843 fn generics_are_inlined_when_part_of_other_types() {
848 fn function(bar: Vec<T>);
852 impl Foo<u32> for Bar {
858 fn function(bar: Vec<T>);
862 impl Foo<u32> for Bar {
863 fn function(bar: Vec<u32>) {
872 fn generics_are_inlined_complex() {
877 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
881 impl Foo<u32, Vec<usize>, u8> for Bar {
887 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
891 impl Foo<u32, Vec<usize>, u8> for Bar {
892 fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
901 fn generics_are_inlined_in_associated_const() {
910 impl Foo<u32> for Bar {
920 impl Foo<u32> for Bar {
928 fn generics_are_inlined_in_where_clause() {
932 trait SomeTrait<T> {}
936 where Self: SomeTrait<T>;
940 impl Foo<u32> for Bar {
945 trait SomeTrait<T> {}
949 where Self: SomeTrait<T>;
953 impl Foo<u32> for Bar {
955 where Self: SomeTrait<u32> {