1 use consts::{Constant, constant_simple};
4 use std::cmp::{PartialOrd, Ordering};
6 use utils::{match_def_path, paths, span_lint};
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.
11 /// **Why is this bad?** This is in all probability not the intended outcome. At
12 /// the least it hurts readability of the code.
14 /// **Known problems:** None
18 /// min(0, max(100, x))
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`.
25 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
28 #[allow(missing_copy_implementations)]
29 pub struct MinMaxPass;
31 impl LintPass for MinMaxPass {
32 fn get_lints(&self) -> LintArray {
37 impl LateLintPass for MinMaxPass {
38 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
39 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
40 if let Some((inner_max, inner_c, _)) = min_max(cx, oe) {
41 if outer_max == inner_max {
44 match (outer_max, outer_c.partial_cmp(&inner_c)) {
46 (MinMax::Max, Some(Ordering::Less)) |
47 (MinMax::Min, Some(Ordering::Greater)) => (),
49 span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
57 #[derive(PartialEq, Eq, Debug)]
63 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
64 if let ExprCall(ref path, ref args) = expr.node {
65 if let ExprPath(None, _) = path.node {
66 let def_id = cx.tcx.expect_def(path.id).def_id();
68 if match_def_path(cx, def_id, &paths::CMP_MIN) {
69 fetch_const(args, MinMax::Min)
70 } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
71 fetch_const(args, MinMax::Max)
83 fn fetch_const(args: &[P<Expr>], m: MinMax) -> Option<(MinMax, Constant, &Expr)> {
87 if let Some(c) = constant_simple(&args[0]) {
88 if constant_simple(&args[1]).is_none() {
90 Some((m, c, &args[1]))
94 } else if let Some(c) = constant_simple(&args[1]) {
95 Some((m, c, &args[0]))