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 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! {
17 /// **What it does:** Checks for comparisons where the relation is always either
18 /// true or false, but where one side has been upcast so that the comparison is
19 /// necessary. Only integer types are checked.
21 /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
22 /// will mistakenly imply that it is possible for `x` to be outside the range of
25 /// **Known problems:**
26 /// https://github.com/rust-lang/rust-clippy/issues/886
33 pub INVALID_UPCAST_COMPARISONS,
35 "a comparison involving an upcast which is always true or false"
38 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
40 #[derive(Copy, Clone, Debug, Eq)]
47 #[allow(clippy::cast_sign_loss)]
49 fn cmp_s_u(s: i128, u: u128) -> Ordering {
52 } else if u > (i128::MAX as u128) {
60 impl PartialEq for FullInt {
62 fn eq(&self, other: &Self) -> bool {
63 self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
67 impl PartialOrd for FullInt {
69 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
70 Some(match (self, other) {
71 (&Self::S(s), &Self::S(o)) => s.cmp(&o),
72 (&Self::U(s), &Self::U(o)) => s.cmp(&o),
73 (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
74 (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
79 impl Ord for FullInt {
81 fn cmp(&self, other: &Self) -> Ordering {
82 self.partial_cmp(other)
83 .expect("`partial_cmp` for FullInt can never return `None`")
87 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
88 if let ExprKind::Cast(cast_exp, _) = expr.kind {
89 let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
90 let cast_ty = cx.typeck_results().expr_ty(expr);
91 // if it's a cast from i32 to u32 wrapping will invalidate all these checks
92 if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
95 match pre_cast_ty.kind() {
96 ty::Int(int_ty) => Some(match int_ty {
97 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
98 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
99 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
100 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
101 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
102 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
104 ty::Uint(uint_ty) => Some(match uint_ty {
105 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
106 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
107 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
108 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
109 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
110 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
119 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
120 let val = constant(cx, cx.typeck_results(), expr)?.0;
121 if let Constant::Int(const_int) = val {
122 match *cx.typeck_results().expr_ty(expr).kind() {
123 ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
124 ty::Uint(_) => Some(FullInt::U(const_int)),
132 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
133 if let ExprKind::Cast(cast_val, _) = expr.kind {
136 INVALID_UPCAST_COMPARISONS,
139 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
140 snippet(cx, cast_val.span, "the expression"),
141 if always { "true" } else { "false" },
147 fn upcast_comparison_bounds_err<'tcx>(
148 cx: &LateContext<'tcx>,
150 rel: comparisons::Rel,
151 lhs_bounds: Option<(FullInt, FullInt)>,
156 if let Some((lb, ub)) = lhs_bounds {
157 if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
158 if rel == Rel::Eq || rel == Rel::Ne {
159 if norm_rhs_val < lb || norm_rhs_val > ub {
160 err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
162 } else if match rel {
177 Rel::Eq | Rel::Ne => unreachable!(),
179 err_upcast_comparison(cx, span, lhs, true);
180 } else if match rel {
195 Rel::Eq | Rel::Ne => unreachable!(),
197 err_upcast_comparison(cx, span, lhs, false);
203 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
204 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
205 if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
206 let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
207 let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
213 let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
214 let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
216 upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
217 upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);