ide_assists/handlers/
convert_nested_function_to_closure.rs

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
use ide_db::assists::{AssistId, AssistKind};
use syntax::ast::{self, HasGenericParams, HasName};
use syntax::{AstNode, SyntaxKind};

use crate::assist_context::{AssistContext, Assists};

// Assist: convert_nested_function_to_closure
//
// Converts a function that is defined within the body of another function into a closure.
//
// ```
// fn main() {
//     fn fo$0o(label: &str, number: u64) {
//         println!("{}: {}", label, number);
//     }
//
//     foo("Bar", 100);
// }
// ```
// ->
// ```
// fn main() {
//     let foo = |label: &str, number: u64| {
//         println!("{}: {}", label, number);
//     };
//
//     foo("Bar", 100);
// }
// ```
pub(crate) fn convert_nested_function_to_closure(
    acc: &mut Assists,
    ctx: &AssistContext<'_>,
) -> Option<()> {
    let name = ctx.find_node_at_offset::<ast::Name>()?;
    let function = name.syntax().parent().and_then(ast::Fn::cast)?;

    if !is_nested_function(&function) || is_generic(&function) || has_modifiers(&function) {
        return None;
    }

    let target = function.syntax().text_range();
    let body = function.body()?;
    let name = function.name()?;
    let param_list = function.param_list()?;

    acc.add(
        AssistId("convert_nested_function_to_closure", AssistKind::RefactorRewrite),
        "Convert nested function to closure",
        target,
        |edit| {
            let params = &param_list.syntax().text().to_string();
            let params = params.strip_prefix('(').unwrap_or(params);
            let params = params.strip_suffix(')').unwrap_or(params);

            let mut body = body.to_string();
            if !has_semicolon(&function) {
                body.push(';');
            }
            edit.replace(target, format!("let {name} = |{params}| {body}"));
        },
    )
}

/// Returns whether the given function is nested within the body of another function.
fn is_nested_function(function: &ast::Fn) -> bool {
    function.syntax().ancestors().skip(1).find_map(ast::Item::cast).map_or(false, |it| {
        matches!(it, ast::Item::Fn(_) | ast::Item::Static(_) | ast::Item::Const(_))
    })
}

/// Returns whether the given nested function has generic parameters.
fn is_generic(function: &ast::Fn) -> bool {
    function.generic_param_list().is_some()
}

/// Returns whether the given nested function has any modifiers:
///
/// - `async`,
/// - `const` or
/// - `unsafe`
fn has_modifiers(function: &ast::Fn) -> bool {
    function.async_token().is_some()
        || function.const_token().is_some()
        || function.unsafe_token().is_some()
}

/// Returns whether the given nested function has a trailing semicolon.
fn has_semicolon(function: &ast::Fn) -> bool {
    function
        .syntax()
        .next_sibling_or_token()
        .map(|t| t.kind() == SyntaxKind::SEMICOLON)
        .unwrap_or(false)
}

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

    use super::convert_nested_function_to_closure;

    #[test]
    fn convert_nested_function_to_closure_works() {
        check_assist(
            convert_nested_function_to_closure,
            r#"
fn main() {
    fn $0foo(a: u64, b: u64) -> u64 {
        2 * (a + b)
    }

    _ = foo(3, 4);
}
            "#,
            r#"
fn main() {
    let foo = |a: u64, b: u64| {
        2 * (a + b)
    };

    _ = foo(3, 4);
}
            "#,
        );
    }

    #[test]
    fn convert_nested_function_to_closure_works_with_existing_semicolon() {
        check_assist(
            convert_nested_function_to_closure,
            r#"
fn main() {
    fn foo$0(a: u64, b: u64) -> u64 {
        2 * (a + b)
    };

    _ = foo(3, 4);
}
            "#,
            r#"
fn main() {
    let foo = |a: u64, b: u64| {
        2 * (a + b)
    };

    _ = foo(3, 4);
}
            "#,
        );
    }

    #[test]
    fn convert_nested_function_to_closure_is_not_suggested_on_top_level_function() {
        check_assist_not_applicable(
            convert_nested_function_to_closure,
            r#"
fn ma$0in() {}
            "#,
        );
    }

    #[test]
    fn convert_nested_function_to_closure_is_not_suggested_when_cursor_off_name() {
        check_assist_not_applicable(
            convert_nested_function_to_closure,
            r#"
fn main() {
    fn foo(a: u64, $0b: u64) -> u64 {
        2 * (a + b)
    }

    _ = foo(3, 4);
}
            "#,
        );
    }

    #[test]
    fn convert_nested_function_to_closure_is_not_suggested_if_function_has_generic_params() {
        check_assist_not_applicable(
            convert_nested_function_to_closure,
            r#"
fn main() {
    fn fo$0o<S: Into<String>>(s: S) -> String {
        s.into()
    }

    _ = foo("hello");
}
            "#,
        );
    }

    #[test]
    fn convert_nested_function_to_closure_is_not_suggested_if_function_has_modifier() {
        check_assist_not_applicable(
            convert_nested_function_to_closure,
            r#"
fn main() {
    const fn fo$0o(s: String) -> String {
        s
    }

    _ = foo("hello");
}
            "#,
        );
    }
}