1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint, lint_array};
6 use std::cmp::Ordering;
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`.
22 declare_clippy_lint! {
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<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
38 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
39 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
40 if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
41 if outer_max == inner_max {
46 Constant::partial_cmp(cx.tcx, &cx.tables.expr_ty(ie).sty, &outer_c, &inner_c),
48 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
54 "this min/max combination leads to constant result",
63 #[derive(PartialEq, Eq, Debug)]
69 fn min_max<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
70 if let ExprKind::Call(ref path, ref args) = expr.node {
71 if let ExprKind::Path(ref qpath) = path.node {
72 opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
73 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
74 fetch_const(cx, args, MinMax::Min)
75 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
76 fetch_const(cx, args, MinMax::Max)
89 fn fetch_const<'a>(cx: &LateContext<'_, '_>, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
93 if let Some(c) = constant_simple(cx, cx.tables, &args[0]) {
94 if constant_simple(cx, cx.tables, &args[1]).is_none() {
96 Some((m, c, &args[1]))
100 } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
101 Some((m, c, &args[0]))