aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_assists/src/handlers/replace_unwrap_with_match.rs
blob: f39c48d8f7b1abb7b26b6af7eba6637b8d6c5e87 (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
use std::iter;

use syntax::{
    ast::{
        self,
        edit::{AstNodeEdit, IndentLevel},
        make,
    },
    AstNode,
};

use crate::{
    utils::{render_snippet, Cursor},
    AssistContext, AssistId, AssistKind, Assists,
};
use ide_db::ty_filter::TryEnum;

// Assist: replace_unwrap_with_match
//
// Replaces `unwrap` with a `match` expression. Works for Result and Option.
//
// ```
// # //- minicore: result
// fn main() {
//     let x: Result<i32, i32> = Ok(92);
//     let y = x.$0unwrap();
// }
// ```
// ->
// ```
// fn main() {
//     let x: Result<i32, i32> = Ok(92);
//     let y = match x {
//         Ok(it) => it,
//         $0_ => unreachable!(),
//     };
// }
// ```
pub(crate) fn replace_unwrap_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let method_call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
    let name = method_call.name_ref()?;
    if name.text() != "unwrap" {
        return None;
    }
    let caller = method_call.receiver()?;
    let ty = ctx.sema.type_of_expr(&caller)?;
    let happy_variant = TryEnum::from_ty(&ctx.sema, &ty)?.happy_case();
    let target = method_call.syntax().text_range();
    acc.add(
        AssistId("replace_unwrap_with_match", AssistKind::RefactorRewrite),
        "Replace unwrap with match",
        target,
        |builder| {
            let ok_path = make::ext::ident_path(happy_variant);
            let it = make::ident_pat(make::name("it")).into();
            let ok_tuple = make::tuple_struct_pat(ok_path, iter::once(it)).into();

            let bind_path = make::ext::ident_path("it");
            let ok_arm = make::match_arm(iter::once(ok_tuple), make::expr_path(bind_path));

            let err_arm = make::match_arm(
                iter::once(make::wildcard_pat().into()),
                make::ext::expr_unreachable(),
            );

            let match_arm_list = make::match_arm_list(vec![ok_arm, err_arm]);
            let match_expr = make::expr_match(caller.clone(), match_arm_list)
                .indent(IndentLevel::from_node(method_call.syntax()));

            let range = method_call.syntax().text_range();
            match ctx.config.snippet_cap {
                Some(cap) => {
                    let err_arm = match_expr
                        .syntax()
                        .descendants()
                        .filter_map(ast::MatchArm::cast)
                        .last()
                        .unwrap();
                    let snippet =
                        render_snippet(cap, match_expr.syntax(), Cursor::Before(err_arm.syntax()));
                    builder.replace_snippet(cap, range, snippet)
                }
                None => builder.replace(range, match_expr.to_string()),
            }
        },
    )
}

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

    use super::*;

    #[test]
    fn test_replace_result_unwrap_with_match() {
        check_assist(
            replace_unwrap_with_match,
            r#"
//- minicore: result
fn i<T>(a: T) -> T { a }
fn main() {
    let x: Result<i32, i32> = Ok(92);
    let y = i(x).$0unwrap();
}
"#,
            r#"
fn i<T>(a: T) -> T { a }
fn main() {
    let x: Result<i32, i32> = Ok(92);
    let y = match i(x) {
        Ok(it) => it,
        $0_ => unreachable!(),
    };
}
"#,
        )
    }

    #[test]
    fn test_replace_option_unwrap_with_match() {
        check_assist(
            replace_unwrap_with_match,
            r#"
//- minicore: option
fn i<T>(a: T) -> T { a }
fn main() {
    let x = Some(92);
    let y = i(x).$0unwrap();
}
"#,
            r#"
fn i<T>(a: T) -> T { a }
fn main() {
    let x = Some(92);
    let y = match i(x) {
        Some(it) => it,
        $0_ => unreachable!(),
    };
}
"#,
        );
    }

    #[test]
    fn test_replace_result_unwrap_with_match_chaining() {
        check_assist(
            replace_unwrap_with_match,
            r#"
//- minicore: result
fn i<T>(a: T) -> T { a }
fn main() {
    let x: Result<i32, i32> = Ok(92);
    let y = i(x).$0unwrap().count_zeroes();
}
"#,
            r#"
fn i<T>(a: T) -> T { a }
fn main() {
    let x: Result<i32, i32> = Ok(92);
    let y = match i(x) {
        Ok(it) => it,
        $0_ => unreachable!(),
    }.count_zeroes();
}
"#,
        )
    }

    #[test]
    fn replace_unwrap_with_match_target() {
        check_assist_target(
            replace_unwrap_with_match,
            r#"
//- minicore: option
fn i<T>(a: T) -> T { a }
fn main() {
    let x = Some(92);
    let y = i(x).$0unwrap();
}
"#,
            r"i(x).unwrap()",
        );
    }
}