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