]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/minmax.rs
Rustup
[rust.git] / clippy_lints / src / minmax.rs
1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
3 use rustc::hir::*;
4 use rustc::lint::*;
5 use std::cmp::Ordering;
6
7 /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
8 /// used to clamp values, but switched so that the result is constant.
9 ///
10 /// **Why is this bad?** This is in all probability not the intended outcome. At
11 /// the least it hurts readability of the code.
12 ///
13 /// **Known problems:** None
14 ///
15 /// **Example:**
16 /// ```rust
17 /// min(0, max(100, x))
18 /// ```
19 /// It will always be equal to `0`. Probably the author meant to clamp the value
20 /// between 0 and 100, but has erroneously swapped `min` and `max`.
21 declare_clippy_lint! {
22     pub MIN_MAX,
23     correctness,
24     "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
25 }
26
27 #[allow(missing_copy_implementations)]
28 pub struct MinMaxPass;
29
30 impl LintPass for MinMaxPass {
31     fn get_lints(&self) -> LintArray {
32         lint_array!(MIN_MAX)
33     }
34 }
35
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
37     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
38         if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
39             if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
40                 if outer_max == inner_max {
41                     return;
42                 }
43                 match (
44                     outer_max,
45                     Constant::partial_cmp(cx.tcx, &cx.tables.expr_ty(ie).sty, &outer_c, &inner_c),
46                 ) {
47                     (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
48                     _ => {
49                         span_lint(
50                             cx,
51                             MIN_MAX,
52                             expr.span,
53                             "this min/max combination leads to constant result",
54                         );
55                     },
56                 }
57             }
58         }
59     }
60 }
61
62 #[derive(PartialEq, Eq, Debug)]
63 enum MinMax {
64     Min,
65     Max,
66 }
67
68 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
69     if let ExprCall(ref path, ref args) = expr.node {
70         if let ExprPath(ref qpath) = path.node {
71             opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
72                 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
73                     fetch_const(cx, args, MinMax::Min)
74                 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
75                     fetch_const(cx, args, MinMax::Max)
76                 } else {
77                     None
78                 }
79             })
80         } else {
81             None
82         }
83     } else {
84         None
85     }
86 }
87
88 fn fetch_const<'a>(cx: &LateContext, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
89     if args.len() != 2 {
90         return None;
91     }
92     if let Some(c) = constant_simple(cx, cx.tables, &args[0]) {
93         if constant_simple(cx, cx.tables, &args[1]).is_none() {
94             // otherwise ignore
95             Some((m, c, &args[1]))
96         } else {
97             None
98         }
99     } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
100         Some((m, c, &args[0]))
101     } else {
102         None
103     }
104 }