]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/minmax.rs
Merge pull request #2821 from mati865/rust-2018-migration
[rust.git] / clippy_lints / src / minmax.rs
1 use crate::consts::{constant_simple, Constant};
2 use rustc::lint::*;
3 use rustc::hir::*;
4 use std::cmp::{Ordering, PartialOrd};
5 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
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, _)) = min_max(cx, oe) {
40                 if outer_max == inner_max {
41                     return;
42                 }
43                 match (outer_max, outer_c.partial_cmp(&inner_c)) {
44                     (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
45                     _ => {
46                         span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
47                     },
48                 }
49             }
50         }
51     }
52 }
53
54 #[derive(PartialEq, Eq, Debug)]
55 enum MinMax {
56     Min,
57     Max,
58 }
59
60 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
61     if let ExprCall(ref path, ref args) = expr.node {
62         if let ExprPath(ref qpath) = path.node {
63             opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
64                 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
65                     fetch_const(cx, args, MinMax::Min)
66                 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
67                     fetch_const(cx, args, MinMax::Max)
68                 } else {
69                     None
70                 }
71             })
72         } else {
73             None
74         }
75     } else {
76         None
77     }
78 }
79
80 fn fetch_const<'a>(cx: &LateContext, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
81     if args.len() != 2 {
82         return None;
83     }
84     if let Some(c) = constant_simple(cx, cx.tables, &args[0]) {
85         if constant_simple(cx, cx.tables, &args[1]).is_none() {
86             // otherwise ignore
87             Some((m, c, &args[1]))
88         } else {
89             None
90         }
91     } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
92         Some((m, c, &args[0]))
93     } else {
94         None
95     }
96 }