From 53c0ae01698a9b53d56d7186c55a617a75668187 Mon Sep 17 00:00:00 2001 From: kimsnj Date: Fri, 12 Jan 2018 18:24:24 +0100 Subject: [PATCH] Fix #1159: avoid comparing fixed and target sized types in lint --- clippy_lints/src/types.rs | 19 +++++++++++++++++++ tests/ui/absurd-extreme-comparisons.rs | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 7c536140f..c0c72408c 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -1106,6 +1106,20 @@ enum AbsurdComparisonResult { } +fn is_cast_between_fixed_and_target<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr +) -> bool { + + if let ExprCast(ref cast_exp, _) = expr.node { + let precast_ty = cx.tables.expr_ty(cast_exp); + let cast_ty = cx.tables.expr_ty(expr); + + return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty) + } + + return false; +} fn detect_absurd_comparison<'a, 'tcx>( cx: &LateContext<'a, 'tcx>, @@ -1123,6 +1137,11 @@ fn detect_absurd_comparison<'a, 'tcx>( return None; } + // comparisons between fix sized types and target sized types are considered unanalyzable + if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) { + return None; + } + let normalized = normalize_comparison(op, lhs, rhs); let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized { val diff --git a/tests/ui/absurd-extreme-comparisons.rs b/tests/ui/absurd-extreme-comparisons.rs index 1f88d94bd..8c036e6c0 100644 --- a/tests/ui/absurd-extreme-comparisons.rs +++ b/tests/ui/absurd-extreme-comparisons.rs @@ -50,3 +50,8 @@ impl PartialOrd for U { pub fn foo(val: U) -> bool { val > std::u32::MAX } + +pub fn bar(len: u64) -> bool { + // This is OK as we are casting from target sized to fixed size + len >= std::usize::MAX as u64 +}