]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/operators/absurd_extreme_comparisons.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / clippy / clippy_lints / src / operators / absurd_extreme_comparisons.rs
1 use rustc_hir::{BinOpKind, Expr, ExprKind};
2 use rustc_lint::LateContext;
3 use rustc_middle::ty;
4
5 use clippy_utils::comparisons::{normalize_comparison, Rel};
6 use clippy_utils::consts::{constant, Constant};
7 use clippy_utils::diagnostics::span_lint_and_help;
8 use clippy_utils::source::snippet;
9 use clippy_utils::ty::is_isize_or_usize;
10 use clippy_utils::{clip, int_bits, unsext};
11
12 use super::ABSURD_EXTREME_COMPARISONS;
13
14 pub(super) fn check<'tcx>(
15     cx: &LateContext<'tcx>,
16     expr: &'tcx Expr<'_>,
17     op: BinOpKind,
18     lhs: &'tcx Expr<'_>,
19     rhs: &'tcx Expr<'_>,
20 ) {
21     if let Some((culprit, result)) = detect_absurd_comparison(cx, op, lhs, rhs) {
22         let msg = "this comparison involving the minimum or maximum element for this \
23                            type contains a case that is always true or always false";
24
25         let conclusion = match result {
26             AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(),
27             AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(),
28             AbsurdComparisonResult::InequalityImpossible => format!(
29                 "the case where the two sides are not equal never occurs, consider using `{} == {}` \
30                          instead",
31                 snippet(cx, lhs.span, "lhs"),
32                 snippet(cx, rhs.span, "rhs")
33             ),
34         };
35
36         let help = format!(
37             "because `{}` is the {} value for this type, {}",
38             snippet(cx, culprit.expr.span, "x"),
39             match culprit.which {
40                 ExtremeType::Minimum => "minimum",
41                 ExtremeType::Maximum => "maximum",
42             },
43             conclusion
44         );
45
46         span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
47     }
48 }
49
50 enum ExtremeType {
51     Minimum,
52     Maximum,
53 }
54
55 struct ExtremeExpr<'a> {
56     which: ExtremeType,
57     expr: &'a Expr<'a>,
58 }
59
60 enum AbsurdComparisonResult {
61     AlwaysFalse,
62     AlwaysTrue,
63     InequalityImpossible,
64 }
65
66 fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
67     if let ExprKind::Cast(cast_exp, _) = expr.kind {
68         let precast_ty = cx.typeck_results().expr_ty(cast_exp);
69         let cast_ty = cx.typeck_results().expr_ty(expr);
70
71         return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
72     }
73
74     false
75 }
76
77 fn detect_absurd_comparison<'tcx>(
78     cx: &LateContext<'tcx>,
79     op: BinOpKind,
80     lhs: &'tcx Expr<'_>,
81     rhs: &'tcx Expr<'_>,
82 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
83     use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
84     use ExtremeType::{Maximum, Minimum};
85     // absurd comparison only makes sense on primitive types
86     // primitive types don't implement comparison operators with each other
87     if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) {
88         return None;
89     }
90
91     // comparisons between fix sized types and target sized types are considered unanalyzable
92     if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
93         return None;
94     }
95
96     let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
97
98     let lx = detect_extreme_expr(cx, normalized_lhs);
99     let rx = detect_extreme_expr(cx, normalized_rhs);
100
101     Some(match rel {
102         Rel::Lt => {
103             match (lx, rx) {
104                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
105                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
106                 _ => return None,
107             }
108         },
109         Rel::Le => {
110             match (lx, rx) {
111                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
112                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
113                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
114                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
115                 _ => return None,
116             }
117         },
118         Rel::Ne | Rel::Eq => return None,
119     })
120 }
121
122 fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
123     let ty = cx.typeck_results().expr_ty(expr);
124
125     let cv = constant(cx, cx.typeck_results(), expr)?.0;
126
127     let which = match (ty.kind(), cv) {
128         (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum,
129         (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
130             ExtremeType::Minimum
131         },
132
133         (&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum,
134         (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
135             ExtremeType::Maximum
136         },
137         (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum,
138
139         _ => return None,
140     };
141     Some(ExtremeExpr { which, expr })
142 }