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.
11 use crate::consts::{constant_simple, Constant};
12 use crate::utils::{match_def_path, opt_def_id, paths, span_lint};
13 use crate::rustc::hir::*;
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use std::cmp::Ordering;
18 /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
19 /// used to clamp values, but switched so that the result is constant.
21 /// **Why is this bad?** This is in all probability not the intended outcome. At
22 /// the least it hurts readability of the code.
24 /// **Known problems:** None
28 /// min(0, max(100, x))
30 /// It will always be equal to `0`. Probably the author meant to clamp the value
31 /// between 0 and 100, but has erroneously swapped `min` and `max`.
32 declare_clippy_lint! {
35 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
38 #[allow(missing_copy_implementations)]
39 pub struct MinMaxPass;
41 impl LintPass for MinMaxPass {
42 fn get_lints(&self) -> LintArray {
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
48 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
50 if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
51 if outer_max == inner_max {
56 Constant::partial_cmp(cx.tcx, &cx.tables.expr_ty(ie).sty, &outer_c, &inner_c),
58 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
64 "this min/max combination leads to constant result",
73 #[derive(PartialEq, Eq, Debug)]
79 fn min_max<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
80 if let ExprKind::Call(ref path, ref args) = expr.node {
81 if let ExprKind::Path(ref qpath) = path.node {
82 opt_def_id(cx.tables.qpath_def(qpath, path.hir_id)).and_then(|def_id| {
83 if match_def_path(cx.tcx, def_id, &paths::CMP_MIN) {
84 fetch_const(cx, args, MinMax::Min)
85 } else if match_def_path(cx.tcx, def_id, &paths::CMP_MAX) {
86 fetch_const(cx, args, MinMax::Max)
99 fn fetch_const<'a>(cx: &LateContext<'_, '_>, args: &'a [Expr], m: MinMax) -> Option<(MinMax, Constant, &'a Expr)> {
103 if let Some(c) = constant_simple(cx, cx.tables, &args[0]) {
104 if constant_simple(cx, cx.tables, &args[1]).is_none() {
106 Some((m, c, &args[1]))
110 } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
111 Some((m, c, &args[0]))