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