1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{match_def_path, paths, span_lint};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use std::cmp::Ordering;
9 /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
10 /// used to clamp values, but switched so that the result is constant.
12 /// **Why is this bad?** This is in all probability not the intended outcome. At
13 /// the least it hurts readability of the code.
15 /// **Known problems:** None
19 /// min(0, max(100, x))
21 /// It will always be equal to `0`. Probably the author meant to clamp the value
22 /// between 0 and 100, but has erroneously swapped `min` and `max`.
25 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
28 declare_lint_pass!(MinMaxPass => [MIN_MAX]);
30 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
31 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
32 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
33 if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
34 if outer_max == inner_max {
39 Constant::partial_cmp(cx.tcx, cx.tables.expr_ty(ie), &outer_c, &inner_c),
41 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
47 "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 ExprKind::Call(ref path, ref args) = expr.kind {
64 if let ExprKind::Path(ref qpath) = path.kind {
65 cx.tables.qpath_res(qpath, path.hir_id).opt_def_id().and_then(|def_id| {
66 if match_def_path(cx, def_id, &paths::CMP_MIN) {
67 fetch_const(cx, args, MinMax::Min)
68 } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
69 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, cx.tables, &args[0]) {
87 if constant_simple(cx, cx.tables, &args[1]).is_none() {
89 Some((m, c, &args[1]))
93 } else if let Some(c) = constant_simple(cx, cx.tables, &args[1]) {
94 Some((m, c, &args[0]))