Skip to content

Commit c3948d1

Browse files
committed
Auto merge of rust-lang#12549 - granddaifuku:fix/suspicious_else_formatting-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
2 parents be27f68 + b9da637 commit c3948d1

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

clippy_lints/src/formatting.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
215215
// it’s bad when there is a ‘\n’ after the “else”
216216
&& let Some(else_snippet) = snippet_opt(cx, else_span)
217217
&& let Some((pre_else, post_else)) = else_snippet.split_once("else")
218+
&& !else_snippet.contains('/')
218219
&& let Some((_, post_else_post_eol)) = post_else.split_once('\n')
219220
{
220221
// Allow allman style braces `} \n else \n {`

tests/ui/suspicious_else_formatting.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,34 @@ fn main() {
120120
/* whelp */
121121
{
122122
}
123+
124+
// #12497 Don't trigger lint as rustfmt wants it
125+
if true {
126+
println!("true");
127+
}
128+
/*else if false {
129+
}*/
130+
else {
131+
println!("false");
132+
}
133+
134+
if true {
135+
println!("true");
136+
} // else if false {}
137+
else {
138+
println!("false");
139+
}
140+
141+
if true {
142+
println!("true");
143+
} /* if true {
144+
println!("true");
145+
}
146+
*/
147+
else {
148+
println!("false");
149+
}
150+
123151
}
124152

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

0 commit comments

Comments
 (0)