aboutsummaryrefslogtreecommitdiff
path: root/crates/assists/src/handlers/generate_impl.rs
blob: 61d1bd25c1300cf7ead9b6fc921aaaed235a3897 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use itertools::Itertools;
use stdx::format_to;
use syntax::{
    ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner},
    SmolStr,
};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: generate_impl
//
// Adds a new inherent impl for a type.
//
// ```
// struct Ctx<T: Clone> {
//     data: T,$0
// }
// ```
// ->
// ```
// struct Ctx<T: Clone> {
//     data: T,
// }
//
// impl<T: Clone> Ctx<T> {
//     $0
// }
// ```
pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let nominal = ctx.find_node_at_offset::<ast::Adt>()?;
    let name = nominal.name()?;
    let target = nominal.syntax().text_range();

    acc.add(
        AssistId("generate_impl", AssistKind::Generate),
        format!("Generate impl for `{}`", name),
        target,
        |edit| {
            let type_params = nominal.generic_param_list();
            let start_offset = nominal.syntax().text_range().end();
            let mut buf = String::new();
            buf.push_str("\n\n");
            nominal
                .attrs()
                .filter(|attr| {
                    attr.as_simple_call().map(|(name, _arg)| name == "cfg").unwrap_or(false)
                })
                .for_each(|attr| buf.push_str(format!("{}\n", attr.to_string()).as_str()));

            buf.push_str("impl");
            if let Some(type_params) = &type_params {
                format_to!(buf, "{}", type_params.syntax());
            }
            buf.push_str(" ");
            buf.push_str(name.text());
            if let Some(type_params) = type_params {
                let lifetime_params = type_params
                    .lifetime_params()
                    .filter_map(|it| it.lifetime())
                    .map(|it| SmolStr::from(it.text()));
                let type_params = type_params
                    .type_params()
                    .filter_map(|it| it.name())
                    .map(|it| SmolStr::from(it.text()));

                let generic_params = lifetime_params.chain(type_params).format(", ");
                format_to!(buf, "<{}>", generic_params)
            }
            match ctx.config.snippet_cap {
                Some(cap) => {
                    buf.push_str(" {\n    $0\n}");
                    edit.insert_snippet(cap, start_offset, buf);
                }
                None => {
                    buf.push_str(" {\n}");
                    edit.insert(start_offset, buf);
                }
            }
        },
    )
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_target};

    use super::*;

    #[test]
    fn test_add_impl() {
        check_assist(
            generate_impl,
            "struct Foo {$0}\n",
            "struct Foo {}\n\nimpl Foo {\n    $0\n}\n",
        );
        check_assist(
            generate_impl,
            "struct Foo<T: Clone> {$0}",
            "struct Foo<T: Clone> {}\n\nimpl<T: Clone> Foo<T> {\n    $0\n}",
        );
        check_assist(
            generate_impl,
            "struct Foo<'a, T: Foo<'a>> {$0}",
            "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n    $0\n}",
        );
        check_assist(
            generate_impl,
            r#"
            #[cfg(feature = "foo")]
            struct Foo<'a, T: Foo<'a>> {$0}"#,
            r#"
            #[cfg(feature = "foo")]
            struct Foo<'a, T: Foo<'a>> {}

            #[cfg(feature = "foo")]
            impl<'a, T: Foo<'a>> Foo<'a, T> {
                $0
            }"#,
        );

        check_assist(
            generate_impl,
            r#"
            #[cfg(not(feature = "foo"))]
            struct Foo<'a, T: Foo<'a>> {$0}"#,
            r#"
            #[cfg(not(feature = "foo"))]
            struct Foo<'a, T: Foo<'a>> {}

            #[cfg(not(feature = "foo"))]
            impl<'a, T: Foo<'a>> Foo<'a, T> {
                $0
            }"#,
        );
    }

    #[test]
    fn add_impl_target() {
        check_assist_target(
            generate_impl,
            "
struct SomeThingIrrelevant;
/// Has a lifetime parameter
struct Foo<'a, T: Foo<'a>> {$0}
struct EvenMoreIrrelevant;
",
            "/// Has a lifetime parameter
struct Foo<'a, T: Foo<'a>> {}",
        );
    }
}