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 get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
56 hir::AssocItem::Function(fn_item)
57 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
59 if let Some(impl_def) = ctx.sema.to_def(&impl_def) {
60 add_function_impl(&trigger, acc, ctx, fn_item, impl_def)
63 hir::AssocItem::TypeAlias(type_item)
64 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
66 add_type_alias_impl(&trigger, acc, ctx, type_item)
68 hir::AssocItem::Const(const_item)
69 if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
71 if let Some(impl_def) = ctx.sema.to_def(&impl_def) {
72 add_const_impl(&trigger, acc, ctx, const_item, impl_def)
80 fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
81 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
82 // the whitespace token, which is outside `FN` syntax node.
83 // We need to follow the previous token in this case.
84 if token.kind() == SyntaxKind::WHITESPACE {
85 token = token.prev_token()?;
88 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
89 let impl_item_offset = match token.kind() {
90 // `impl .. { const $0 }`
94 // `impl .. { fn/type $0 }`
97 T![fn] | T![type] => 0,
98 // `impl .. { fn/type/const foo$0 }`
99 // FN/TYPE_ALIAS/CONST 1
102 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
103 // `impl .. { foo$0 }`
109 SyntaxKind::IDENT if 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 $0 fn/type/const }`
121 _ if token.kind() == T![const] => 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,
138 let fn_name = func.name(ctx.db).to_string();
140 let label = if func.assoc_fn_params(ctx.db).is_empty() {
141 format!("fn {}()", fn_name)
143 format!("fn {}(..)", fn_name)
146 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
147 item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
149 let completion_kind = if func.self_param(ctx.db).is_some() {
150 CompletionItemKind::Method
152 CompletionItemKind::SymbolKind(SymbolKind::Function)
154 let range = replacement_range(ctx, fn_def_node);
156 if let Some(source) = func.source(ctx.db) {
157 let assoc_item = ast::AssocItem::Fn(source.value);
158 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
159 let transformed_fn = match transformed_item {
160 ast::AssocItem::Fn(func) => func,
164 let function_decl = function_declaration(&transformed_fn);
165 match ctx.config.snippet_cap {
167 let snippet = format!("{} {{\n $0\n}}", function_decl);
168 item.snippet_edit(cap, TextEdit::replace(range, snippet));
171 let header = format!("{} {{", function_decl);
172 item.text_edit(TextEdit::replace(range, header));
175 item.kind(completion_kind);
181 /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
182 fn get_transformed_assoc_item(
183 ctx: &CompletionContext,
184 assoc_item: ast::AssocItem,
186 ) -> Option<ast::AssocItem> {
187 let assoc_item = assoc_item.clone_for_update();
188 let trait_ = impl_def.trait_(ctx.db)?;
189 let source_scope = &ctx.sema.scope_for_def(trait_);
190 let target_scope = &ctx.sema.scope(impl_def.source(ctx.db)?.syntax().value);
191 let transform = PathTransform {
192 subst: (trait_, impl_def.source(ctx.db)?.value),
197 transform.apply(assoc_item.clone());
198 Some(match assoc_item {
199 ast::AssocItem::Fn(func) => ast::AssocItem::Fn(edit::remove_attrs_and_docs(&func)),
204 fn add_type_alias_impl(
205 type_def_node: &SyntaxNode,
206 acc: &mut Completions,
207 ctx: &CompletionContext,
208 type_alias: hir::TypeAlias,
210 let alias_name = type_alias.name(ctx.db).to_string();
212 let snippet = format!("type {} = ", alias_name);
214 let range = replacement_range(ctx, type_def_node);
215 let mut item = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
216 item.text_edit(TextEdit::replace(range, snippet))
217 .lookup_by(alias_name)
218 .kind(SymbolKind::TypeAlias)
219 .set_documentation(type_alias.docs(ctx.db));
224 const_def_node: &SyntaxNode,
225 acc: &mut Completions,
226 ctx: &CompletionContext,
230 let const_name = const_.name(ctx.db).map(|n| n.to_string());
232 if let Some(const_name) = const_name {
233 if let Some(source) = const_.source(ctx.db) {
234 let assoc_item = ast::AssocItem::Const(source.value);
235 if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
236 let transformed_const = match transformed_item {
237 ast::AssocItem::Const(const_) => const_,
241 let snippet = make_const_compl_syntax(&transformed_const);
243 let range = replacement_range(ctx, const_def_node);
245 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
246 item.text_edit(TextEdit::replace(range, snippet))
247 .lookup_by(const_name)
248 .kind(SymbolKind::Const)
249 .set_documentation(const_.docs(ctx.db));
256 fn make_const_compl_syntax(const_: &ast::Const) -> String {
257 let const_ = edit::remove_attrs_and_docs(const_);
259 let const_start = const_.syntax().text_range().start();
260 let const_end = const_.syntax().text_range().end();
263 const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
267 .children_with_tokens()
268 .find(|s| s.kind() == T![;] || s.kind() == T![=])
269 .map_or(const_end, |f| f.text_range().start());
271 let len = end - start;
272 let range = TextRange::new(0.into(), len);
274 let syntax = const_.syntax().text().slice(range).to_string();
276 format!("{} = ", syntax.trim_end())
279 fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
280 let first_child = item
281 .children_with_tokens()
283 !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
285 .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
287 TextRange::new(first_child.text_range().start(), ctx.source_range().end())
292 use expect_test::{expect, Expect};
295 tests::{check_edit, filtered_completion_list},
299 fn check(ra_fixture: &str, expect: Expect) {
300 let actual = filtered_completion_list(ra_fixture, CompletionKind::Magic);
301 expect.assert_eq(&actual)
305 fn name_ref_function_type_const() {
310 const TEST_CONST: u16;
320 ta type TestType = \n\
321 ct const TEST_CONST: u16 = \n\
328 fn no_completion_inside_fn() {
331 trait Test { fn test(); fn test2(); }
345 trait Test { fn test(); fn test2(); }
359 trait Test { fn test(); fn test2(); }
371 // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
374 trait Test { fn test(); fn test2(); }
388 trait Test { fn test(_: i32); fn test2(); }
400 trait Test { fn test(_: fn()); fn test2(); }
412 fn no_completion_inside_const() {
415 trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
427 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
439 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
443 const TEST: u32 = f$0
451 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
465 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
479 trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
493 fn no_completion_inside_type() {
496 trait Test { type Test; type Test2; fn test(); }
508 trait Test { type Test; type Test2; fn test(); }
520 fn name_ref_single_function() {
549 fn single_function() {
578 fn hide_implemented_fn() {
629 fn foo<T>() where T: Into<String>;
639 fn foo<T>() where T: Into<String>;
645 where T: Into<String> {
654 fn associated_type() {
679 fn associated_const() {
684 const SOME_CONST: u16;
693 const SOME_CONST: u16;
697 const SOME_CONST: u16 = \n\
706 const SOME_CONST: u16 = 92;
715 const SOME_CONST: u16 = 92;
719 const SOME_CONST: u16 = \n\
726 fn complete_without_name() {
727 let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
760 completed, next_sibling
765 // Enumerate some possible next siblings.
766 for next_sibling in &[
768 "fn other_fn() {}", // `const $0 fn` -> `const fn`
769 "type OtherType = i32;",
770 "const OTHER_CONST: i32 = 0;",
771 "async fn other_fn() {}",
772 "unsafe fn other_fn() {}",
773 "default fn other_fn() {}",
774 "default type OtherType = i32;",
775 "default const OTHER_CONST: i32 = 0;",
777 test("bar", "fn $0", "fn bar() {\n $0\n}", next_sibling);
778 test("Foo", "type $0", "type Foo = ", next_sibling);
779 test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
784 fn snippet_does_not_overwrite_comment_or_attr() {
785 let test = |completion: &str, hint: &str, completed: &str| {
793 const CONST: i32 = 0;
810 const CONST: i32 = 0;
824 test("function", "fn f$0", "fn function() {\n $0\n}");
825 test("Type", "type T$0", "type Type = ");
826 test("CONST", "const C$0", "const CONST: i32 = ");
830 fn generics_are_inlined_in_return_type() {
839 impl Foo<u32> for Bar {
849 impl Foo<u32> for Bar {
850 fn function() -> u32 {
859 fn generics_are_inlined_in_parameter() {
868 impl Foo<u32> for Bar {
878 impl Foo<u32> for Bar {
879 fn function(bar: u32) {
888 fn generics_are_inlined_when_part_of_other_types() {
893 fn function(bar: Vec<T>);
897 impl Foo<u32> for Bar {
903 fn function(bar: Vec<T>);
907 impl Foo<u32> for Bar {
908 fn function(bar: Vec<u32>) {
917 fn generics_are_inlined_complex() {
922 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
926 impl Foo<u32, Vec<usize>, u8> for Bar {
932 fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
936 impl Foo<u32, Vec<usize>, u8> for Bar {
937 fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
946 fn generics_are_inlined_in_associated_const() {
955 impl Foo<u32> for Bar {
965 impl Foo<u32> for Bar {
973 fn generics_are_inlined_in_where_clause() {
977 trait SomeTrait<T> {}
981 where Self: SomeTrait<T>;
985 impl Foo<u32> for Bar {
990 trait SomeTrait<T> {}
994 where Self: SomeTrait<T>;
998 impl Foo<u32> for Bar {
1000 where Self: SomeTrait<u32> {