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