]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/checked_conversions.rs
Rollup merge of #90995 - the8472:hash-portability, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / checked_conversions.rs
1 //! lint on manually implemented checked conversions that could be transformed into `try_from`
2
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::{meets_msrv, msrvs, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_ast::ast::LitKind;
8 use rustc_errors::Applicability;
9 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind, QPath, TyKind};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for explicit bounds checking when casting.
18     ///
19     /// ### Why is this bad?
20     /// Reduces the readability of statements & is error prone.
21     ///
22     /// ### Example
23     /// ```rust
24     /// # let foo: u32 = 5;
25     /// # let _ =
26     /// foo <= i32::MAX as u32
27     /// # ;
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # use std::convert::TryFrom;
34     /// # let foo = 1;
35     /// # let _ =
36     /// i32::try_from(foo).is_ok()
37     /// # ;
38     /// ```
39     pub CHECKED_CONVERSIONS,
40     pedantic,
41     "`try_from` could replace manual bounds checking when casting"
42 }
43
44 pub struct CheckedConversions {
45     msrv: Option<RustcVersion>,
46 }
47
48 impl CheckedConversions {
49     #[must_use]
50     pub fn new(msrv: Option<RustcVersion>) -> Self {
51         Self { msrv }
52     }
53 }
54
55 impl_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
56
57 impl<'tcx> LateLintPass<'tcx> for CheckedConversions {
58     fn check_expr(&mut self, cx: &LateContext<'_>, item: &Expr<'_>) {
59         if !meets_msrv(self.msrv.as_ref(), &msrvs::TRY_FROM) {
60             return;
61         }
62
63         let result = if_chain! {
64             if !in_external_macro(cx.sess(), item.span);
65             if let ExprKind::Binary(op, left, right) = &item.kind;
66
67             then {
68                 match op.node {
69                     BinOpKind::Ge | BinOpKind::Le => single_check(item),
70                     BinOpKind::And => double_check(cx, left, right),
71                     _ => None,
72                 }
73             } else {
74                 None
75             }
76         };
77
78         if let Some(cv) = result {
79             if let Some(to_type) = cv.to_type {
80                 let mut applicability = Applicability::MachineApplicable;
81                 let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability);
82                 span_lint_and_sugg(
83                     cx,
84                     CHECKED_CONVERSIONS,
85                     item.span,
86                     "checked cast can be simplified",
87                     "try",
88                     format!("{}::try_from({}).is_ok()", to_type, snippet),
89                     applicability,
90                 );
91             }
92         }
93     }
94
95     extract_msrv_attr!(LateContext);
96 }
97
98 /// Searches for a single check from unsigned to _ is done
99 /// todo: check for case signed -> larger unsigned == only x >= 0
100 fn single_check<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
101     check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
102 }
103
104 /// Searches for a combination of upper & lower bound checks
105 fn double_check<'a>(cx: &LateContext<'_>, left: &'a Expr<'_>, right: &'a Expr<'_>) -> Option<Conversion<'a>> {
106     let upper_lower = |l, r| {
107         let upper = check_upper_bound(l);
108         let lower = check_lower_bound(r);
109
110         upper.zip(lower).and_then(|(l, r)| l.combine(r, cx))
111     };
112
113     upper_lower(left, right).or_else(|| upper_lower(right, left))
114 }
115
116 /// Contains the result of a tried conversion check
117 #[derive(Clone, Debug)]
118 struct Conversion<'a> {
119     cvt: ConversionType,
120     expr_to_cast: &'a Expr<'a>,
121     to_type: Option<&'a str>,
122 }
123
124 /// The kind of conversion that is checked
125 #[derive(Copy, Clone, Debug, PartialEq)]
126 enum ConversionType {
127     SignedToUnsigned,
128     SignedToSigned,
129     FromUnsigned,
130 }
131
132 impl<'a> Conversion<'a> {
133     /// Combine multiple conversions if the are compatible
134     pub fn combine(self, other: Self, cx: &LateContext<'_>) -> Option<Conversion<'a>> {
135         if self.is_compatible(&other, cx) {
136             // Prefer a Conversion that contains a type-constraint
137             Some(if self.to_type.is_some() { self } else { other })
138         } else {
139             None
140         }
141     }
142
143     /// Checks if two conversions are compatible
144     /// same type of conversion, same 'castee' and same 'to type'
145     pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_>) -> bool {
146         (self.cvt == other.cvt)
147             && (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
148             && (self.has_compatible_to_type(other))
149     }
150
151     /// Checks if the to-type is the same (if there is a type constraint)
152     fn has_compatible_to_type(&self, other: &Self) -> bool {
153         match (self.to_type, other.to_type) {
154             (Some(l), Some(r)) => l == r,
155             _ => true,
156         }
157     }
158
159     /// Try to construct a new conversion if the conversion type is valid
160     fn try_new(expr_to_cast: &'a Expr<'_>, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
161         ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
162             cvt,
163             expr_to_cast,
164             to_type: Some(to_type),
165         })
166     }
167
168     /// Construct a new conversion without type constraint
169     fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
170         Conversion {
171             cvt: ConversionType::SignedToUnsigned,
172             expr_to_cast,
173             to_type: None,
174         }
175     }
176 }
177
178 impl ConversionType {
179     /// Creates a conversion type if the type is allowed & conversion is valid
180     #[must_use]
181     fn try_new(from: &str, to: &str) -> Option<Self> {
182         if UINTS.contains(&from) {
183             Some(Self::FromUnsigned)
184         } else if SINTS.contains(&from) {
185             if UINTS.contains(&to) {
186                 Some(Self::SignedToUnsigned)
187             } else if SINTS.contains(&to) {
188                 Some(Self::SignedToSigned)
189             } else {
190                 None
191             }
192         } else {
193             None
194         }
195     }
196 }
197
198 /// Check for `expr <= (to_type::MAX as from_type)`
199 fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
200     if_chain! {
201          if let ExprKind::Binary(ref op, left, right) = &expr.kind;
202          if let Some((candidate, check)) = normalize_le_ge(op, left, right);
203          if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX");
204
205          then {
206              Conversion::try_new(candidate, from, to)
207          } else {
208             None
209         }
210     }
211 }
212
213 /// Check for `expr >= 0|(to_type::MIN as from_type)`
214 fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
215     fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option<Conversion<'a>> {
216         (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
217     }
218
219     // First of we need a binary containing the expression & the cast
220     if let ExprKind::Binary(ref op, left, right) = &expr.kind {
221         normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
222     } else {
223         None
224     }
225 }
226
227 /// Check for `expr >= 0`
228 fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
229     if_chain! {
230         if let ExprKind::Lit(ref lit) = &check.kind;
231         if let LitKind::Int(0, _) = &lit.node;
232
233         then {
234             Some(Conversion::new_any(candidate))
235         } else {
236             None
237         }
238     }
239 }
240
241 /// Check for `expr >= (to_type::MIN as from_type)`
242 fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
243     if let Some((from, to)) = get_types_from_cast(check, SINTS, "min_value", "MIN") {
244         Conversion::try_new(candidate, from, to)
245     } else {
246         None
247     }
248 }
249
250 /// Tries to extract the from- and to-type from a cast expression
251 fn get_types_from_cast<'a>(
252     expr: &'a Expr<'_>,
253     types: &'a [&str],
254     func: &'a str,
255     assoc_const: &'a str,
256 ) -> Option<(&'a str, &'a str)> {
257     // `to_type::max_value() as from_type`
258     // or `to_type::MAX as from_type`
259     let call_from_cast: Option<(&Expr<'_>, &str)> = if_chain! {
260         // to_type::max_value(), from_type
261         if let ExprKind::Cast(limit, from_type) = &expr.kind;
262         if let TyKind::Path(ref from_type_path) = &from_type.kind;
263         if let Some(from_sym) = int_ty_to_sym(from_type_path);
264
265         then {
266             Some((limit, from_sym))
267         } else {
268             None
269         }
270     };
271
272     // `from_type::from(to_type::max_value())`
273     let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
274         if_chain! {
275             // `from_type::from, to_type::max_value()`
276             if let ExprKind::Call(from_func, args) = &expr.kind;
277             // `to_type::max_value()`
278             if args.len() == 1;
279             if let limit = &args[0];
280             // `from_type::from`
281             if let ExprKind::Path(ref path) = &from_func.kind;
282             if let Some(from_sym) = get_implementing_type(path, INTS, "from");
283
284             then {
285                 Some((limit, from_sym))
286             } else {
287                 None
288             }
289         }
290     });
291
292     if let Some((limit, from_type)) = limit_from {
293         match limit.kind {
294             // `from_type::from(_)`
295             ExprKind::Call(path, _) => {
296                 if let ExprKind::Path(ref path) = path.kind {
297                     // `to_type`
298                     if let Some(to_type) = get_implementing_type(path, types, func) {
299                         return Some((from_type, to_type));
300                     }
301                 }
302             },
303             // `to_type::MAX`
304             ExprKind::Path(ref path) => {
305                 if let Some(to_type) = get_implementing_type(path, types, assoc_const) {
306                     return Some((from_type, to_type));
307                 }
308             },
309             _ => {},
310         }
311     };
312     None
313 }
314
315 /// Gets the type which implements the called function
316 fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function: &str) -> Option<&'a str> {
317     if_chain! {
318         if let QPath::TypeRelative(ty, path) = &path;
319         if path.ident.name.as_str() == function;
320         if let TyKind::Path(QPath::Resolved(None, tp)) = &ty.kind;
321         if let [int] = &*tp.segments;
322         then {
323             let name = &int.ident.name.as_str();
324             candidates.iter().find(|c| name == *c).copied()
325         } else {
326             None
327         }
328     }
329 }
330
331 /// Gets the type as a string, if it is a supported integer
332 fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
333     if_chain! {
334         if let QPath::Resolved(_, path) = *path;
335         if let [ty] = &*path.segments;
336         then {
337             let name = &ty.ident.name.as_str();
338             INTS.iter().find(|c| name == *c).copied()
339         } else {
340             None
341         }
342     }
343 }
344
345 /// Will return the expressions as if they were expr1 <= expr2
346 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
347     match op.node {
348         BinOpKind::Le => Some((left, right)),
349         BinOpKind::Ge => Some((right, left)),
350         _ => None,
351     }
352 }
353
354 // Constants
355 const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
356 const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
357 const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];