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