Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit d14b228

Browse files
ShoyuVanilladavidsemakula
authored andcommitted
Handle cases for else if
1 parent e9c80a9 commit d14b228

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

crates/hir-ty/src/diagnostics/expr.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -341,8 +341,23 @@ impl ExprValidator {
341341
if let Some(else_branch) = else_branch {
342342
// If else branch has a tail, it is an "expression" that produces a value,
343343
// e.g. `let a = if { ... } else { ... };` and this `else` is not unnecessary
344-
if let Expr::Block { tail: Some(_), .. } = body.exprs[*else_branch] {
345-
return;
344+
let mut branch = *else_branch;
345+
loop {
346+
match body.exprs[branch] {
347+
Expr::Block { tail: Some(_), .. } => return,
348+
Expr::If { then_branch, else_branch, .. } => {
349+
if let Expr::Block { tail: Some(_), .. } = body.exprs[then_branch] {
350+
return;
351+
}
352+
if let Some(else_branch) = else_branch {
353+
// Continue checking for branches like `if { ... } else if { ... } else...`
354+
branch = else_branch;
355+
continue;
356+
}
357+
}
358+
_ => break,
359+
}
360+
break;
346361
}
347362
} else {
348363
return;

crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,18 @@ fn test2(a: bool) -> i32 {
407407
0
408408
}
409409
}
410+
411+
fn test3(a: bool, b: bool, c: bool) {
412+
let _x = if a {
413+
return;
414+
} else if b {
415+
return;
416+
} else if c {
417+
1
418+
} else {
419+
return;
420+
};
421+
}
410422
"#,
411423
);
412424
}

0 commit comments

Comments
 (0)