Skip to content

Commit ce2ef31

Browse files
committed
fix(needless_if): don't expand macro invocations in the suggestion
1 parent d1b51ea commit ce2ef31

File tree

4 files changed

+34
-3
lines changed

4 files changed

+34
-3
lines changed

clippy_lints/src/needless_if.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::higher::If;
33
use clippy_utils::is_from_proc_macro;
4-
use clippy_utils::source::SpanRangeExt;
4+
use clippy_utils::source::{SpanRangeExt, walk_span_to_context};
55
use rustc_errors::Applicability;
66
use rustc_hir::{ExprKind, Stmt, StmtKind};
77
use rustc_lint::{LateContext, LateLintPass, LintContext};
@@ -56,7 +56,8 @@ impl LateLintPass<'_> for NeedlessIf {
5656
src.bytes()
5757
.all(|ch| matches!(ch, b'{' | b'}') || ch.is_ascii_whitespace())
5858
})
59-
&& let Some(cond_snippet) = cond.span.get_source_text(cx)
59+
&& let Some(cond_span) = walk_span_to_context(cond.span, expr.span.ctxt())
60+
&& let Some(cond_snippet) = cond_span.get_source_text(cx)
6061
&& !is_from_proc_macro(cx, expr)
6162
{
6263
span_lint_and_sugg(

tests/ui/needless_if.fixed

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,12 @@ fn main() {
104104

105105
let () = if maybe_side_effect() {};
106106
}
107+
108+
fn issue15960() -> i32 {
109+
matches!(2, 3);
110+
//~^ needless_if
111+
matches!(2, 3) == (2 * 2 == 5);
112+
//~^ needless_if
113+
114+
1 // put something here so that `if` is a statement not an expression
115+
}

tests/ui/needless_if.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,12 @@ fn main() {
105105

106106
let () = if maybe_side_effect() {};
107107
}
108+
109+
fn issue15960() -> i32 {
110+
if matches!(2, 3) {}
111+
//~^ needless_if
112+
if matches!(2, 3) == (2 * 2 == 5) {}
113+
//~^ needless_if
114+
115+
1 // put something here so that `if` is a statement not an expression
116+
}

tests/ui/needless_if.stderr

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,17 @@ error: this `if` branch is empty
7474
LL | if true {}
7575
| ^^^^^^^^^^ help: you can remove it: `true;`
7676

77-
error: aborting due to 7 previous errors
77+
error: this `if` branch is empty
78+
--> tests/ui/needless_if.rs:110:5
79+
|
80+
LL | if matches!(2, 3) {}
81+
| ^^^^^^^^^^^^^^^^^^^^ help: you can remove it: `matches!(2, 3);`
82+
83+
error: this `if` branch is empty
84+
--> tests/ui/needless_if.rs:112:5
85+
|
86+
LL | if matches!(2, 3) == (2 * 2 == 5) {}
87+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: you can remove it: `matches!(2, 3) == (2 * 2 == 5);`
88+
89+
error: aborting due to 9 previous errors
7890

0 commit comments

Comments
 (0)