1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! Lint on unnecessary double comparisons. Some examples:
13 use crate::rustc::hir::*;
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::syntax::source_map::Span;
18 use crate::utils::{snippet, span_lint_and_sugg, SpanlessEq};
20 /// **What it does:** Checks for double comparions that could be simpified to a single expression.
23 /// **Why is this bad?** Readability.
25 /// **Known problems:** None.
32 /// Could be written as:
37 declare_clippy_lint! {
38 pub DOUBLE_COMPARISONS,
40 "unnecessary double comparisons that can be simplified"
43 pub struct DoubleComparisonPass;
45 impl LintPass for DoubleComparisonPass {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(DOUBLE_COMPARISONS)
51 impl<'a, 'tcx> DoubleComparisonPass {
54 cx: &LateContext<'a, 'tcx>,
60 let (lkind, llhs, lrhs, rkind, rlhs, rrhs) = match (lhs.node.clone(), rhs.node.clone()) {
61 (ExprKind::Binary(lb, llhs, lrhs), ExprKind::Binary(rb, rlhs, rrhs)) => {
62 (lb.node, llhs, lrhs, rb.node, rlhs, rrhs)
66 let mut spanless_eq = SpanlessEq::new(cx).ignore_fn();
67 if !(spanless_eq.eq_expr(&llhs, &rlhs) && spanless_eq.eq_expr(&lrhs, &rrhs)) {
70 macro_rules! lint_double_comparison {
72 let lhs_str = snippet(cx, llhs.span, "");
73 let rhs_str = snippet(cx, lrhs.span, "");
74 let sugg = format!("{} {} {}", lhs_str, stringify!($op), rhs_str);
75 span_lint_and_sugg(cx, DOUBLE_COMPARISONS, span,
76 "This binary expression can be simplified",
80 match (op, lkind, rkind) {
81 (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Lt) | (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Eq) => lint_double_comparison!(<=),
82 (BinOpKind::Or, BinOpKind::Eq, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Eq) => lint_double_comparison!(>=),
83 (BinOpKind::Or, BinOpKind::Lt, BinOpKind::Gt) | (BinOpKind::Or, BinOpKind::Gt, BinOpKind::Lt) => lint_double_comparison!(!=),
84 (BinOpKind::And, BinOpKind::Le, BinOpKind::Ge) | (BinOpKind::And, BinOpKind::Ge, BinOpKind::Le) => lint_double_comparison!(==),
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DoubleComparisonPass {
91 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
92 if let ExprKind::Binary(ref kind, ref lhs, ref rhs) = expr.node {
93 self.check_binop(cx, kind.node, lhs, rhs, expr.span);