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