1 use consts::{constant_simple, Constant};
4 use std::cmp::{Ordering, PartialOrd};
5 use utils::{match_def_path, opt_def_id, paths, span_lint};
7 /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
8 /// used to clamp values, but switched so that the result is constant.
10 /// **Why is this bad?** This is in all probability not the intended outcome. At
11 /// the least it hurts readability of the code.
13 /// **Known problems:** None
17 /// min(0, max(100, x))
19 /// It will always be equal to `0`. Probably the author meant to clamp the value
20 /// between 0 and 100, but has erroneously swapped `min` and `max`.
21 declare_clippy_lint! {
24 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
27 #[allow(missing_copy_implementations)]
28 pub struct MinMaxPass;
30 impl LintPass for MinMaxPass {
31 fn get_lints(&self) -> LintArray {
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
37 fn check_expr(&mut self, cx: &LateContext<'a, '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, _)) = min_max(cx, oe) {
40 if outer_max == inner_max {
43 match (outer_max, outer_c.partial_cmp(&inner_c)) {
44 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
46 span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
54 #[derive(PartialEq, Eq, Debug)]
60 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
61 if let ExprCall(ref path, ref args) = expr.node {
62 if let ExprPath(ref qpath) = path.node {
63 opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
64 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
65 fetch_const(cx, args, MinMax::Min)
66 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
67 fetch_const(cx, args, MinMax::Max)
80 fn fetch_const<'a>(cx: &LateContext, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
84 if let Some(c) = constant_simple(cx, &args[0]) {
85 if constant_simple(cx, &args[1]).is_none() {
87 Some((m, c, &args[1]))
91 } else if let Some(c) = constant_simple(cx, &args[1]) {
92 Some((m, c, &args[0]))