1 use std::cmp::Ordering;
3 use rustc_hir::{Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::{self, IntTy, UintTy};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_target::abi::LayoutOf;
10 use crate::consts::{constant, Constant};
12 use clippy_utils::comparisons::Rel;
13 use clippy_utils::diagnostics::span_lint;
14 use clippy_utils::source::snippet;
15 use clippy_utils::{comparisons, sext};
17 declare_clippy_lint! {
18 /// **What it does:** 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?** An expression like `let x : u8 = ...; (x as u32) > 300`
23 /// will mistakenly imply that it is possible for `x` to be outside the range of
26 /// **Known problems:**
27 /// https://github.com/rust-lang/rust-clippy/issues/886
34 pub INVALID_UPCAST_COMPARISONS,
36 "a comparison involving an upcast which is always true or false"
39 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
41 #[derive(Copy, Clone, Debug, Eq)]
48 #[allow(clippy::cast_sign_loss)]
50 fn cmp_s_u(s: i128, u: u128) -> Ordering {
53 } else if u > (i128::MAX as u128) {
61 impl PartialEq for FullInt {
63 fn eq(&self, other: &Self) -> bool {
64 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
68 impl PartialOrd for FullInt {
70 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
71 Some(match (self, other) {
72 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
73 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
74 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
75 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
80 impl Ord for FullInt {
82 fn cmp(&self, other: &Self) -> Ordering {
83 self.partial_cmp(other)
84 .expect("`partial_cmp` for FullInt can never return `None`")
88 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
89 if let ExprKind::Cast(cast_exp, _) = expr.kind {
90 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
91 let cast_ty = cx.typeck_results().expr_ty(expr);
92 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
93 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
96 match pre_cast_ty.kind() {
97 ty::Int(int_ty) => Some(match int_ty {
98 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
99 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
100 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
101 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
102 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
103 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
105 ty::Uint(uint_ty) => Some(match uint_ty {
106 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
107 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
108 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
109 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
110 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
111 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
120 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
121 let val = constant(cx, cx.typeck_results(), expr)?.0;
122 if let Constant::Int(const_int) = val {
123 match *cx.typeck_results().expr_ty(expr).kind() {
124 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
125 ty::Uint(_) => Some(FullInt::U(const_int)),
133 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
134 if let ExprKind::Cast(cast_val, _) = expr.kind {
137 INVALID_UPCAST_COMPARISONS,
140 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
141 snippet(cx, cast_val.span, "the expression"),
142 if always { "true" } else { "false" },
148 fn upcast_comparison_bounds_err<'tcx>(
149 cx: &LateContext<'tcx>,
151 rel: comparisons::Rel,
152 lhs_bounds: Option<(FullInt, FullInt)>,
157 if let Some((lb, ub)) = lhs_bounds {
158 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
159 if rel == Rel::Eq || rel == Rel::Ne {
160 if norm_rhs_val < lb || norm_rhs_val > ub {
161 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
163 } else if match rel {
178 Rel::Eq | Rel::Ne => unreachable!(),
180 err_upcast_comparison(cx, span, lhs, true)
181 } else if match rel {
196 Rel::Eq | Rel::Ne => unreachable!(),
198 err_upcast_comparison(cx, span, lhs, false)
204 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
205 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
206 if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
207 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
208 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
214 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
215 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
217 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
218 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);