1 //! Lint on unnecessary double comparisons. Some examples:
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::eq_expr_value;
5 use clippy_utils::source::snippet_with_applicability;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BinOpKind, Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::Span;
12 declare_clippy_lint! {
14 /// Checks for double comparisons that could be simplified to a single expression.
17 /// ### Why is this bad?
24 /// if x == y || x < y {}
27 /// Could be written as:
34 #[clippy::version = "pre 1.29.0"]
35 pub DOUBLE_COMPARISONS,
37 "unnecessary double comparisons that can be simplified"
40 declare_lint_pass!(DoubleComparisons => [DOUBLE_COMPARISONS]);
42 impl<'tcx> DoubleComparisons {
43 #[allow(clippy::similar_names)]
44 fn check_binop(cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, span: Span) {
45 let (lkind, llhs, lrhs, rkind, rlhs, rrhs) = match (&lhs.kind, &rhs.kind) {
46 (ExprKind::Binary(lb, llhs, lrhs), ExprKind::Binary(rb, rlhs, rrhs)) => {
47 (lb.node, llhs, lrhs, rb.node, rlhs, rrhs)
51 if !(eq_expr_value(cx, llhs, rlhs) && eq_expr_value(cx, lrhs, rrhs)) {
54 macro_rules! lint_double_comparison {
56 let mut applicability = Applicability::MachineApplicable;
57 let lhs_str = snippet_with_applicability(cx, llhs.span, "", &mut applicability);
58 let rhs_str = snippet_with_applicability(cx, lrhs.span, "", &mut applicability);
59 let sugg = format!("{} {} {}", lhs_str, stringify!($op), rhs_str);
64 "this binary expression can be simplified",
72 match (op, lkind, rkind) {
73 (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Lt) | (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Eq) => {
74 lint_double_comparison!(<=);
76 (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Eq) => {
77 lint_double_comparison!(>=);
79 (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Lt) => {
80 lint_double_comparison!(!=);
82 (BinOpKind::And, BinOpKind::Le, BinOpKind::Ge) | (BinOpKind::And, BinOpKind::Ge, BinOpKind::Le) => {
83 lint_double_comparison!(==);
90 impl<'tcx> LateLintPass<'tcx> for DoubleComparisons {
91 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
92 if let ExprKind::Binary(ref kind, lhs, rhs) = expr.kind {
93 Self::check_binop(cx, kind.node, lhs, rhs, expr.span);