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