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