1 use std::cmp::Ordering;
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::layout::LayoutOf;
6 use rustc_middle::ty::{self, IntTy, UintTy};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use clippy_utils::comparisons::Rel;
11 use clippy_utils::consts::{constant, Constant};
12 use clippy_utils::diagnostics::span_lint;
13 use clippy_utils::source::snippet;
14 use clippy_utils::{comparisons, sext};
16 declare_clippy_lint! {
18 /// Checks for comparisons where the relation is always either
19 /// true or false, but where one side has been upcast so that the comparison is
20 /// necessary. Only integer types are checked.
22 /// ### Why is this bad?
23 /// An expression like `let x : u8 = ...; (x as u32) > 300`
24 /// will mistakenly imply that it is possible for `x` to be outside the range of
27 /// ### Known problems
28 /// https://github.com/rust-lang/rust-clippy/issues/886
35 pub INVALID_UPCAST_COMPARISONS,
37 "a comparison involving an upcast which is always true or false"
40 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
42 #[derive(Copy, Clone, Debug, Eq)]
49 #[allow(clippy::cast_sign_loss)]
51 fn cmp_s_u(s: i128, u: u128) -> Ordering {
54 } else if u > (i128::MAX as u128) {
62 impl PartialEq for FullInt {
64 fn eq(&self, other: &Self) -> bool {
65 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
69 impl PartialOrd for FullInt {
71 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
72 Some(match (self, other) {
73 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
74 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
75 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
76 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
81 impl Ord for FullInt {
83 fn cmp(&self, other: &Self) -> Ordering {
84 self.partial_cmp(other)
85 .expect("`partial_cmp` for FullInt can never return `None`")
89 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
90 if let ExprKind::Cast(cast_exp, _) = expr.kind {
91 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
92 let cast_ty = cx.typeck_results().expr_ty(expr);
93 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
94 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
97 match pre_cast_ty.kind() {
98 ty::Int(int_ty) => Some(match int_ty {
99 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
100 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
101 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
102 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
103 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
104 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
106 ty::Uint(uint_ty) => Some(match uint_ty {
107 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
108 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
109 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
110 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
111 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
112 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
121 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
122 let val = constant(cx, cx.typeck_results(), expr)?.0;
123 if let Constant::Int(const_int) = val {
124 match *cx.typeck_results().expr_ty(expr).kind() {
125 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
126 ty::Uint(_) => Some(FullInt::U(const_int)),
134 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
135 if let ExprKind::Cast(cast_val, _) = expr.kind {
138 INVALID_UPCAST_COMPARISONS,
141 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
142 snippet(cx, cast_val.span, "the expression"),
143 if always { "true" } else { "false" },
149 fn upcast_comparison_bounds_err<'tcx>(
150 cx: &LateContext<'tcx>,
152 rel: comparisons::Rel,
153 lhs_bounds: Option<(FullInt, FullInt)>,
158 if let Some((lb, ub)) = lhs_bounds {
159 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
160 if rel == Rel::Eq || rel == Rel::Ne {
161 if norm_rhs_val < lb || norm_rhs_val > ub {
162 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
164 } else if match rel {
179 Rel::Eq | Rel::Ne => unreachable!(),
181 err_upcast_comparison(cx, span, lhs, true);
182 } else if match rel {
197 Rel::Eq | Rel::Ne => unreachable!(),
199 err_upcast_comparison(cx, span, lhs, false);
205 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
206 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
207 if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
208 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
209 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
215 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
216 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
218 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
219 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);