]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/minmax.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / minmax.rs
1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::span_lint;
3 use clippy_utils::{match_trait_method, paths};
4 use if_chain::if_chain;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::sym;
9 use std::cmp::Ordering;
10
11 declare_clippy_lint! {
12 /// ### What it does
13 /// Checks for expressions where `std::cmp::min` and `max` are
14 /// used to clamp values, but switched so that the result is constant.
15 ///
16 /// ### Why is this bad?
17 /// This is in all probability not the intended outcome. At
18 /// the least it hurts readability of the code.
19 ///
20 /// ### Example
21 /// ```rust,ignore
22 /// min(0, max(100, x))
23 ///
24 /// // or
25 ///
26 /// x.max(100).min(0)
27 /// ```
28 /// It will always be equal to `0`. Probably the author meant to clamp the value
29 /// between 0 and 100, but has erroneously swapped `min` and `max`.
30 #[clippy::version = "pre 1.29.0"]
31 pub MIN_MAX,
32 correctness,
33 "`min(_, max(_, _))` (or vice versa) with bounds clamping the result to a constant"
34 }
35
36 declare_lint_pass!(MinMaxPass => [MIN_MAX]);
37
38 impl<'tcx> LateLintPass<'tcx> for MinMaxPass {
39 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
40 if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
41 if let Some((inner_max, inner_c, ie)) = min_max(cx, oe) {
42 if outer_max == inner_max {
43 return;
44 }
45 match (
46 outer_max,
47 Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(ie), &outer_c, &inner_c),
48 ) {
49 (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
50 _ => {
51 span_lint(
52 cx,
53 MIN_MAX,
54 expr.span,
55 "this `min`/`max` combination leads to constant result",
56 );
57 },
58 }
59 }
60 }
61 }
62 }
63
64 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
65 enum MinMax {
66 Min,
67 Max,
68 }
69
70 fn min_max<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
71 match expr.kind {
72 ExprKind::Call(path, args) => {
73 if let ExprKind::Path(ref qpath) = path.kind {
74 cx.typeck_results()
75 .qpath_res(qpath, path.hir_id)
76 .opt_def_id()
77 .and_then(|def_id| match cx.tcx.get_diagnostic_name(def_id) {
78 Some(sym::cmp_min) => fetch_const(cx, args, MinMax::Min),
79 Some(sym::cmp_max) => fetch_const(cx, args, MinMax::Max),
80 _ => None,
81 })
82 } else {
83 None
84 }
85 },
86 ExprKind::MethodCall(path, args, _) => {
87 if_chain! {
88 if let [obj, _] = args;
89 if cx.typeck_results().expr_ty(obj).is_floating_point() || match_trait_method(cx, expr, &paths::ORD);
90 then {
91 if path.ident.name == sym!(max) {
92 fetch_const(cx, args, MinMax::Max)
93 } else if path.ident.name == sym!(min) {
94 fetch_const(cx, args, MinMax::Min)
95 } else {
96 None
97 }
98 } else {
99 None
100 }
101 }
102 },
103 _ => None,
104 }
105 }
106
107 fn fetch_const<'a>(cx: &LateContext<'_>, args: &'a [Expr<'a>], m: MinMax) -> Option<(MinMax, Constant, &'a Expr<'a>)> {
108 if args.len() != 2 {
109 return None;
110 }
111 constant_simple(cx, cx.typeck_results(), &args[0]).map_or_else(
112 || constant_simple(cx, cx.typeck_results(), &args[1]).map(|c| (m, c, &args[0])),
113 |c| {
114 if constant_simple(cx, cx.typeck_results(), &args[1]).is_none() {
115 // otherwise ignore
116 Some((m, c, &args[1]))
117 } else {
118 None
119 }
120 },
121 )
122 }