Skip to content

Commit cc9008b

Browse files
authored
Merge pull request #2347 from kimsnj/extrem_comp
Fix #1159: avoid comparing fixed and target sized types in lint
2 parents b863a00 + 53c0ae0 commit cc9008b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

clippy_lints/src/types.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,20 @@ enum AbsurdComparisonResult {
11061106
}
11071107

11081108

1109+
fn is_cast_between_fixed_and_target<'a, 'tcx>(
1110+
cx: &LateContext<'a, 'tcx>,
1111+
expr: &'tcx Expr
1112+
) -> bool {
1113+
1114+
if let ExprCast(ref cast_exp, _) = expr.node {
1115+
let precast_ty = cx.tables.expr_ty(cast_exp);
1116+
let cast_ty = cx.tables.expr_ty(expr);
1117+
1118+
return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty)
1119+
}
1120+
1121+
return false;
1122+
}
11091123

11101124
fn detect_absurd_comparison<'a, 'tcx>(
11111125
cx: &LateContext<'a, 'tcx>,
@@ -1123,6 +1137,11 @@ fn detect_absurd_comparison<'a, 'tcx>(
11231137
return None;
11241138
}
11251139

1140+
// comparisons between fix sized types and target sized types are considered unanalyzable
1141+
if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1142+
return None;
1143+
}
1144+
11261145
let normalized = normalize_comparison(op, lhs, rhs);
11271146
let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
11281147
val

tests/ui/absurd-extreme-comparisons.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,8 @@ impl PartialOrd<u32> for U {
5050
pub fn foo(val: U) -> bool {
5151
val > std::u32::MAX
5252
}
53+
54+
pub fn bar(len: u64) -> bool {
55+
// This is OK as we are casting from target sized to fixed size
56+
len >= std::usize::MAX as u64
57+
}

0 commit comments

Comments
 (0)