1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{match_def_path, paths, span_lint};
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{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<'tcx> LateLintPass<'tcx> for MinMaxPass {
31 fn check_expr(&mut self, cx: &LateContext<'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, Clone, Copy)]
62 fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
63 if let ExprKind::Call(ref path, ref args) = expr.kind {
64 if let ExprKind::Path(ref qpath) = path.kind {
66 .qpath_res(qpath, path.hir_id)
69 if match_def_path(cx, def_id, &paths::CMP_MIN) {
70 fetch_const(cx, args, MinMax::Min)
71 } else if match_def_path(cx, def_id, &paths::CMP_MAX) {
72 fetch_const(cx, args, MinMax::Max)
85 fn fetch_const<'a>(cx: &LateContext<'_>, args: &'a [Expr<'a>], m: MinMax) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
89 constant_simple(cx, cx.tables(), &args[0]).map_or_else(
90 || constant_simple(cx, cx.tables(), &args[1]).map(|c| (m, c, &args[0])),
92 if constant_simple(cx, cx.tables(), &args[1]).is_none() {
94 Some((m, c, &args[1]))