2 use rustc_front::hir::*;
4 use std::cmp::PartialOrd;
5 use std::cmp::Ordering::*;
7 use consts::{Constant, constant_simple};
8 use utils::{match_def_path, span_lint};
9 use self::MinMax::{Min, Max};
11 /// **What it does:** This lint checks for expressions where `std::cmp::min` and `max` are used to clamp values, but switched so that the result is constant.
13 /// **Why is this bad?** This is in all probability not the intended outcome. At the least it hurts readability of the code.
15 /// **Known problems:** None
17 /// **Example:** `min(0, max(100, x))` will always be equal to `0`. Probably the author meant to clamp the value between 0 and 100, but has erroneously swapped `min` and `max`.
18 declare_lint!(pub MIN_MAX, Warn,
19 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result \
22 #[allow(missing_copy_implementations)]
23 pub struct MinMaxPass;
25 impl LintPass for MinMaxPass {
26 fn get_lints(&self) -> LintArray {
31 impl LateLintPass for MinMaxPass {
32 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
33 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
34 if let Some((inner_max, inner_c, _)) = min_max(cx, oe) {
35 if outer_max == inner_max { return; }
36 match (outer_max, outer_c.partial_cmp(&inner_c)) {
37 (_, None) | (Max, Some(Less)) | (Min, Some(Greater)) => (),
39 span_lint(cx, MIN_MAX, expr.span,
40 "this min/max combination leads to constant result")
48 #[derive(PartialEq, Eq, Debug)]
54 fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
55 if let ExprCall(ref path, ref args) = expr.node {
56 if let ExprPath(None, _) = path.node {
57 let def_id = cx.tcx.def_map.borrow()[&path.id].def_id();
59 if match_def_path(cx, def_id, &["core", "cmp", "min"]) {
60 fetch_const(args, Min)
62 if match_def_path(cx, def_id, &["core", "cmp", "max"]) {
63 fetch_const(args, Max)
72 fn fetch_const(args: &[P<Expr>], m: MinMax) ->
73 Option<(MinMax, Constant, &Expr)> {
74 if args.len() != 2 { return None }
75 if let Some(c) = constant_simple(&args[0]) {
76 if let None = constant_simple(&args[1]) { // otherwise ignore
77 Some((m, c, &args[1]))
80 if let Some(c) = constant_simple(&args[1]) {
81 Some((m, c, &args[0]))