]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_let_with_if_let.rs
Merge #11481
[rust.git] / crates / ide_assists / src / handlers / replace_let_with_if_let.rs
1 use std::iter::once;
2
3 use ide_db::ty_filter::TryEnum;
4 use syntax::{
5     ast::{
6         self,
7         edit::{AstNodeEdit, IndentLevel},
8         make,
9     },
10     AstNode, T,
11 };
12
13 use crate::{AssistContext, AssistId, AssistKind, Assists};
14
15 // Assist: replace_let_with_if_let
16 //
17 // Replaces `let` with an `if let`.
18 //
19 // ```
20 // # enum Option<T> { Some(T), None }
21 //
22 // fn main(action: Action) {
23 //     $0let x = compute();
24 // }
25 //
26 // fn compute() -> Option<i32> { None }
27 // ```
28 // ->
29 // ```
30 // # enum Option<T> { Some(T), None }
31 //
32 // fn main(action: Action) {
33 //     if let Some(x) = compute() {
34 //     }
35 // }
36 //
37 // fn compute() -> Option<i32> { None }
38 // ```
39 pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
40     let let_kw = ctx.find_token_syntax_at_offset(T![let])?;
41     let let_stmt = let_kw.parent().and_then(ast::LetStmt::cast)?;
42     let init = let_stmt.initializer()?;
43     let original_pat = let_stmt.pat()?;
44
45     let target = let_kw.text_range();
46     acc.add(
47         AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite),
48         "Replace let with if let",
49         target,
50         |edit| {
51             let ty = ctx.sema.type_of_expr(&init);
52             let happy_variant = ty
53                 .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
54                 .map(|it| it.happy_case());
55             let pat = match happy_variant {
56                 None => original_pat,
57                 Some(var_name) => {
58                     make::tuple_struct_pat(make::ext::ident_path(var_name), once(original_pat))
59                         .into()
60                 }
61             };
62
63             let block =
64                 make::ext::empty_block_expr().indent(IndentLevel::from_node(let_stmt.syntax()));
65             let if_ = make::expr_if(make::expr_let(pat, init).into(), block, None);
66             let stmt = make::expr_stmt(if_);
67
68             edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
69         },
70     )
71 }
72
73 #[cfg(test)]
74 mod tests {
75     use crate::tests::check_assist;
76
77     use super::*;
78
79     #[test]
80     fn replace_let_unknown_enum() {
81         check_assist(
82             replace_let_with_if_let,
83             r"
84 enum E<T> { X(T), Y(T) }
85
86 fn main() {
87     $0let x = E::X(92);
88 }
89             ",
90             r"
91 enum E<T> { X(T), Y(T) }
92
93 fn main() {
94     if let x = E::X(92) {
95     }
96 }
97             ",
98         )
99     }
100 }