Skip to content

Commit 6e9fd75

Browse files
ShoyuVanilladavidsemakula
authored andcommitted
Fix the remove unnecessary else action to preserve block tail expr
1 parent 41e995a commit 6e9fd75

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

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

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &RemoveUnnecessaryElse) -> Option<Vec<
4141
indent = indent + 1;
4242
}
4343
let else_replacement = match if_expr.else_branch()? {
44-
ast::ElseBranch::Block(ref block) => {
45-
block.statements().map(|stmt| format!("\n{indent}{stmt}")).join("")
46-
}
44+
ast::ElseBranch::Block(ref block) => block
45+
.statements()
46+
.map(|stmt| format!("\n{indent}{stmt}"))
47+
.chain(block.tail_expr().map(|tail| format!("\n{indent}{tail}")))
48+
.join(""),
4749
ast::ElseBranch::IfExpr(ref nested_if_expr) => {
4850
format!("\n{indent}{nested_if_expr}")
4951
}
@@ -171,6 +173,41 @@ fn test() {
171173
);
172174
}
173175

176+
#[test]
177+
fn remove_unnecessary_else_for_return3() {
178+
check_diagnostics_with_needless_return_disabled(
179+
r#"
180+
fn test(a: bool) -> i32 {
181+
if a {
182+
return 1;
183+
} else {
184+
//^^^^ 💡 weak: remove unnecessary else block
185+
0
186+
}
187+
}
188+
"#,
189+
);
190+
check_fix(
191+
r#"
192+
fn test(a: bool) -> i32 {
193+
if a {
194+
return 1;
195+
} else$0 {
196+
0
197+
}
198+
}
199+
"#,
200+
r#"
201+
fn test(a: bool) -> i32 {
202+
if a {
203+
return 1;
204+
}
205+
0
206+
}
207+
"#,
208+
);
209+
}
210+
174211
#[test]
175212
fn remove_unnecessary_else_for_return_in_child_if_expr() {
176213
check_diagnostics_with_needless_return_disabled(

0 commit comments

Comments
 (0)