remove trailing return in trailing if expression

This commit is contained in:
davidsemakula 2024-01-31 06:46:48 +03:00
parent 2987fac76f
commit cad222ff1b
2 changed files with 66 additions and 0 deletions

View file

@ -266,6 +266,12 @@ impl ExprValidator {
self.check_for_trailing_return(last_stmt, body);
}
}
Expr::If { then_branch, else_branch, .. } => {
self.check_for_trailing_return(*then_branch, body);
if let Some(else_branch) = else_branch {
self.check_for_trailing_return(*else_branch, body);
}
}
Expr::Return { .. } => {
self.diagnostics.push(BodyValidationDiagnostic::RemoveTrailingReturn {
return_expr: body_expr,

View file

@ -131,6 +131,22 @@ fn foo() -> u8 {
);
}
#[test]
fn remove_trailing_return_in_if() {
check_diagnostics(
r#"
fn foo(x: usize) -> u8 {
if x > 0 {
return 1;
//^^^^^^^^^ 💡 weak: replace return <expr>; with <expr>
} else {
return 0;
} //^^^^^^^^^ 💡 weak: replace return <expr>; with <expr>
}
"#,
);
}
#[test]
fn no_diagnostic_if_no_return_keyword() {
check_diagnostics(
@ -256,6 +272,50 @@ fn foo() -> u8 {
};
bar()
}
"#,
);
}
#[test]
fn replace_in_if() {
check_fix(
r#"
fn foo(x: usize) -> u8 {
if x > 0 {
return$0 1;
} else {
0
}
}
"#,
r#"
fn foo(x: usize) -> u8 {
if x > 0 {
1
} else {
0
}
}
"#,
);
check_fix(
r#"
fn foo(x: usize) -> u8 {
if x > 0 {
1
} else {
return$0 0;
}
}
"#,
r#"
fn foo(x: usize) -> u8 {
if x > 0 {
1
} else {
0
}
}
"#,
);
}