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, HasSource};
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(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_smol_str();
138 let label = if func.assoc_fn_params(ctx.db).is_empty() {
139 format!("fn {}()", fn_name)
141 format!("fn {}(..)", fn_name)
144 let completion_kind = if func.self_param(ctx.db).is_some() {
145 CompletionItemKind::Method
147 CompletionItemKind::SymbolKind(SymbolKind::Function)
149 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), label);
150 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
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));
178 /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
179 fn get_transformed_assoc_item(
180 ctx: &CompletionContext,
181 assoc_item: ast::AssocItem,
183 ) -> Option<ast::AssocItem> {
184 let assoc_item = assoc_item.clone_for_update();
185 let trait_ = impl_def.trait_(ctx.db)?;
186 let source_scope = &ctx.sema.scope_for_def(trait_);
187 let target_scope = &ctx.sema.scope(ctx.sema.source(impl_def)?.syntax().value);
188 let transform = PathTransform::trait_impl(
192 impl_def.source(ctx.db)?.value,
195 transform.apply(assoc_item.syntax());
196 if let ast::AssocItem::Fn(func) = &assoc_item {
197 func.remove_attrs_and_docs()
202 fn add_type_alias_impl(
203 type_def_node: &SyntaxNode,
204 acc: &mut Completions,
205 ctx: &CompletionContext,
206 type_alias: hir::TypeAlias,
208 let alias_name = type_alias.name(ctx.db).to_smol_str();
210 let snippet = format!("type {} = ", alias_name);
212 let range = replacement_range(ctx, type_def_node);
213 let mut item = CompletionItem::new(SymbolKind::TypeAlias, ctx.source_range(), &snippet);
214 item.text_edit(TextEdit::replace(range, snippet))
215 .lookup_by(alias_name)
216 .set_documentation(type_alias.docs(ctx.db));
221 const_def_node: &SyntaxNode,
222 acc: &mut Completions,
223 ctx: &CompletionContext,
227 let const_name = const_.name(ctx.db).map(|n| n.to_smol_str());
229 if let Some(const_name) = const_name {
230 if let Some(source) = const_.source(ctx.db) {
231 let assoc_item = ast::AssocItem::Const(source.value);
232 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
233 let transformed_const = match transformed_item {
234 ast::AssocItem::Const(const_) => const_,
238 let snippet = make_const_compl_syntax(&transformed_const);
240 let range = replacement_range(ctx, const_def_node);
241 let mut item = CompletionItem::new(SymbolKind::Const, ctx.source_range(), &snippet);
242 item.text_edit(TextEdit::replace(range, snippet))
243 .lookup_by(const_name)
244 .set_documentation(const_.docs(ctx.db));
251 fn make_const_compl_syntax(const_: &ast::Const) -> String {
252 const_.remove_attrs_and_docs();
254 let const_start = const_.syntax().text_range().start();
255 let const_end = const_.syntax().text_range().end();
258 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
262 .children_with_tokens()
263 .find(|s| s.kind() == T![;] || s.kind() == T![=])
264 .map_or(const_end, |f| f.text_range().start());
266 let len = end - start;
267 let range = TextRange::new(0.into(), len);
269 let syntax = const_.syntax().text().slice(range).to_string();
271 format!("{} = ", syntax.trim_end())
274 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
275 let first_child = item
276 .children_with_tokens()
278 !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
280 .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
282 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
287 use expect_test::{expect, Expect};
289 use crate::tests::{check_edit, completion_list_no_kw};
291 fn check(ra_fixture: &str, expect: Expect) {
292 let actual = completion_list_no_kw(ra_fixture);
293 expect.assert_eq(&actual)
297 fn no_completion_inside_fn() {
300 trait Test { fn test(); fn test2(); }
319 trait Test { fn test(); fn test2(); }
333 trait Test { fn test(); fn test2(); }
345 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
348 trait Test { fn test(); fn test2(); }
362 trait Test { fn test(_: i32); fn test2(); }
377 trait Test { fn test(_: fn()); fn test2(); }
392 fn no_completion_inside_const() {
395 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
407 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
424 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
428 const TEST: u32 = f$0
441 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
460 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
474 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
488 fn no_completion_inside_type() {
491 trait Test { type Test; type Test2; fn test(); }
508 trait Test { type Test; type Test2; fn test(); }
525 fn name_ref_single_function() {
554 fn single_function() {
613 fn foo<T>() where T: Into<String>;
623 fn foo<T>() where T: Into<String>;
629 where T: Into<String> {
638 fn associated_type() {
663 fn associated_const() {
668 const SOME_CONST: u16;
677 const SOME_CONST: u16;
681 const SOME_CONST: u16 = \n\
690 const SOME_CONST: u16 = 92;
699 const SOME_CONST: u16 = 92;
703 const SOME_CONST: u16 = \n\
710 fn complete_without_name() {
711 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
744 completed, next_sibling
749 // Enumerate some possible next siblings.
750 for next_sibling in &[
752 "fn other_fn() {}", // `const $0 fn` -> `const fn`
753 "type OtherType = i32;",
754 "const OTHER_CONST: i32 = 0;",
755 "async fn other_fn() {}",
756 "unsafe fn other_fn() {}",
757 "default fn other_fn() {}",
758 "default type OtherType = i32;",
759 "default const OTHER_CONST: i32 = 0;",
761 test("bar", "fn $0", "fn bar() {\n $0\n}", next_sibling);
762 test("Foo", "type $0", "type Foo = ", next_sibling);
763 test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
768 fn snippet_does_not_overwrite_comment_or_attr() {
769 let test = |completion: &str, hint: &str, completed: &str| {
777 const CONST: i32 = 0;
794 const CONST: i32 = 0;
808 test("function", "fn f$0", "fn function() {\n $0\n}");
809 test("Type", "type T$0", "type Type = ");
810 test("CONST", "const C$0", "const CONST: i32 = ");
814 fn generics_are_inlined_in_return_type() {
823 impl Foo<u32> for Bar {
833 impl Foo<u32> for Bar {
834 fn function() -> u32 {
843 fn generics_are_inlined_in_parameter() {
852 impl Foo<u32> for Bar {
862 impl Foo<u32> for Bar {
863 fn function(bar: u32) {
872 fn generics_are_inlined_when_part_of_other_types() {
877 fn function(bar: Vec<T>);
881 impl Foo<u32> for Bar {
887 fn function(bar: Vec<T>);
891 impl Foo<u32> for Bar {
892 fn function(bar: Vec<u32>) {
901 fn generics_are_inlined_complex() {
906 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
910 impl Foo<u32, Vec<usize>, u8> for Bar {
916 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
920 impl Foo<u32, Vec<usize>, u8> for Bar {
921 fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
930 fn generics_are_inlined_in_associated_const() {
939 impl Foo<u32> for Bar {
949 impl Foo<u32> for Bar {
957 fn generics_are_inlined_in_where_clause() {
961 trait SomeTrait<T> {}
965 where Self: SomeTrait<T>;
969 impl Foo<u32> for Bar {
974 trait SomeTrait<T> {}
978 where Self: SomeTrait<T>;
982 impl Foo<u32> for Bar {
984 where Self: SomeTrait<u32> {