Skip to content

Commit ccd5130

Browse files
committed
extract each lint into its own module
1 parent 54a84c1 commit ccd5130

File tree

5 files changed

+701
-640
lines changed

5 files changed

+701
-640
lines changed

clippy_lints/src/ptr/cmp_null.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use super::CMP_NULL;
2+
use clippy_utils::diagnostics::span_lint_and_sugg;
3+
use clippy_utils::res::{MaybeDef, MaybeResPath};
4+
use clippy_utils::sugg::Sugg;
5+
use clippy_utils::{is_lint_allowed, sym};
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{BinOpKind, Expr, ExprKind};
8+
use rustc_lint::LateContext;
9+
10+
pub(super) fn check<'tcx>(
11+
cx: &LateContext<'tcx>,
12+
expr: &'tcx Expr<'_>,
13+
op: BinOpKind,
14+
l: &Expr<'_>,
15+
r: &Expr<'_>,
16+
) -> bool {
17+
let non_null_path_snippet = match (
18+
is_lint_allowed(cx, CMP_NULL, expr.hir_id),
19+
is_null_path(cx, l),
20+
is_null_path(cx, r),
21+
) {
22+
(false, true, false) if let Some(sugg) = Sugg::hir_opt(cx, r) => sugg.maybe_paren(),
23+
(false, false, true) if let Some(sugg) = Sugg::hir_opt(cx, l) => sugg.maybe_paren(),
24+
_ => return false,
25+
};
26+
let invert = if op == BinOpKind::Eq { "" } else { "!" };
27+
28+
span_lint_and_sugg(
29+
cx,
30+
CMP_NULL,
31+
expr.span,
32+
"comparing with null is better expressed by the `.is_null()` method",
33+
"try",
34+
format!("{invert}{non_null_path_snippet}.is_null()",),
35+
Applicability::MachineApplicable,
36+
);
37+
true
38+
}
39+
40+
fn is_null_path(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
41+
if let ExprKind::Call(pathexp, []) = expr.kind {
42+
matches!(
43+
pathexp.basic_res().opt_diag_name(cx),
44+
Some(sym::ptr_null | sym::ptr_null_mut)
45+
)
46+
} else {
47+
false
48+
}
49+
}

0 commit comments

Comments
 (0)