]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/checked_conversions.rs
Auto merge of #5671 - ebroto:changelog_144_145, 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_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind, QPath, TyKind};
7 use rustc_lint::{LateContext, LateLintPass, LintContext};
8 use rustc_middle::lint::in_external_macro;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
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 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 let Some(cv) = result {
62             if let Some(to_type) = cv.to_type {
63                 let mut applicability = Applicability::MachineApplicable;
64                 let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut applicability);
65                 span_lint_and_sugg(
66                     cx,
67                     CHECKED_CONVERSIONS,
68                     item.span,
69                     "Checked cast can be simplified.",
70                     "try",
71                     format!("{}::try_from({}).is_ok()", to_type, snippet),
72                     applicability,
73                 );
74             }
75         }
76     }
77 }
78
79 /// Searches for a single check from unsigned to _ is done
80 /// todo: check for case signed -> larger unsigned == only x >= 0
81 fn single_check<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
82     check_upper_bound(expr).filter(|cv| cv.cvt == ConversionType::FromUnsigned)
83 }
84
85 /// Searches for a combination of upper & lower bound checks
86 fn double_check<'a>(cx: &LateContext<'_, '_>, left: &'a Expr<'_>, right: &'a Expr<'_>) -> Option<Conversion<'a>> {
87     let upper_lower = |l, r| {
88         let upper = check_upper_bound(l);
89         let lower = check_lower_bound(r);
90
91         transpose(upper, lower).and_then(|(l, r)| l.combine(r, cx))
92     };
93
94     upper_lower(left, right).or_else(|| upper_lower(right, left))
95 }
96
97 /// Contains the result of a tried conversion check
98 #[derive(Clone, Debug)]
99 struct Conversion<'a> {
100     cvt: ConversionType,
101     expr_to_cast: &'a Expr<'a>,
102     to_type: Option<&'a str>,
103 }
104
105 /// The kind of conversion that is checked
106 #[derive(Copy, Clone, Debug, PartialEq)]
107 enum ConversionType {
108     SignedToUnsigned,
109     SignedToSigned,
110     FromUnsigned,
111 }
112
113 impl<'a> Conversion<'a> {
114     /// Combine multiple conversions if the are compatible
115     pub fn combine(self, other: Self, cx: &LateContext<'_, '_>) -> Option<Conversion<'a>> {
116         if self.is_compatible(&other, cx) {
117             // Prefer a Conversion that contains a type-constraint
118             Some(if self.to_type.is_some() { self } else { other })
119         } else {
120             None
121         }
122     }
123
124     /// Checks if two conversions are compatible
125     /// same type of conversion, same 'castee' and same 'to type'
126     pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_, '_>) -> bool {
127         (self.cvt == other.cvt)
128             && (SpanlessEq::new(cx).eq_expr(self.expr_to_cast, other.expr_to_cast))
129             && (self.has_compatible_to_type(other))
130     }
131
132     /// Checks if the to-type is the same (if there is a type constraint)
133     fn has_compatible_to_type(&self, other: &Self) -> bool {
134         transpose(self.to_type.as_ref(), other.to_type.as_ref()).map_or(true, |(l, r)| l == r)
135     }
136
137     /// Try to construct a new conversion if the conversion type is valid
138     fn try_new(expr_to_cast: &'a Expr<'_>, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
139         ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
140             cvt,
141             expr_to_cast,
142             to_type: Some(to_type),
143         })
144     }
145
146     /// Construct a new conversion without type constraint
147     fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
148         Conversion {
149             cvt: ConversionType::SignedToUnsigned,
150             expr_to_cast,
151             to_type: None,
152         }
153     }
154 }
155
156 impl ConversionType {
157     /// Creates a conversion type if the type is allowed & conversion is valid
158     #[must_use]
159     fn try_new(from: &str, to: &str) -> Option<Self> {
160         if UINTS.contains(&from) {
161             Some(Self::FromUnsigned)
162         } else if SINTS.contains(&from) {
163             if UINTS.contains(&to) {
164                 Some(Self::SignedToUnsigned)
165             } else if SINTS.contains(&to) {
166                 Some(Self::SignedToSigned)
167             } else {
168                 None
169             }
170         } else {
171             None
172         }
173     }
174 }
175
176 /// Check for `expr <= (to_type::MAX as from_type)`
177 fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
178     if_chain! {
179          if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind;
180          if let Some((candidate, check)) = normalize_le_ge(op, left, right);
181          if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX");
182
183          then {
184              Conversion::try_new(candidate, from, to)
185          } else {
186             None
187         }
188     }
189 }
190
191 /// Check for `expr >= 0|(to_type::MIN as from_type)`
192 fn check_lower_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
193     fn check_function<'a>(candidate: &'a Expr<'a>, check: &'a Expr<'a>) -> Option<Conversion<'a>> {
194         (check_lower_bound_zero(candidate, check)).or_else(|| (check_lower_bound_min(candidate, check)))
195     }
196
197     // First of we need a binary containing the expression & the cast
198     if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind {
199         normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
200     } else {
201         None
202     }
203 }
204
205 /// Check for `expr >= 0`
206 fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
207     if_chain! {
208         if let ExprKind::Lit(ref lit) = &check.kind;
209         if let LitKind::Int(0, _) = &lit.node;
210
211         then {
212             Some(Conversion::new_any(candidate))
213         } else {
214             None
215         }
216     }
217 }
218
219 /// Check for `expr >= (to_type::MIN as from_type)`
220 fn check_lower_bound_min<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
221     if let Some((from, to)) = get_types_from_cast(check, SINTS, "min_value", "MIN") {
222         Conversion::try_new(candidate, from, to)
223     } else {
224         None
225     }
226 }
227
228 /// Tries to extract the from- and to-type from a cast expression
229 fn get_types_from_cast<'a>(
230     expr: &'a Expr<'_>,
231     types: &'a [&str],
232     func: &'a str,
233     assoc_const: &'a str,
234 ) -> Option<(&'a str, &'a str)> {
235     // `to_type::max_value() as from_type`
236     // or `to_type::MAX as from_type`
237     let call_from_cast: Option<(&Expr<'_>, &str)> = if_chain! {
238         // to_type::max_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::max_value())`
251     let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
252         if_chain! {
253             // `from_type::from, to_type::max_value()`
254             if let ExprKind::Call(ref from_func, ref args) = &expr.kind;
255             // `to_type::max_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         match limit.kind {
272             // `from_type::from(_)`
273             ExprKind::Call(path, _) => {
274                 if let ExprKind::Path(ref path) = path.kind {
275                     // `to_type`
276                     if let Some(to_type) = get_implementing_type(path, types, func) {
277                         return Some((from_type, to_type));
278                     }
279                 }
280             },
281             // `to_type::MAX`
282             ExprKind::Path(ref path) => {
283                 if let Some(to_type) = get_implementing_type(path, types, assoc_const) {
284                     return Some((from_type, to_type));
285                 }
286             },
287             _ => {},
288         }
289     };
290     None
291 }
292
293 /// Gets the type which implements the called function
294 fn get_implementing_type<'a>(path: &QPath<'_>, candidates: &'a [&str], function: &str) -> Option<&'a str> {
295     if_chain! {
296         if let QPath::TypeRelative(ref ty, ref path) = &path;
297         if path.ident.name.as_str() == function;
298         if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.kind;
299         if let [int] = &*tp.segments;
300         let name = &int.ident.name.as_str();
301
302         then {
303             candidates.iter().find(|c| name == *c).cloned()
304         } else {
305             None
306         }
307     }
308 }
309
310 /// Gets the type as a string, if it is a supported integer
311 fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
312     if_chain! {
313         if let QPath::Resolved(_, ref path) = *path;
314         if let [ty] = &*path.segments;
315         let name = &ty.ident.name.as_str();
316
317         then {
318             INTS.iter().find(|c| name == *c).cloned()
319         } else {
320             None
321         }
322     }
323 }
324
325 /// (Option<T>, Option<U>) -> Option<(T, U)>
326 fn transpose<T, U>(lhs: Option<T>, rhs: Option<U>) -> Option<(T, U)> {
327     match (lhs, rhs) {
328         (Some(l), Some(r)) => Some((l, r)),
329         _ => None,
330     }
331 }
332
333 /// Will return the expressions as if they were expr1 <= expr2
334 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
335     match op.node {
336         BinOpKind::Le => Some((left, right)),
337         BinOpKind::Ge => Some((right, left)),
338         _ => None,
339     }
340 }
341
342 // Constants
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"];