Skip to content

Commit

Permalink
remove trailing return in trailing if expression
Browse files Browse the repository at this point in the history
  • Loading branch information
davidsemakula committed Jan 31, 2024
1 parent 10132a1 commit ee44cf1
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
6 changes: 6 additions & 0 deletions crates/hir-ty/src/diagnostics/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,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,
Expand Down
60 changes: 60 additions & 0 deletions crates/ide-diagnostics/src/handlers/remove_trailing_return.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
}
}
"#,
);
}
Expand Down

0 comments on commit ee44cf1

Please sign in to comment.