Skip to content

Commit f231b59

Browse files
committed
Move invalid_upcast_comparisons to its own module
1 parent caa49c8 commit f231b59

File tree

3 files changed

+227
-216
lines changed

3 files changed

+227
-216
lines changed
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
use std::cmp::Ordering;
2+
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};
7+
use rustc_span::Span;
8+
use rustc_target::abi::LayoutOf;
9+
10+
use crate::consts::{constant, Constant};
11+
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};
16+
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.
21+
///
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
24+
/// `u8`.
25+
///
26+
/// **Known problems:**
27+
/// https://github.com/rust-lang/rust-clippy/issues/886
28+
///
29+
/// **Example:**
30+
/// ```rust
31+
/// let x: u8 = 1;
32+
/// (x as u32) > 300;
33+
/// ```
34+
pub INVALID_UPCAST_COMPARISONS,
35+
pedantic,
36+
"a comparison involving an upcast which is always true or false"
37+
}
38+
39+
declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
40+
41+
#[derive(Copy, Clone, Debug, Eq)]
42+
enum FullInt {
43+
S(i128),
44+
U(u128),
45+
}
46+
47+
impl FullInt {
48+
#[allow(clippy::cast_sign_loss)]
49+
#[must_use]
50+
fn cmp_s_u(s: i128, u: u128) -> Ordering {
51+
if s < 0 {
52+
Ordering::Less
53+
} else if u > (i128::MAX as u128) {
54+
Ordering::Greater
55+
} else {
56+
(s as u128).cmp(&u)
57+
}
58+
}
59+
}
60+
61+
impl PartialEq for FullInt {
62+
#[must_use]
63+
fn eq(&self, other: &Self) -> bool {
64+
self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
65+
}
66+
}
67+
68+
impl PartialOrd for FullInt {
69+
#[must_use]
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(),
76+
})
77+
}
78+
}
79+
80+
impl Ord for FullInt {
81+
#[must_use]
82+
fn cmp(&self, other: &Self) -> Ordering {
83+
self.partial_cmp(other)
84+
.expect("`partial_cmp` for FullInt can never return `None`")
85+
}
86+
}
87+
88+
fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
89+
if let ExprKind::Cast(ref 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) {
94+
return None;
95+
}
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)),
104+
}),
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)),
112+
}),
113+
_ => None,
114+
}
115+
} else {
116+
None
117+
}
118+
}
119+
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)),
126+
_ => None,
127+
}
128+
} else {
129+
None
130+
}
131+
}
132+
133+
fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
134+
if let ExprKind::Cast(ref cast_val, _) = expr.kind {
135+
span_lint(
136+
cx,
137+
INVALID_UPCAST_COMPARISONS,
138+
span,
139+
&format!(
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" },
143+
),
144+
);
145+
}
146+
}
147+
148+
fn upcast_comparison_bounds_err<'tcx>(
149+
cx: &LateContext<'tcx>,
150+
span: Span,
151+
rel: comparisons::Rel,
152+
lhs_bounds: Option<(FullInt, FullInt)>,
153+
lhs: &'tcx Expr<'_>,
154+
rhs: &'tcx Expr<'_>,
155+
invert: bool,
156+
) {
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);
162+
}
163+
} else if match rel {
164+
Rel::Lt => {
165+
if invert {
166+
norm_rhs_val < lb
167+
} else {
168+
ub < norm_rhs_val
169+
}
170+
},
171+
Rel::Le => {
172+
if invert {
173+
norm_rhs_val <= lb
174+
} else {
175+
ub <= norm_rhs_val
176+
}
177+
},
178+
Rel::Eq | Rel::Ne => unreachable!(),
179+
} {
180+
err_upcast_comparison(cx, span, lhs, true)
181+
} else if match rel {
182+
Rel::Lt => {
183+
if invert {
184+
norm_rhs_val >= ub
185+
} else {
186+
lb >= norm_rhs_val
187+
}
188+
},
189+
Rel::Le => {
190+
if invert {
191+
norm_rhs_val > ub
192+
} else {
193+
lb > norm_rhs_val
194+
}
195+
},
196+
Rel::Eq | Rel::Ne => unreachable!(),
197+
} {
198+
err_upcast_comparison(cx, span, lhs, false)
199+
}
200+
}
201+
}
202+
}
203+
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, ref lhs, ref 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 {
209+
val
210+
} else {
211+
return;
212+
};
213+
214+
let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
215+
let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
216+
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);
219+
}
220+
}
221+
}

clippy_lints/src/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ mod inherent_to_string;
242242
mod inline_fn_without_body;
243243
mod int_plus_one;
244244
mod integer_division;
245+
mod invalid_upcast_comparisons;
245246
mod items_after_statements;
246247
mod large_const_arrays;
247248
mod large_enum_variant;
@@ -697,6 +698,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
697698
&inline_fn_without_body::INLINE_FN_WITHOUT_BODY,
698699
&int_plus_one::INT_PLUS_ONE,
699700
&integer_division::INTEGER_DIVISION,
701+
&invalid_upcast_comparisons::INVALID_UPCAST_COMPARISONS,
700702
&items_after_statements::ITEMS_AFTER_STATEMENTS,
701703
&large_const_arrays::LARGE_CONST_ARRAYS,
702704
&large_enum_variant::LARGE_ENUM_VARIANT,
@@ -960,7 +962,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
960962
&types::BORROWED_BOX,
961963
&types::BOX_VEC,
962964
&types::IMPLICIT_HASHER,
963-
&types::INVALID_UPCAST_COMPARISONS,
964965
&types::LINKEDLIST,
965966
&types::OPTION_OPTION,
966967
&types::RC_BUFFER,
@@ -1114,7 +1115,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11141115
store.register_late_pass(|| box drop_forget_ref::DropForgetRef);
11151116
store.register_late_pass(|| box empty_enum::EmptyEnum);
11161117
store.register_late_pass(|| box absurd_extreme_comparisons::AbsurdExtremeComparisons);
1117-
store.register_late_pass(|| box types::InvalidUpcastComparisons);
1118+
store.register_late_pass(|| box invalid_upcast_comparisons::InvalidUpcastComparisons);
11181119
store.register_late_pass(|| box regex::Regex::default());
11191120
store.register_late_pass(|| box copies::CopyAndPaste);
11201121
store.register_late_pass(|| box copy_iterator::CopyIterator);
@@ -1374,6 +1375,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13741375
LintId::of(&if_not_else::IF_NOT_ELSE),
13751376
LintId::of(&implicit_saturating_sub::IMPLICIT_SATURATING_SUB),
13761377
LintId::of(&infinite_iter::MAYBE_INFINITE_ITER),
1378+
LintId::of(&invalid_upcast_comparisons::INVALID_UPCAST_COMPARISONS),
13771379
LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS),
13781380
LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS),
13791381
LintId::of(&let_underscore::LET_UNDERSCORE_DROP),
@@ -1413,7 +1415,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14131415
LintId::of(&trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS),
14141416
LintId::of(&trait_bounds::TYPE_REPETITION_IN_BOUNDS),
14151417
LintId::of(&types::IMPLICIT_HASHER),
1416-
LintId::of(&types::INVALID_UPCAST_COMPARISONS),
14171418
LintId::of(&types::LINKEDLIST),
14181419
LintId::of(&types::OPTION_OPTION),
14191420
LintId::of(&unicode::NON_ASCII_LITERAL),

0 commit comments

Comments
 (0)