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