Skip to content

Commit

Permalink
Fix the remove unnecessary else action to preserve block tail expr
Browse files Browse the repository at this point in the history
  • Loading branch information
ShoyuVanilla authored and davidsemakula committed Feb 19, 2024
1 parent 21f4ff0 commit 8f6e212
Showing 1 changed file with 40 additions and 3 deletions.
43 changes: 40 additions & 3 deletions crates/ide-diagnostics/src/handlers/remove_unnecessary_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &RemoveUnnecessaryElse) -> Option<Vec<
indent = indent + 1;
}
let else_replacement = match if_expr.else_branch()? {
ast::ElseBranch::Block(ref block) => {
block.statements().map(|stmt| format!("\n{indent}{stmt}")).join("")
}
ast::ElseBranch::Block(ref block) => block
.statements()
.map(|stmt| format!("\n{indent}{stmt}"))
.chain(block.tail_expr().map(|tail| format!("\n{indent}{tail}")))
.join(""),
ast::ElseBranch::IfExpr(ref nested_if_expr) => {
format!("\n{indent}{nested_if_expr}")
}
Expand Down Expand Up @@ -171,6 +173,41 @@ fn test() {
);
}

#[test]
fn remove_unnecessary_else_for_return3() {
check_diagnostics_with_needless_return_disabled(
r#"
fn test(a: bool) -> i32 {
if a {
return 1;
} else {
//^^^^ 💡 weak: remove unnecessary else block
0
}
}
"#,
);
check_fix(
r#"
fn test(a: bool) -> i32 {
if a {
return 1;
} else$0 {
0
}
}
"#,
r#"
fn test(a: bool) -> i32 {
if a {
return 1;
}
0
}
"#,
);
}

#[test]
fn remove_unnecessary_else_for_return_in_child_if_expr() {
check_diagnostics_with_needless_return_disabled(
Expand Down

0 comments on commit 8f6e212

Please sign in to comment.