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