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