]> git.lizzy.rs Git - rust.git/blob - crates/ide_assists/src/handlers/replace_let_with_if_let.rs
Invert boolean literals in assist negation logic
[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.ancestors().find_map(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 with if-let",
49         target,
50         |edit| {
51             let ty = ctx.sema.type_of_expr(&init);
52             let happy_variant =
53                 ty.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty)).map(|it| it.happy_case());
54             let pat = match happy_variant {
55                 None => original_pat,
56                 Some(var_name) => {
57                     make::tuple_struct_pat(make::ext::ident_path(var_name), once(original_pat))
58                         .into()
59                 }
60             };
61
62             let block =
63                 make::ext::empty_block_expr().indent(IndentLevel::from_node(let_stmt.syntax()));
64             let if_ = make::expr_if(make::condition(init, Some(pat)), block, None);
65             let stmt = make::expr_stmt(if_);
66
67             edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
68         },
69     )
70 }
71
72 #[cfg(test)]
73 mod tests {
74     use crate::tests::check_assist;
75
76     use super::*;
77
78     #[test]
79     fn replace_let_unknown_enum() {
80         check_assist(
81             replace_let_with_if_let,
82             r"
83 enum E<T> { X(T), Y(T) }
84
85 fn main() {
86     $0let x = E::X(92);
87 }
88             ",
89             r"
90 enum E<T> { X(T), Y(T) }
91
92 fn main() {
93     if let x = E::X(92) {
94     }
95 }
96             ",
97         )
98     }
99 }