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.parent().and_then(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 let with if let",
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 {
58 make::tuple_struct_pat(make::ext::ident_path(var_name), once(original_pat))
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_);
68 edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
75 use crate::tests::check_assist;
80 fn replace_let_unknown_enum() {
82 replace_let_with_if_let,
84 enum E<T> { X(T), Y(T) }
91 enum E<T> { X(T), Y(T) }