]> git.lizzy.rs Git - rust.git/blobdiff - crates/ide_completion/src/completions/trait_impl.rs
internal: Expand the derive attribute into a pseudo expansion
[rust.git] / crates / ide_completion / src / completions / trait_impl.rs
index 031f42d4a4c88a6182772414a3236a43595337b5..0d59f77a55c975d4ac5b4534d91e201feae904c7 100644 (file)
@@ -1,7 +1,7 @@
 //! Completion for associated items in a trait implementation.
 //!
 //! This module adds the completion items related to implementing associated
-//! items within a `impl Trait for Struct` block. The current context node
+//! items within an `impl Trait for Struct` block. The current context node
 //! must be within either a `FN`, `TYPE_ALIAS`, or `CONST` node
 //! and an direct child of an `IMPL`.
 //!
 //! }
 //! ```
 
-use hir::{self, HasAttrs, HasSource};
-use ide_db::{traits::get_missing_assoc_items, SymbolKind};
+use hir::{self, HasAttrs};
+use ide_db::{path_transform::PathTransform, traits::get_missing_assoc_items, SymbolKind};
 use syntax::{
-    ast::{self, edit, Impl},
+    ast::{self, edit_in_place::AttrsOwnerEdit},
     display::function_declaration,
-    AstNode, SyntaxKind, SyntaxNode, TextRange, T,
+    AstNode, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, T,
 };
 use text_edit::TextEdit;
 
-use crate::{
-    CompletionContext,
-    CompletionItem,
-    CompletionItemKind,
-    CompletionKind,
-    Completions,
-    // display::function_declaration,
-};
+use crate::{CompletionContext, CompletionItem, CompletionItemKind, Completions};
 
-#[derive(Debug, PartialEq, Eq)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 enum ImplCompletionKind {
     All,
     Fn,
@@ -58,37 +51,38 @@ enum ImplCompletionKind {
 }
 
 pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
-    if let Some((kind, trigger, impl_def)) = completion_match(ctx) {
-        get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
-            hir::AssocItem::Function(fn_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
-            {
-                add_function_impl(&trigger, acc, ctx, fn_item)
-            }
-            hir::AssocItem::TypeAlias(type_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
-            {
-                add_type_alias_impl(&trigger, acc, ctx, type_item)
-            }
-            hir::AssocItem::Const(const_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
-            {
-                add_const_impl(&trigger, acc, ctx, const_item)
-            }
-            _ => {}
-        });
+    if let Some((kind, trigger, impl_def)) = completion_match(ctx.token.clone()) {
+        if let Some(hir_impl) = ctx.sema.to_def(&impl_def) {
+            get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| {
+                match (item, kind) {
+                    (
+                        hir::AssocItem::Function(fn_item),
+                        ImplCompletionKind::All | ImplCompletionKind::Fn,
+                    ) => add_function_impl(acc, ctx, &trigger, fn_item, hir_impl),
+                    (
+                        hir::AssocItem::TypeAlias(type_item),
+                        ImplCompletionKind::All | ImplCompletionKind::TypeAlias,
+                    ) => add_type_alias_impl(acc, ctx, &trigger, type_item),
+                    (
+                        hir::AssocItem::Const(const_item),
+                        ImplCompletionKind::All | ImplCompletionKind::Const,
+                    ) => add_const_impl(acc, ctx, &trigger, const_item, hir_impl),
+                    _ => {}
+                }
+            });
+        }
     }
 }
 
-fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
-    let mut token = ctx.token.clone();
-    // For keywork without name like `impl .. { fn $0 }`, the current position is inside
+fn completion_match(mut token: SyntaxToken) -> Option<(ImplCompletionKind, SyntaxNode, ast::Impl)> {
+    // For keyword without name like `impl .. { fn $0 }`, the current position is inside
     // the whitespace token, which is outside `FN` syntax node.
     // We need to follow the previous token in this case.
     if token.kind() == SyntaxKind::WHITESPACE {
         token = token.prev_token()?;
     }
 
+    let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
     let impl_item_offset = match token.kind() {
         // `impl .. { const $0 }`
         // ERROR      0
@@ -102,14 +96,14 @@ fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, Synt
         // FN/TYPE_ALIAS/CONST  1
         //  NAME                0
         //    IDENT             <- *
-        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
+        SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
         // `impl .. { foo$0 }`
         // MACRO_CALL       3
         //  PATH            2
         //    PATH_SEGMENT  1
         //      NAME_REF    0
         //        IDENT     <- *
-        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
+        SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
         _ => return None,
     };
 
@@ -132,12 +126,13 @@ fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, Synt
 }
 
 fn add_function_impl(
-    fn_def_node: &SyntaxNode,
     acc: &mut Completions,
     ctx: &CompletionContext,
+    fn_def_node: &SyntaxNode,
     func: hir::Function,
+    impl_def: hir::Impl,
 ) {
-    let fn_name = func.name(ctx.db).to_string();
+    let fn_name = func.name(ctx.db).to_smol_str();
 
     let label = if func.assoc_fn_params(ctx.db).is_empty() {
         format!("fn {}()", fn_name)
@@ -145,84 +140,115 @@ fn add_function_impl(
         format!("fn {}(..)", fn_name)
     };
 
-    let mut builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label);
-    builder.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
-
     let completion_kind = if func.self_param(ctx.db).is_some() {
         CompletionItemKind::Method
     } else {
         CompletionItemKind::SymbolKind(SymbolKind::Function)
     };
-    let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
-
-    if let Some(src) = func.source(ctx.db) {
-        let function_decl = function_declaration(&src.value);
-        match ctx.config.snippet_cap {
-            Some(cap) => {
-                let snippet = format!("{} {{\n    $0\n}}", function_decl);
-                builder.snippet_edit(cap, TextEdit::replace(range, snippet));
-            }
-            None => {
-                let header = format!("{} {{", function_decl);
-                builder.text_edit(TextEdit::replace(range, header));
-            }
-        };
-        builder.kind(completion_kind);
-        builder.add_to(acc);
+
+    let range = replacement_range(ctx, fn_def_node);
+    let mut item = CompletionItem::new(completion_kind, range, label);
+    item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
+
+    if let Some(source) = ctx.sema.source(func) {
+        let assoc_item = ast::AssocItem::Fn(source.value);
+        if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
+            let transformed_fn = match transformed_item {
+                ast::AssocItem::Fn(func) => func,
+                _ => unreachable!(),
+            };
+
+            let function_decl = function_declaration(&transformed_fn);
+            match ctx.config.snippet_cap {
+                Some(cap) => {
+                    let snippet = format!("{} {{\n    $0\n}}", function_decl);
+                    item.snippet_edit(cap, TextEdit::replace(range, snippet));
+                }
+                None => {
+                    let header = format!("{} {{", function_decl);
+                    item.text_edit(TextEdit::replace(range, header));
+                }
+            };
+            item.add_to(acc);
+        }
     }
 }
 
+/// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc.
+fn get_transformed_assoc_item(
+    ctx: &CompletionContext,
+    assoc_item: ast::AssocItem,
+    impl_def: hir::Impl,
+) -> Option<ast::AssocItem> {
+    let assoc_item = assoc_item.clone_for_update();
+    let trait_ = impl_def.trait_(ctx.db)?;
+    let source_scope = &ctx.sema.scope_for_def(trait_);
+    let target_scope = &ctx.sema.scope(ctx.sema.source(impl_def)?.syntax().value);
+    let transform = PathTransform::trait_impl(
+        target_scope,
+        source_scope,
+        trait_,
+        ctx.sema.source(impl_def)?.value,
+    );
+
+    transform.apply(assoc_item.syntax());
+    if let ast::AssocItem::Fn(func) = &assoc_item {
+        func.remove_attrs_and_docs();
+    }
+    Some(assoc_item)
+}
+
 fn add_type_alias_impl(
-    type_def_node: &SyntaxNode,
     acc: &mut Completions,
     ctx: &CompletionContext,
+    type_def_node: &SyntaxNode,
     type_alias: hir::TypeAlias,
 ) {
-    let alias_name = type_alias.name(ctx.db).to_string();
+    let alias_name = type_alias.name(ctx.db).to_smol_str();
 
     let snippet = format!("type {} = ", alias_name);
 
-    let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
-
-    let mut builder =
-        CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
-    builder
-        .text_edit(TextEdit::replace(range, snippet))
+    let range = replacement_range(ctx, type_def_node);
+    let mut item = CompletionItem::new(SymbolKind::TypeAlias, range, &snippet);
+    item.text_edit(TextEdit::replace(range, snippet))
         .lookup_by(alias_name)
-        .kind(SymbolKind::TypeAlias)
         .set_documentation(type_alias.docs(ctx.db));
-    builder.add_to(acc);
+    item.add_to(acc);
 }
 
 fn add_const_impl(
-    const_def_node: &SyntaxNode,
     acc: &mut Completions,
     ctx: &CompletionContext,
+    const_def_node: &SyntaxNode,
     const_: hir::Const,
+    impl_def: hir::Impl,
 ) {
-    let const_name = const_.name(ctx.db).map(|n| n.to_string());
+    let const_name = const_.name(ctx.db).map(|n| n.to_smol_str());
 
     if let Some(const_name) = const_name {
-        if let Some(source) = const_.source(ctx.db) {
-            let snippet = make_const_compl_syntax(&source.value);
-
-            let range =
-                TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
-
-            let mut builder =
-                CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone());
-            builder
-                .text_edit(TextEdit::replace(range, snippet))
-                .lookup_by(const_name)
-                .kind(SymbolKind::Const)
-                .set_documentation(const_.docs(ctx.db));
-            builder.add_to(acc);
+        if let Some(source) = ctx.sema.source(const_) {
+            let assoc_item = ast::AssocItem::Const(source.value);
+            if let Some(transformed_item) = get_transformed_assoc_item(ctx, assoc_item, impl_def) {
+                let transformed_const = match transformed_item {
+                    ast::AssocItem::Const(const_) => const_,
+                    _ => unreachable!(),
+                };
+
+                let snippet = make_const_compl_syntax(&transformed_const);
+
+                let range = replacement_range(ctx, const_def_node);
+                let mut item = CompletionItem::new(SymbolKind::Const, range, &snippet);
+                item.text_edit(TextEdit::replace(range, snippet))
+                    .lookup_by(const_name)
+                    .set_documentation(const_.docs(ctx.db));
+                item.add_to(acc);
+            }
         }
     }
 }
 
 fn make_const_compl_syntax(const_: &ast::Const) -> String {
-    let const_ = edit::remove_attrs_and_docs(const_);
+    const_.remove_attrs_and_docs();
 
     let const_start = const_.syntax().text_range().start();
     let const_end = const_.syntax().text_range().end();
@@ -244,43 +270,28 @@ fn make_const_compl_syntax(const_: &ast::Const) -> String {
     format!("{} = ", syntax.trim_end())
 }
 
+fn replacement_range(ctx: &CompletionContext, item: &SyntaxNode) -> TextRange {
+    let first_child = item
+        .children_with_tokens()
+        .find(|child| {
+            !matches!(child.kind(), SyntaxKind::COMMENT | SyntaxKind::WHITESPACE | SyntaxKind::ATTR)
+        })
+        .unwrap_or_else(|| SyntaxElement::Node(item.clone()));
+
+    TextRange::new(first_child.text_range().start(), ctx.source_range().end())
+}
+
 #[cfg(test)]
 mod tests {
     use expect_test::{expect, Expect};
 
-    use crate::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
+    use crate::tests::{check_edit, completion_list_no_kw};
 
     fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Magic);
+        let actual = completion_list_no_kw(ra_fixture);
         expect.assert_eq(&actual)
     }
 
-    #[test]
-    fn name_ref_function_type_const() {
-        check(
-            r#"
-trait Test {
-    type TestType;
-    const TEST_CONST: u16;
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    t$0
-}
-"#,
-            expect![["
-ta type TestType = \n\
-ct const TEST_CONST: u16 = \n\
-fn fn test()
-"]],
-        );
-    }
-
     #[test]
     fn no_completion_inside_fn() {
         check(
@@ -294,7 +305,12 @@ fn test() {
     }
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
 
         check(
@@ -337,7 +353,7 @@ fn test() {
     }
 }
 ",
-            expect![[""]],
+            expect![[r#""#]],
         );
 
         check(
@@ -349,7 +365,10 @@ impl Test for T {
     fn test(t$0)
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                st T
+            "#]],
         );
 
         check(
@@ -361,7 +380,10 @@ impl Test for T {
     fn test(f: fn $0)
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                st T
+            "#]],
         );
     }
 
@@ -376,7 +398,7 @@ impl Test for T {
     const TEST: fn $0
 }
 ",
-            expect![[""]],
+            expect![[r#""#]],
         );
 
         check(
@@ -388,7 +410,12 @@ impl Test for T {
     const TEST: T$0
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
 
         check(
@@ -400,7 +427,12 @@ impl Test for T {
     const TEST: u32 = f$0
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
 
         check(
@@ -414,7 +446,12 @@ impl Test for T {
     };
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
 
         check(
@@ -457,7 +494,12 @@ impl Test for T {
     type Test = T$0;
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
 
         check(
@@ -469,7 +511,12 @@ impl Test for T {
     type Test = fn $0;
 }
 ",
-            expect![[""]],
+            expect![[r#"
+                sp Self
+                tt Test
+                st T
+                bt u32
+            "#]],
         );
     }
 
@@ -531,27 +578,6 @@ fn test() {
         );
     }
 
-    #[test]
-    fn hide_implemented_fn() {
-        check(
-            r#"
-trait Test {
-    fn foo();
-    fn foo_bar();
-}
-struct T;
-
-impl Test for T {
-    fn foo() {}
-    fn f$0
-}
-"#,
-            expect![[r#"
-                fn fn foo_bar()
-            "#]],
-        );
-    }
-
     #[test]
     fn generic_fn() {
         check_edit(
@@ -736,4 +762,229 @@ impl Test for T {{
             test("CONST", "const $0", "const CONST: u16 = ", next_sibling);
         }
     }
+
+    #[test]
+    fn snippet_does_not_overwrite_comment_or_attr() {
+        let test = |completion: &str, hint: &str, completed: &str| {
+            check_edit(
+                completion,
+                &format!(
+                    r#"
+trait Foo {{
+    type Type;
+    fn function();
+    const CONST: i32 = 0;
+}}
+struct T;
+
+impl Foo for T {{
+    // Comment
+    #[bar]
+    {}
+}}
+"#,
+                    hint
+                ),
+                &format!(
+                    r#"
+trait Foo {{
+    type Type;
+    fn function();
+    const CONST: i32 = 0;
+}}
+struct T;
+
+impl Foo for T {{
+    // Comment
+    #[bar]
+    {}
+}}
+"#,
+                    completed
+                ),
+            )
+        };
+        test("function", "fn f$0", "fn function() {\n    $0\n}");
+        test("Type", "type T$0", "type Type = ");
+        test("CONST", "const C$0", "const CONST: i32 = ");
+    }
+
+    #[test]
+    fn generics_are_inlined_in_return_type() {
+        check_edit(
+            "function",
+            r#"
+trait Foo<T> {
+    fn function() -> T;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn f$0
+}
+"#,
+            r#"
+trait Foo<T> {
+    fn function() -> T;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn function() -> u32 {
+    $0
+}
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn generics_are_inlined_in_parameter() {
+        check_edit(
+            "function",
+            r#"
+trait Foo<T> {
+    fn function(bar: T);
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn f$0
+}
+"#,
+            r#"
+trait Foo<T> {
+    fn function(bar: T);
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn function(bar: u32) {
+    $0
+}
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn generics_are_inlined_when_part_of_other_types() {
+        check_edit(
+            "function",
+            r#"
+trait Foo<T> {
+    fn function(bar: Vec<T>);
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn f$0
+}
+"#,
+            r#"
+trait Foo<T> {
+    fn function(bar: Vec<T>);
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn function(bar: Vec<u32>) {
+    $0
+}
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn generics_are_inlined_complex() {
+        check_edit(
+            "function",
+            r#"
+trait Foo<T, U, V> {
+    fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
+}
+struct Bar;
+
+impl Foo<u32, Vec<usize>, u8> for Bar {
+    fn f$0
+}
+"#,
+            r#"
+trait Foo<T, U, V> {
+    fn function(bar: Vec<T>, baz: U) -> Arc<Vec<V>>;
+}
+struct Bar;
+
+impl Foo<u32, Vec<usize>, u8> for Bar {
+    fn function(bar: Vec<u32>, baz: Vec<usize>) -> Arc<Vec<u8>> {
+    $0
+}
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn generics_are_inlined_in_associated_const() {
+        check_edit(
+            "BAR",
+            r#"
+trait Foo<T> {
+    const BAR: T;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    const B$0;
+}
+"#,
+            r#"
+trait Foo<T> {
+    const BAR: T;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    const BAR: u32 = ;
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn generics_are_inlined_in_where_clause() {
+        check_edit(
+            "function",
+            r#"
+trait SomeTrait<T> {}
+
+trait Foo<T> {
+    fn function()
+    where Self: SomeTrait<T>;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn f$0
+}
+"#,
+            r#"
+trait SomeTrait<T> {}
+
+trait Foo<T> {
+    fn function()
+    where Self: SomeTrait<T>;
+}
+struct Bar;
+
+impl Foo<u32> for Bar {
+    fn function()
+where Self: SomeTrait<u32> {
+    $0
+}
+}
+"#,
+        )
+    }
 }