aboutsummaryrefslogtreecommitdiff
path: root/crates/assists/src/handlers/add_lifetime_to_type.rs
blob: 2edf7b204b1714d9cb2f15cbc03209c1dda4594a (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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use ast::FieldList;
use syntax::ast::{self, AstNode, GenericParamsOwner, NameOwner, RefType, Type};

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

// Assist: add_lifetime_to_type
//
// Adds a new lifetime to a struct, enum or union.
//
// ```
// struct Point {
//     x: &$0u32,
//     y: u32,
// }
// ```
// ->
// ```
// struct Point<'a> {
//     x: &'a u32,
//     y: u32,
// }
// ```
pub(crate) fn add_lifetime_to_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let ref_type_focused = ctx.find_node_at_offset::<ast::RefType>()?;
    if ref_type_focused.lifetime().is_some() {
        return None;
    }

    let node = ctx.find_node_at_offset::<ast::Adt>()?;
    let has_lifetime = node
        .generic_param_list()
        .map(|gen_list| gen_list.lifetime_params().count() > 0)
        .unwrap_or_default();

    if has_lifetime {
        return None;
    }

    let ref_types = fetch_borrowed_types(&node)?;
    let target = node.syntax().text_range();

    acc.add(
        AssistId("add_lifetime_to_type", AssistKind::Generate),
        "Add lifetime`",
        target,
        |builder| {
            match node.generic_param_list() {
                Some(gen_param) => {
                    if let Some(left_angle) = gen_param.l_angle_token() {
                        builder.insert(left_angle.text_range().end(), "'a, ");
                    }
                }
                None => {
                    if let Some(name) = node.name() {
                        builder.insert(name.syntax().text_range().end(), "<'a>");
                    }
                }
            }

            for ref_type in ref_types {
                if let Some(amp_token) = ref_type.amp_token() {
                    builder.insert(amp_token.text_range().end(), "'a ");
                }
            }
        },
    )
}

fn fetch_borrowed_types(node: &ast::Adt) -> Option<Vec<RefType>> {
    let ref_types: Vec<RefType> = match node {
        ast::Adt::Enum(enum_) => {
            let variant_list = enum_.variant_list()?;
            variant_list
                .variants()
                .filter_map(|variant| {
                    let field_list = variant.field_list()?;

                    find_ref_types_from_field_list(&field_list)
                })
                .flatten()
                .collect()
        }
        ast::Adt::Struct(strukt) => {
            let field_list = strukt.field_list()?;
            find_ref_types_from_field_list(&field_list)?
        }
        ast::Adt::Union(un) => {
            let record_field_list = un.record_field_list()?;
            record_field_list
                .fields()
                .filter_map(|r_field| {
                    if let Type::RefType(ref_type) = r_field.ty()? {
                        if ref_type.lifetime().is_none() {
                            return Some(ref_type);
                        }
                    }

                    None
                })
                .collect()
        }
    };

    if ref_types.is_empty() {
        None
    } else {
        Some(ref_types)
    }
}

fn find_ref_types_from_field_list(field_list: &FieldList) -> Option<Vec<RefType>> {
    let ref_types: Vec<RefType> = match field_list {
        ast::FieldList::RecordFieldList(record_list) => record_list
            .fields()
            .filter_map(|f| {
                if let Type::RefType(ref_type) = f.ty()? {
                    if ref_type.lifetime().is_none() {
                        return Some(ref_type);
                    }
                }

                None
            })
            .collect(),
        ast::FieldList::TupleFieldList(tuple_field_list) => tuple_field_list
            .fields()
            .filter_map(|f| {
                if let Type::RefType(ref_type) = f.ty()? {
                    if ref_type.lifetime().is_none() {
                        return Some(ref_type);
                    }
                }

                None
            })
            .collect(),
    };

    if ref_types.is_empty() {
        None
    } else {
        Some(ref_types)
    }
}

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

    use super::*;

    #[test]
    fn add_lifetime_to_struct() {
        check_assist(
            add_lifetime_to_type,
            "struct Foo { a: &$0i32 }",
            "struct Foo<'a> { a: &'a i32 }",
        );

        check_assist(
            add_lifetime_to_type,
            "struct Foo { a: &$0i32, b: &usize }",
            "struct Foo<'a> { a: &'a i32, b: &'a usize }",
        );

        check_assist(
            add_lifetime_to_type,
            "struct Foo { a: &$0i32, b: usize }",
            "struct Foo<'a> { a: &'a i32, b: usize }",
        );

        check_assist(
            add_lifetime_to_type,
            "struct Foo<T> { a: &$0T, b: usize }",
            "struct Foo<'a, T> { a: &'a T, b: usize }",
        );

        check_assist_not_applicable(add_lifetime_to_type, "struct Foo<'a> { a: &$0'a i32 }");
        check_assist_not_applicable(add_lifetime_to_type, "struct Foo { a: &'a$0 i32 }");
    }

    #[test]
    fn add_lifetime_to_enum() {
        check_assist(
            add_lifetime_to_type,
            "enum Foo { Bar { a: i32 }, Other, Tuple(u32, &$0u32)}",
            "enum Foo<'a> { Bar { a: i32 }, Other, Tuple(u32, &'a u32)}",
        );

        check_assist(
            add_lifetime_to_type,
            "enum Foo { Bar { a: &$0i32 }}",
            "enum Foo<'a> { Bar { a: &'a i32 }}",
        );

        check_assist(
            add_lifetime_to_type,
            "enum Foo<T> { Bar { a: &$0i32, b: &T }}",
            "enum Foo<'a, T> { Bar { a: &'a i32, b: &'a T }}",
        );

        check_assist_not_applicable(add_lifetime_to_type, "enum Foo<'a> { Bar { a: &$0'a i32 }}");
        check_assist_not_applicable(add_lifetime_to_type, "enum Foo { Bar, $0Misc }");
    }

    #[test]
    fn add_lifetime_to_union() {
        check_assist(
            add_lifetime_to_type,
            "union Foo { a: &$0i32 }",
            "union Foo<'a> { a: &'a i32 }",
        );

        check_assist(
            add_lifetime_to_type,
            "union Foo { a: &$0i32, b: &usize }",
            "union Foo<'a> { a: &'a i32, b: &'a usize }",
        );

        check_assist(
            add_lifetime_to_type,
            "union Foo<T> { a: &$0T, b: usize }",
            "union Foo<'a, T> { a: &'a T, b: usize }",
        );

        check_assist_not_applicable(add_lifetime_to_type, "struct Foo<'a> { a: &'a $0i32 }");
    }
}