diff --git a/clippy_lints/src/needless_if.rs b/clippy_lints/src/needless_if.rs index c90019f6ee16..c550700757bf 100644 --- a/clippy_lints/src/needless_if.rs +++ b/clippy_lints/src/needless_if.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::higher::If; use clippy_utils::is_from_proc_macro; -use clippy_utils::source::SpanRangeExt; +use clippy_utils::source::{SpanRangeExt, walk_span_to_context}; use rustc_errors::Applicability; use rustc_hir::{ExprKind, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; @@ -56,7 +56,8 @@ impl LateLintPass<'_> for NeedlessIf { src.bytes() .all(|ch| matches!(ch, b'{' | b'}') || ch.is_ascii_whitespace()) }) - && let Some(cond_snippet) = cond.span.get_source_text(cx) + && let Some(cond_span) = walk_span_to_context(cond.span, expr.span.ctxt()) + && let Some(cond_snippet) = cond_span.get_source_text(cx) && !is_from_proc_macro(cx, expr) { span_lint_and_sugg( diff --git a/tests/ui/needless_if.fixed b/tests/ui/needless_if.fixed index c839156bed9b..e371c6463854 100644 --- a/tests/ui/needless_if.fixed +++ b/tests/ui/needless_if.fixed @@ -104,3 +104,12 @@ fn main() { let () = if maybe_side_effect() {}; } + +fn issue15960() -> i32 { + matches!(2, 3); + //~^ needless_if + matches!(2, 3) == (2 * 2 == 5); + //~^ needless_if + + 1 // put something here so that `if` is a statement not an expression +} diff --git a/tests/ui/needless_if.rs b/tests/ui/needless_if.rs index 11103af5c559..9d73d9104dd9 100644 --- a/tests/ui/needless_if.rs +++ b/tests/ui/needless_if.rs @@ -105,3 +105,12 @@ fn main() { let () = if maybe_side_effect() {}; } + +fn issue15960() -> i32 { + if matches!(2, 3) {} + //~^ needless_if + if matches!(2, 3) == (2 * 2 == 5) {} + //~^ needless_if + + 1 // put something here so that `if` is a statement not an expression +} diff --git a/tests/ui/needless_if.stderr b/tests/ui/needless_if.stderr index 4b56843bd522..b81a3890afa1 100644 --- a/tests/ui/needless_if.stderr +++ b/tests/ui/needless_if.stderr @@ -74,5 +74,17 @@ error: this `if` branch is empty LL | if true {} | ^^^^^^^^^^ help: you can remove it: `true;` -error: aborting due to 7 previous errors +error: this `if` branch is empty + --> tests/ui/needless_if.rs:110:5 + | +LL | if matches!(2, 3) {} + | ^^^^^^^^^^^^^^^^^^^^ help: you can remove it: `matches!(2, 3);` + +error: this `if` branch is empty + --> tests/ui/needless_if.rs:112:5 + | +LL | if matches!(2, 3) == (2 * 2 == 5) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: you can remove it: `matches!(2, 3) == (2 * 2 == 5);` + +error: aborting due to 9 previous errors