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