1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::consts::{constant_simple, Constant};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
15 use std::cmp::Ordering;
17 /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
18 /// used to clamp values, but switched so that the result is constant.
20 /// **Why is this bad?** This is in all probability not the intended outcome. At
21 /// the least it hurts readability of the code.
23 /// **Known problems:** None
27 /// min(0, max(100, x))
29 /// It will always be equal to `0`. Probably the author meant to clamp the value
30 /// between 0 and 100, but has erroneously swapped `min` and `max`.
31 declare_clippy_lint! {
34 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
37 pub struct MinMaxPass;
39 impl LintPass for MinMaxPass {
40 fn get_lints(&self) -> LintArray {
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
46 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
47 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
48 if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
49 if outer_max == inner_max {
54 Constant::partial_cmp(cx.tcx, cx.tables.expr_ty(ie), &outer_c, &inner_c),
56 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
62 "this min/max combination leads to constant result",
71 #[derive(PartialEq, Eq, Debug)]
77 fn min_max<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
78 if let ExprKind::Call(ref path, ref args) = expr.node {
79 if let ExprKind::Path(ref qpath) = path.node {
80 opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
81 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
82 fetch_const(cx, args, MinMax::Min)
83 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
84 fetch_const(cx, args, MinMax::Max)
97 fn fetch_const<'a>(cx: &LateContext<'_, '_>, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
101 if let Some(c) = constant_simple(cx, cx.tables, &args[0]) {
102 if constant_simple(cx, cx.tables, &args[1]).is_none() {
104 Some((m, c, &args[1]))
108 } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
109 Some((m, c, &args[0]))