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