]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/comparison_chain.rs
Add a new lint for comparison chains
[rust.git] / clippy_lints / src / comparison_chain.rs
1 use crate::utils::{if_sequence, parent_node_is_if_expr, span_help_and_lint, SpanlessEq};
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
5
6 declare_clippy_lint! {
7     /// **What it does:** Checks comparison chains written with `if` that can be
8     /// rewritten with `match` and `cmp`.
9     ///
10     /// **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get
11     /// repetitive
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     /// ```rust,ignore
17     /// # fn a() {}
18     /// # fn b() {}
19     /// # fn c() {}
20     /// fn f(x: u8, y: u8) {
21     ///     if x > y {
22     ///         a()
23     ///     } else if x < y {
24     ///         b()
25     ///     } else {
26     ///         c()
27     ///     }
28     /// }
29     /// ```
30     ///
31     /// Could be written:
32     ///
33     /// ```rust,ignore
34     /// use std::cmp::Ordering;
35     /// # fn a() {}
36     /// # fn b() {}
37     /// # fn c() {}
38     /// fn f(x: u8, y: u8) {
39     ///      match x.cmp(y) {
40     ///          Ordering::Greater => a(),
41     ///          Ordering::Less => b(),
42     ///          Ordering::Equal => c()
43     ///      }
44     /// }
45     /// ```
46     pub COMPARISON_CHAIN,
47     style,
48     "`if`s that can be rewritten with `match` and `cmp`"
49 }
50
51 declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]);
52
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ComparisonChain {
54     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
55         if expr.span.from_expansion() {
56             return;
57         }
58
59         // We only care about the top-most `if` in the chain
60         if parent_node_is_if_expr(expr, cx) {
61             return;
62         }
63
64         // Check that there exists at least one explicit else condition
65         let (conds, _) = if_sequence(expr);
66         if conds.len() < 2 {
67             return;
68         }
69
70         for cond in conds.windows(2) {
71             if let (
72                 &ExprKind::Binary(ref kind1, ref lhs1, ref rhs1),
73                 &ExprKind::Binary(ref kind2, ref lhs2, ref rhs2),
74             ) = (&cond[0].node, &cond[1].node)
75             {
76                 if !kind_is_cmp(kind1.node) || !kind_is_cmp(kind2.node) {
77                     return;
78                 }
79
80                 // Check that both sets of operands are equal
81                 let mut spanless_eq = SpanlessEq::new(cx);
82                 if (!spanless_eq.eq_expr(lhs1, lhs2) || !spanless_eq.eq_expr(rhs1, rhs2))
83                     && (!spanless_eq.eq_expr(lhs1, rhs2) || !spanless_eq.eq_expr(rhs1, lhs2))
84                 {
85                     return;
86                 }
87             } else {
88                 // We only care about comparison chains
89                 return;
90             }
91         }
92         span_help_and_lint(
93             cx,
94             COMPARISON_CHAIN,
95             expr.span,
96             "`if` chain can be rewritten with `match`",
97             "Consider rewriting the `if` chain to use `cmp` and `match`.",
98         )
99     }
100 }
101
102 fn kind_is_cmp(kind: BinOpKind) -> bool {
103     match kind {
104         BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq => true,
105         _ => false,
106     }
107 }