1 //! lint on manually implemented checked conversions that could be transformed into `try_from`
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};
15 const CHECKED_CONVERSIONS_MSRV: RustcVersion = RustcVersion::new(1, 34, 0);
17 declare_clippy_lint! {
18 /// **What it does:** Checks for explicit bounds checking when casting.
20 /// **Why is this bad?** Reduces the readability of statements & is error prone.
22 /// **Known problems:** None.
26 /// # let foo: u32 = 5;
28 /// foo <= i32::MAX as u32
35 /// # use std::convert::TryFrom;
38 /// i32::try_from(foo).is_ok()
41 pub CHECKED_CONVERSIONS,
43 "`try_from` could replace manual bounds checking when casting"
46 pub struct CheckedConversions {
47 msrv: Option<RustcVersion>,
50 impl CheckedConversions {
52 pub fn new(msrv: Option<RustcVersion>) -> Self {
57 impl_lint_pass!(CheckedConversions => [CHECKED_CONVERSIONS]);
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) {
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;
71 BinOpKind::Ge | BinOpKind::Le => single_check(item),
72 BinOpKind::And => double_check(cx, left, right),
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);
88 "checked cast can be simplified",
90 format!("{}::try_from({}).is_ok()", to_type, snippet),
97 extract_msrv_attr!(LateContext);
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)
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);
112 upper.zip(lower).and_then(|(l, r)| l.combine(r, cx))
115 upper_lower(left, right).or_else(|| upper_lower(right, left))
118 /// Contains the result of a tried conversion check
119 #[derive(Clone, Debug)]
120 struct Conversion<'a> {
122 expr_to_cast: &'a Expr<'a>,
123 to_type: Option<&'a str>,
126 /// The kind of conversion that is checked
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum ConversionType {
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 })
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))
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,
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 {
166 to_type: Some(to_type),
170 /// Construct a new conversion without type constraint
171 fn new_any(expr_to_cast: &'a Expr<'_>) -> Conversion<'a> {
173 cvt: ConversionType::SignedToUnsigned,
180 impl ConversionType {
181 /// Creates a conversion type if the type is allowed & conversion is valid
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)
200 /// Check for `expr <= (to_type::MAX as from_type)`
201 fn check_upper_bound<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<Conversion<'tcx>> {
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");
208 Conversion::try_new(candidate, from, to)
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)))
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))
229 /// Check for `expr >= 0`
230 fn check_lower_bound_zero<'a>(candidate: &'a Expr<'_>, check: &'a Expr<'_>) -> Option<Conversion<'a>> {
232 if let ExprKind::Lit(ref lit) = &check.kind;
233 if let LitKind::Int(0, _) = &lit.node;
236 Some(Conversion::new_any(candidate))
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)
252 /// Tries to extract the from- and to-type from a cast expression
253 fn get_types_from_cast<'a>(
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);
268 Some((limit, from_sym))
274 // `from_type::from(to_type::max_value())`
275 let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
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()`
281 if let limit = &args[0];
283 if let ExprKind::Path(ref path) = &from_func.kind;
284 if let Some(from_sym) = get_implementing_type(path, INTS, "from");
287 Some((limit, from_sym))
294 if let Some((limit, from_type)) = limit_from {
296 // `from_type::from(_)`
297 ExprKind::Call(path, _) => {
298 if let ExprKind::Path(ref path) = path.kind {
300 if let Some(to_type) = get_implementing_type(path, types, func) {
301 return Some((from_type, to_type));
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));
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> {
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;
325 let name = &int.ident.name.as_str();
326 candidates.iter().find(|c| name == *c).cloned()
333 /// Gets the type as a string, if it is a supported integer
334 fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> {
336 if let QPath::Resolved(_, ref path) = *path;
337 if let [ty] = &*path.segments;
339 let name = &ty.ident.name.as_str();
340 INTS.iter().find(|c| name == *c).cloned()
347 /// Will return the expressions as if they were expr1 <= expr2
348 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
350 BinOpKind::Le => Some((left, right)),
351 BinOpKind::Ge => Some((right, left)),
357 const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
358 const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
359 const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];