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