]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/minmax.rs
Rollup merge of #80959 - jhpratt:unsigned_abs-stabilization, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / minmax.rs
1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{match_def_path, match_trait_method, paths, span_lint};
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, 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     /// or
23     /// ```ignore
24     /// x.max(100).min(0)
25     /// ```
26     /// It will always be equal to `0`. Probably the author meant to clamp the value
27     /// between 0 and 100, but has erroneously swapped `min` and `max`.
28     pub MIN_MAX,
29     correctness,
30     "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
31 }
32
33 declare_lint_pass!(MinMaxPass => [MIN_MAX]);
34
35 impl<'tcx> LateLintPass<'tcx> for MinMaxPass {
36     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
37         if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
38             if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
39                 if outer_max == inner_max {
40                     return;
41                 }
42                 match (
43                     outer_max,
44                     Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(ie), &outer_c, &inner_c),
45                 ) {
46                     (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
47                     _ => {
48                         span_lint(
49                             cx,
50                             MIN_MAX,
51                             expr.span,
52                             "this `min`/`max` combination leads to constant result",
53                         );
54                     },
55                 }
56             }
57         }
58     }
59 }
60
61 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
62 enum MinMax {
63     Min,
64     Max,
65 }
66
67 fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
68     match expr.kind {
69         ExprKind::Call(ref path, ref args) => {
70             if let ExprKind::Path(ref qpath) = path.kind {
71                 cx.typeck_results()
72                     .qpath_res(qpath, path.hir_id)
73                     .opt_def_id()
74                     .and_then(|def_id| {
75                         if match_def_path(cx, def_id, &paths::CMP_MIN) {
76                             fetch_const(cx, args, MinMax::Min)
77                         } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
78                             fetch_const(cx, args, MinMax::Max)
79                         } else {
80                             None
81                         }
82                     })
83             } else {
84                 None
85             }
86         },
87         ExprKind::MethodCall(ref path, _, ref args, _) => {
88             if_chain! {
89                 if let [obj, _] = args;
90                 if cx.typeck_results().expr_ty(obj).is_floating_point() || match_trait_method(cx, expr, &paths::ORD);
91                 then {
92                     if path.ident.name == sym!(max) {
93                         fetch_const(cx, args, MinMax::Max)
94                     } else if path.ident.name == sym!(min) {
95                         fetch_const(cx, args, MinMax::Min)
96                     } else {
97                         None
98                     }
99                 } else {
100                     None
101                 }
102             }
103         },
104         _ => None,
105     }
106 }
107
108 fn fetch_const<'a>(cx: &LateContext<'_>, args: &'a [Expr<'a>], m: MinMax) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
109     if args.len() != 2 {
110         return None;
111     }
112     constant_simple(cx, cx.typeck_results(), &args[0]).map_or_else(
113         || constant_simple(cx, cx.typeck_results(), &args[1]).map(|c| (m, c, &args[0])),
114         |c| {
115             if constant_simple(cx, cx.typeck_results(), &args[1]).is_none() {
116                 // otherwise ignore
117                 Some((m, c, &args[1]))
118             } else {
119                 None
120             }
121         },
122     )
123 }