]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/invalid_upcast_comparisons.rs
3b28b1212048a1b20de55a1e613858fb236c76cd
[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
18     /// 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?
23     /// An expression like `let x : u8 = ...; (x as u32) > 300`
24     /// will mistakenly imply that it is possible for `x` to be outside the range of
25     /// `u8`.
26     ///
27     /// ### Known problems
28     /// https://github.com/rust-lang/rust-clippy/issues/886
29     ///
30     /// ### Example
31     /// ```rust
32     /// let x: u8 = 1;
33     /// (x as u32) > 300;
34     /// ```
35     pub INVALID_UPCAST_COMPARISONS,
36     pedantic,
37     "a comparison involving an upcast which is always true or false"
38 }
39
40 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
41
42 #[derive(Copy, Clone, Debug, Eq)]
43 enum FullInt {
44     S(i128),
45     U(u128),
46 }
47
48 impl FullInt {
49     #[allow(clippy::cast_sign_loss)]
50     #[must_use]
51     fn cmp_s_u(s: i128, u: u128) -> Ordering {
52         if s < 0 {
53             Ordering::Less
54         } else if u > (i128::MAX as u128) {
55             Ordering::Greater
56         } else {
57             (s as u128).cmp(&u)
58         }
59     }
60 }
61
62 impl PartialEq for FullInt {
63     #[must_use]
64     fn eq(&self, other: &Self) -> bool {
65         self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
66     }
67 }
68
69 impl PartialOrd for FullInt {
70     #[must_use]
71     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
72         Some(match (self, other) {
73             (&Self::S(s), &Self::S(o)) => s.cmp(&o),
74             (&Self::U(s), &Self::U(o)) => s.cmp(&o),
75             (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
76             (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
77         })
78     }
79 }
80
81 impl Ord for FullInt {
82     #[must_use]
83     fn cmp(&self, other: &Self) -> Ordering {
84         self.partial_cmp(other)
85             .expect("`partial_cmp` for FullInt can never return `None`")
86     }
87 }
88
89 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
90     if let ExprKind::Cast(cast_exp, _) = expr.kind {
91         let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp);
92         let cast_ty = cx.typeck_results().expr_ty(expr);
93         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
94         if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
95             return None;
96         }
97         match pre_cast_ty.kind() {
98             ty::Int(int_ty) => Some(match int_ty {
99                 IntTy::I8 => (FullInt::S(i128::from(i8::MIN)), FullInt::S(i128::from(i8::MAX))),
100                 IntTy::I16 => (FullInt::S(i128::from(i16::MIN)), FullInt::S(i128::from(i16::MAX))),
101                 IntTy::I32 => (FullInt::S(i128::from(i32::MIN)), FullInt::S(i128::from(i32::MAX))),
102                 IntTy::I64 => (FullInt::S(i128::from(i64::MIN)), FullInt::S(i128::from(i64::MAX))),
103                 IntTy::I128 => (FullInt::S(i128::MIN), FullInt::S(i128::MAX)),
104                 IntTy::Isize => (FullInt::S(isize::MIN as i128), FullInt::S(isize::MAX as i128)),
105             }),
106             ty::Uint(uint_ty) => Some(match uint_ty {
107                 UintTy::U8 => (FullInt::U(u128::from(u8::MIN)), FullInt::U(u128::from(u8::MAX))),
108                 UintTy::U16 => (FullInt::U(u128::from(u16::MIN)), FullInt::U(u128::from(u16::MAX))),
109                 UintTy::U32 => (FullInt::U(u128::from(u32::MIN)), FullInt::U(u128::from(u32::MAX))),
110                 UintTy::U64 => (FullInt::U(u128::from(u64::MIN)), FullInt::U(u128::from(u64::MAX))),
111                 UintTy::U128 => (FullInt::U(u128::MIN), FullInt::U(u128::MAX)),
112                 UintTy::Usize => (FullInt::U(usize::MIN as u128), FullInt::U(usize::MAX as u128)),
113             }),
114             _ => None,
115         }
116     } else {
117         None
118     }
119 }
120
121 fn node_as_const_fullint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
122     let val = constant(cx, cx.typeck_results(), expr)?.0;
123     if let Constant::Int(const_int) = val {
124         match *cx.typeck_results().expr_ty(expr).kind() {
125             ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
126             ty::Uint(_) => Some(FullInt::U(const_int)),
127             _ => None,
128         }
129     } else {
130         None
131     }
132 }
133
134 fn err_upcast_comparison(cx: &LateContext<'_>, span: Span, expr: &Expr<'_>, always: bool) {
135     if let ExprKind::Cast(cast_val, _) = expr.kind {
136         span_lint(
137             cx,
138             INVALID_UPCAST_COMPARISONS,
139             span,
140             &format!(
141                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
142                 snippet(cx, cast_val.span, "the expression"),
143                 if always { "true" } else { "false" },
144             ),
145         );
146     }
147 }
148
149 fn upcast_comparison_bounds_err<'tcx>(
150     cx: &LateContext<'tcx>,
151     span: Span,
152     rel: comparisons::Rel,
153     lhs_bounds: Option<(FullInt, FullInt)>,
154     lhs: &'tcx Expr<'_>,
155     rhs: &'tcx Expr<'_>,
156     invert: bool,
157 ) {
158     if let Some((lb, ub)) = lhs_bounds {
159         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
160             if rel == Rel::Eq || rel == Rel::Ne {
161                 if norm_rhs_val < lb || norm_rhs_val > ub {
162                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
163                 }
164             } else if match rel {
165                 Rel::Lt => {
166                     if invert {
167                         norm_rhs_val < lb
168                     } else {
169                         ub < norm_rhs_val
170                     }
171                 },
172                 Rel::Le => {
173                     if invert {
174                         norm_rhs_val <= lb
175                     } else {
176                         ub <= norm_rhs_val
177                     }
178                 },
179                 Rel::Eq | Rel::Ne => unreachable!(),
180             } {
181                 err_upcast_comparison(cx, span, lhs, true);
182             } else if match rel {
183                 Rel::Lt => {
184                     if invert {
185                         norm_rhs_val >= ub
186                     } else {
187                         lb >= norm_rhs_val
188                     }
189                 },
190                 Rel::Le => {
191                     if invert {
192                         norm_rhs_val > ub
193                     } else {
194                         lb > norm_rhs_val
195                     }
196                 },
197                 Rel::Eq | Rel::Ne => unreachable!(),
198             } {
199                 err_upcast_comparison(cx, span, lhs, false);
200             }
201         }
202     }
203 }
204
205 impl<'tcx> LateLintPass<'tcx> for InvalidUpcastComparisons {
206     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
207         if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
208             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
209             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
210                 val
211             } else {
212                 return;
213             };
214
215             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
216             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
217
218             upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
219             upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
220         }
221     }
222 }