Skip to content

Commit 62e7d9f

Browse files
authored
Merge pull request #19433 from snprajwal/fix-replace-let-else
fix(ide-assists): `let else` to `if let else`
2 parents b057d82 + 4fdb7dc commit 62e7d9f

File tree

1 file changed

+41
-8
lines changed

1 file changed

+41
-8
lines changed

crates/ide-assists/src/handlers/replace_let_with_if_let.rs

+41-8
Original file line numberDiff line numberDiff line change
@@ -45,19 +45,31 @@ pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext<'_>
4545
let mut editor = builder.make_editor(let_stmt.syntax());
4646
let make = SyntaxFactory::new();
4747
let ty = ctx.sema.type_of_expr(&init);
48-
let happy_variant = ty
49-
.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
50-
.map(|it| it.happy_case());
51-
let pat = match happy_variant {
52-
None => original_pat,
53-
Some(var_name) => {
54-
make.tuple_struct_pat(make.ident_path(var_name), [original_pat]).into()
48+
let pat = if let_stmt.let_else().is_some() {
49+
// Do not add the wrapper type that implements `Try`,
50+
// since the statement already wraps the pattern.
51+
original_pat
52+
} else {
53+
let happy_variant = ty
54+
.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
55+
.map(|it| it.happy_case());
56+
match happy_variant {
57+
None => original_pat,
58+
Some(var_name) => {
59+
make.tuple_struct_pat(make.ident_path(var_name), [original_pat]).into()
60+
}
5561
}
5662
};
5763

5864
let block = make.block_expr([], None);
5965
block.indent(IndentLevel::from_node(let_stmt.syntax()));
60-
let if_expr = make.expr_if(make.expr_let(pat, init).into(), block, None);
66+
let if_expr = make.expr_if(
67+
make.expr_let(pat, init).into(),
68+
block,
69+
let_stmt
70+
.let_else()
71+
.and_then(|let_else| let_else.block_expr().map(ast::ElseBranch::from)),
72+
);
6173
let if_stmt = make.expr_stmt(if_expr.into());
6274

6375
editor.replace(let_stmt.syntax(), if_stmt.syntax());
@@ -90,6 +102,27 @@ enum E<T> { X(T), Y(T) }
90102
fn main() {
91103
if let x = E::X(92) {
92104
}
105+
}
106+
",
107+
)
108+
}
109+
110+
#[test]
111+
fn replace_let_else() {
112+
check_assist(
113+
replace_let_with_if_let,
114+
r"
115+
//- minicore: option
116+
fn main() {
117+
let a = Some(1);
118+
$0let Some(_) = a else { unreachable!() };
119+
}
120+
",
121+
r"
122+
fn main() {
123+
let a = Some(1);
124+
if let Some(_) = a {
125+
} else { unreachable!() }
93126
}
94127
",
95128
)

0 commit comments

Comments
 (0)