1 //! Lint on unnecessary double comparisons. Some examples:
5 use syntax::codemap::Span;
7 use utils::{snippet, span_lint_and_sugg, SpanlessEq};
9 /// **What it does:** Checks for double comparions that could be simpified to a single expression.
12 /// **Why is this bad?** Readability.
14 /// **Known problems:** None.
21 /// Could be written as:
26 declare_clippy_lint! {
27 pub DOUBLE_COMPARISONS,
29 "unnecessary double comparisons that can be simplified"
32 pub struct DoubleComparisonPass;
34 impl LintPass for DoubleComparisonPass {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(DOUBLE_COMPARISONS)
40 impl<'a, 'tcx> DoubleComparisonPass {
43 cx: &LateContext<'a, 'tcx>,
49 let (lkind, llhs, lrhs, rkind, rlhs, rrhs) = match (lhs.node.clone(), rhs.node.clone()) {
50 (ExprBinary(lb, llhs, lrhs), ExprBinary(rb, rlhs, rrhs)) => {
51 (lb.node, llhs, lrhs, rb.node, rlhs, rrhs)
55 let mut spanless_eq = SpanlessEq::new(cx).ignore_fn();
56 if !(spanless_eq.eq_expr(&llhs, &rlhs) && spanless_eq.eq_expr(&lrhs, &rrhs)) {
59 macro_rules! lint_double_comparison {
61 let lhs_str = snippet(cx, llhs.span, "");
62 let rhs_str = snippet(cx, lrhs.span, "");
63 let sugg = format!("{} {} {}", lhs_str, stringify!($op), rhs_str);
64 span_lint_and_sugg(cx, DOUBLE_COMPARISONS, span,
65 "This binary expression can be simplified",
69 match (op, lkind, rkind) {
70 (BiOr, BiEq, BiLt) | (BiOr, BiLt, BiEq) => lint_double_comparison!(<=),
71 (BiOr, BiEq, BiGt) | (BiOr, BiGt, BiEq) => lint_double_comparison!(>=),
72 (BiOr, BiLt, BiGt) | (BiOr, BiGt, BiLt) => lint_double_comparison!(!=),
73 (BiAnd, BiLe, BiGe) | (BiAnd, BiGe, BiLe) => lint_double_comparison!(==),
79 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DoubleComparisonPass {
80 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
81 if let ExprBinary(ref kind, ref lhs, ref rhs) = expr.node {
82 self.check_binop(cx, kind.node, lhs, rhs, expr.span);