Skip to content

Commit 75f0701

Browse files
committed
Add heuristic to determine type of IdentPat, make check for empty expressions correct
1 parent d669528 commit 75f0701

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

crates/ide_assists/src/handlers/replace_if_let_with_match.rs

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -235,24 +235,36 @@ fn pick_pattern_and_expr_order(
235235
) -> Option<(ast::Pat, ast::Expr, ast::Expr)> {
236236
let res = match (pat, pat2) {
237237
(ast::Pat::WildcardPat(_), _) => return None,
238-
(pat, _) if expr2.syntax().first_child().is_none() => (pat, expr, expr2),
239-
(_, pat) if expr.syntax().first_child().is_none() => (pat, expr2, expr),
238+
(pat, _) if is_empty_expr(&expr2) => (pat, expr, expr2),
239+
(_, pat) if is_empty_expr(&expr) => (pat, expr2, expr),
240240
(pat, pat2) => match (binds_name(&pat), binds_name(&pat2)) {
241+
(true, true) => return None,
241242
(true, false) => (pat, expr, expr2),
242243
(false, true) => (pat2, expr2, expr),
243244
_ if is_sad_pat(sema, &pat2) => (pat, expr, expr2),
244245
_ if is_sad_pat(sema, &pat) => (pat2, expr2, expr),
245-
(true, true) => return None,
246246
(false, false) => (pat, expr, expr2),
247247
},
248248
};
249249
Some(res)
250250
}
251251

252+
fn is_empty_expr(expr: &ast::Expr) -> bool {
253+
match expr {
254+
ast::Expr::BlockExpr(expr) => {
255+
expr.statements().next().is_none() && expr.tail_expr().is_none()
256+
}
257+
ast::Expr::TupleExpr(expr) => expr.fields().next().is_none(),
258+
_ => false,
259+
}
260+
}
261+
252262
fn binds_name(pat: &ast::Pat) -> bool {
253263
let binds_name_v = |pat| binds_name(&pat);
254264
match pat {
255-
ast::Pat::IdentPat(_) => true,
265+
ast::Pat::IdentPat(pat) => {
266+
pat.to_string().starts_with(|c: char| c.is_lowercase() && c != '_')
267+
}
256268
ast::Pat::MacroPat(_) => true,
257269
ast::Pat::OrPat(pat) => pat.pats().any(binds_name_v),
258270
ast::Pat::SlicePat(pat) => pat.pats().any(binds_name_v),
@@ -704,6 +716,28 @@ fn main() {
704716
)
705717
}
706718

719+
#[test]
720+
fn replace_match_with_if_let_number_body() {
721+
check_assist(
722+
replace_match_with_if_let,
723+
r#"
724+
fn main() {
725+
$0match Ok(()) {
726+
Ok(()) => {},
727+
Err(_) => 0,
728+
}
729+
}
730+
"#,
731+
r#"
732+
fn main() {
733+
if let Err(_) = Ok(()) {
734+
0
735+
}
736+
}
737+
"#,
738+
)
739+
}
740+
707741
#[test]
708742
fn replace_match_with_if_let_exhaustive() {
709743
check_assist(

0 commit comments

Comments
 (0)