3 use ide_db::ty_filter::TryEnum;
7 edit::{AstNodeEdit, IndentLevel},
13 use crate::{AssistContext, AssistId, AssistKind, Assists};
15 // Assist: replace_let_with_if_let
17 // Replaces `let` with an `if-let`.
20 // # enum Option<T> { Some(T), None }
22 // fn main(action: Action) {
23 // $0let x = compute();
26 // fn compute() -> Option<i32> { None }
30 // # enum Option<T> { Some(T), None }
32 // fn main(action: Action) {
33 // if let Some(x) = compute() {
37 // fn compute() -> Option<i32> { None }
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()?;
45 let target = let_kw.text_range();
47 AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite),
48 "Replace with if-let",
51 let ty = ctx.sema.type_of_expr(&init);
53 ty.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty)).map(|it| it.happy_case());
54 let pat = match happy_variant {
57 make::tuple_struct_pat(make::ext::ident_path(var_name), once(original_pat))
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_);
67 edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
74 use crate::tests::check_assist;
79 fn replace_let_unknown_enum() {
81 replace_let_with_if_let,
83 enum E<T> { X(T), Y(T) }
90 enum E<T> { X(T), Y(T) }