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

Commit e9c80a9

Browse files
ShoyuVanilladavidsemakula
authored andcommitted
fix: False positive diagnostic for necessary else
1 parent ac1029f commit e9c80a9

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,13 @@ impl ExprValidator {
338338

339339
fn check_for_unnecessary_else(&mut self, id: ExprId, expr: &Expr, body: &Body) {
340340
if let Expr::If { condition: _, then_branch, else_branch } = expr {
341-
if else_branch.is_none() {
341+
if let Some(else_branch) = else_branch {
342+
// If else branch has a tail, it is an "expression" that produces a value,
343+
// 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;
346+
}
347+
} else {
342348
return;
343349
}
344350
if let Expr::Block { statements, tail, .. } = &body.exprs[*then_branch] {

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,29 @@ fn test() {
384384
return bar;
385385
}
386386
}
387+
"#,
388+
);
389+
}
390+
391+
#[test]
392+
fn no_diagnostic_if_tail_exists_in_else_branch() {
393+
check_diagnostics_with_needless_return_disabled(
394+
r#"
395+
fn test1(a: bool) {
396+
let _x = if a {
397+
return;
398+
} else {
399+
1
400+
};
401+
}
402+
403+
fn test2(a: bool) -> i32 {
404+
if a {
405+
return 1;
406+
} else {
407+
0
408+
}
409+
}
387410
"#,
388411
);
389412
}

0 commit comments

Comments
 (0)