Skip to content

Commit

Permalink
Auto merge of rust-lang#12549 - granddaifuku:fix/suspicious_else_form…
Browse files Browse the repository at this point in the history
…atting-false-positive-when-commented-else, r=Alexendoo

fix: `suspicious_else_formatting` false positive when else is included …

This PR addresses an issue where invalid suggestions are generated for `if-else` formatting if comments contain the keyword `else`.

The root of the problem is identified [here](https://github.com/rust-lang/rust-clippy/blob/95c62ffae9bbce793f68a6f1473e3fc24af19bdd/clippy_lints/src/formatting.rs#L217). Specifically, when a comment contains the word `else`, the lint mistakenly interprets it as part of an `if-else` clause. This misinterpretation leads to an incorrect splitting of the snippet, resulting in erroneous suggestions.

fixes: rust-lang#12497

changelog: [`suspicious_else_formatting`]: Fixes invalid suggestions when comments include word else
  • Loading branch information
bors committed Mar 25, 2024
2 parents be27f68 + b9da637 commit c3948d1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions clippy_lints/src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
// it’s bad when there is a ‘\n’ after the “else”
&& let Some(else_snippet) = snippet_opt(cx, else_span)
&& let Some((pre_else, post_else)) = else_snippet.split_once("else")
&& !else_snippet.contains('/')
&& let Some((_, post_else_post_eol)) = post_else.split_once('\n')
{
// Allow allman style braces `} \n else \n {`
Expand Down
28 changes: 28 additions & 0 deletions tests/ui/suspicious_else_formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,34 @@ fn main() {
/* whelp */
{
}

// #12497 Don't trigger lint as rustfmt wants it
if true {
println!("true");
}
/*else if false {
}*/
else {
println!("false");
}

if true {
println!("true");
} // else if false {}
else {
println!("false");
}

if true {
println!("true");
} /* if true {
println!("true");
}
*/
else {
println!("false");
}

}

// #7650 - Don't lint. Proc-macro using bad spans for `if` expressions.
Expand Down

0 comments on commit c3948d1

Please sign in to comment.