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