1 use consts::{Constant, constant_simple};
4 use std::cmp::{PartialOrd, Ordering};
5 use utils::{match_def_path, 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`.
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)) {
45 (MinMax::Max, Some(Ordering::Less)) |
46 (MinMax::Min, Some(Ordering::Greater)) => (),
48 span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
56 #[derive(PartialEq, Eq, Debug)]
62 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
63 if let ExprCall(ref path, ref args) = expr.node {
64 if let ExprPath(ref qpath) = path.node {
65 let def_id = cx.tables.qpath_def(qpath, path.id).def_id();
67 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
68 fetch_const(cx, args, MinMax::Min)
69 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
70 fetch_const(cx, args, MinMax::Max)
82 fn fetch_const<'a>(cx: &LateContext, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
86 if let Some(c) = constant_simple(cx, &args[0]) {
87 if constant_simple(cx, &args[1]).is_none() {
89 Some((m, c, &args[1]))
93 } else if let Some(c) = constant_simple(cx, &args[1]) {
94 Some((m, c, &args[0]))