|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::eq_expr_value; |
| 3 | +use clippy_utils::source::snippet_with_applicability; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::{BinOpKind, Expr, ExprKind}; |
| 6 | +use rustc_lint::LateContext; |
| 7 | +use rustc_span::source_map::Span; |
| 8 | + |
| 9 | +use super::DOUBLE_COMPARISONS; |
| 10 | + |
| 11 | +#[expect(clippy::similar_names)] |
| 12 | +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, span: Span) { |
| 13 | + let (lkind, llhs, lrhs, rkind, rlhs, rrhs) = match (&lhs.kind, &rhs.kind) { |
| 14 | + (ExprKind::Binary(lb, llhs, lrhs), ExprKind::Binary(rb, rlhs, rrhs)) => { |
| 15 | + (lb.node, llhs, lrhs, rb.node, rlhs, rrhs) |
| 16 | + }, |
| 17 | + _ => return, |
| 18 | + }; |
| 19 | + if !(eq_expr_value(cx, llhs, rlhs) && eq_expr_value(cx, lrhs, rrhs)) { |
| 20 | + return; |
| 21 | + } |
| 22 | + macro_rules! lint_double_comparison { |
| 23 | + ($op:tt) => {{ |
| 24 | + let mut applicability = Applicability::MachineApplicable; |
| 25 | + let lhs_str = snippet_with_applicability(cx, llhs.span, "", &mut applicability); |
| 26 | + let rhs_str = snippet_with_applicability(cx, lrhs.span, "", &mut applicability); |
| 27 | + let sugg = format!("{} {} {}", lhs_str, stringify!($op), rhs_str); |
| 28 | + span_lint_and_sugg( |
| 29 | + cx, |
| 30 | + DOUBLE_COMPARISONS, |
| 31 | + span, |
| 32 | + "this binary expression can be simplified", |
| 33 | + "try", |
| 34 | + sugg, |
| 35 | + applicability, |
| 36 | + ); |
| 37 | + }}; |
| 38 | + } |
| 39 | + match (op, lkind, rkind) { |
| 40 | + (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Lt) | (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Eq) => { |
| 41 | + lint_double_comparison!(<=); |
| 42 | + }, |
| 43 | + (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Eq) => { |
| 44 | + lint_double_comparison!(>=); |
| 45 | + }, |
| 46 | + (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Lt) => { |
| 47 | + lint_double_comparison!(!=); |
| 48 | + }, |
| 49 | + (BinOpKind::And, BinOpKind::Le, BinOpKind::Ge) | (BinOpKind::And, BinOpKind::Ge, BinOpKind::Le) => { |
| 50 | + lint_double_comparison!(==); |
| 51 | + }, |
| 52 | + _ => (), |
| 53 | + }; |
| 54 | +} |
0 commit comments