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:** This lint checks for expressions where `std::cmp::min` and `max` are used to
9 /// 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 the least it hurts
12 /// readability of the code.
14 /// **Known problems:** None
16 /// **Example:** `min(0, max(100, x))` will always be equal to `0`. Probably the author meant to
17 /// clamp the value between 0 and 100, but has erroneously swapped `min` and `max`.
20 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
23 #[allow(missing_copy_implementations)]
24 pub struct MinMaxPass;
26 impl LintPass for MinMaxPass {
27 fn get_lints(&self) -> LintArray {
32 impl LateLintPass for MinMaxPass {
33 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
34 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
35 if let Some((inner_max, inner_c, _)) = min_max(cx, oe) {
36 if outer_max == inner_max {
39 match (outer_max, outer_c.partial_cmp(&inner_c)) {
41 (MinMax::Max, Some(Ordering::Less)) |
42 (MinMax::Min, Some(Ordering::Greater)) => (),
44 span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
52 #[derive(PartialEq, Eq, Debug)]
58 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
59 if let ExprCall(ref path, ref args) = expr.node {
60 if let ExprPath(None, _) = path.node {
61 let def_id = cx.tcx.expect_def(path.id).def_id();
63 if match_def_path(cx, def_id, &paths::CMP_MIN) {
64 fetch_const(args, MinMax::Min)
65 } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
66 fetch_const(args, MinMax::Max)
78 fn fetch_const(args: &[P<Expr>], m: MinMax) -> Option<(MinMax, Constant, &Expr)> {
82 if let Some(c) = constant_simple(&args[0]) {
83 if let None = constant_simple(&args[1]) {
85 Some((m, c, &args[1]))
89 } else if let Some(c) = constant_simple(&args[1]) {
90 Some((m, c, &args[0]))