]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/minmax.rs
Rollup merge of #73771 - alexcrichton:ignore-unstable, r=estebank,GuillaumeGomez
[rust.git] / src / tools / clippy / 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::{Expr, ExprKind};
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<'tcx> LateLintPass<'tcx> for MinMaxPass {
31     fn check_expr(&mut self, cx: &LateContext<'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, Clone, Copy)]
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()
66                 .qpath_res(qpath, path.hir_id)
67                 .opt_def_id()
68                 .and_then(|def_id| {
69                     if match_def_path(cx, def_id, &paths::CMP_MIN) {
70                         fetch_const(cx, args, MinMax::Min)
71                     } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
72                         fetch_const(cx, args, MinMax::Max)
73                     } else {
74                         None
75                     }
76                 })
77         } else {
78             None
79         }
80     } else {
81         None
82     }
83 }
84
85 fn fetch_const<'a>(cx: &LateContext<'_>, args: &'a [Expr<'a>], m: MinMax) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
86     if args.len() != 2 {
87         return None;
88     }
89     constant_simple(cx, cx.tables(), &args[0]).map_or_else(
90         || constant_simple(cx, cx.tables(), &args[1]).map(|c| (m, c, &args[0])),
91         |c| {
92             if constant_simple(cx, cx.tables(), &args[1]).is_none() {
93                 // otherwise ignore
94                 Some((m, c, &args[1]))
95             } else {
96                 None
97             }
98         },
99     )
100 }