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