diff --git a/clippy_lints/src/collapsible_if.rs b/clippy_lints/src/collapsible_if.rs index 67ef10482..a55ca04f7 100644 --- a/clippy_lints/src/collapsible_if.rs +++ b/clippy_lints/src/collapsible_if.rs @@ -113,10 +113,10 @@ fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) { } fn block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool { - // The zeroth character in the trimmed block text is "{", which marks the beginning of the block. - // Therefore, we check if the first string after that is a comment, i.e. starts with //. - let trimmed_block_text = snippet_block(cx, expr.span, "..").trim_left().to_owned(); - trimmed_block_text[1..trimmed_block_text.len()].trim_left().starts_with("//") + // We trim all opening braces and whitespaces and then check if the next string is a comment. + let trimmed_block_text = + snippet_block(cx, expr.span, "..").trim_left_matches(|c: char| c.is_whitespace() || c == '{').to_owned(); + trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*") } fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) { diff --git a/tests/ui/collapsible_if.rs b/tests/ui/collapsible_if.rs index c186d9e57..1bc866010 100644 --- a/tests/ui/collapsible_if.rs +++ b/tests/ui/collapsible_if.rs @@ -196,4 +196,17 @@ fn main() { println!("world!") } } + + if x == "hello" { + /* Not collapsible */ + if y == "world" { + println!("Hello world!"); + } + } + + if x == "hello" { /* Not collapsible */ + if y == "world" { + println!("Hello world!"); + } + } }