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