]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/checked_conversions.rs
rustup https://github.com/rust-lang/rust/pull/67455
[rust.git] / clippy_lints / src / checked_conversions.rs
index 0269a1959b7686b5e763f2e0a7d206cbc2def3ad..abd44974fa7b6be5642e43e924e440e9d112f629 100644 (file)
@@ -1,12 +1,14 @@
 //! lint on manually implemented checked conversions that could be transformed into `try_from`
 
 use if_chain::if_chain;
+use rustc::declare_lint_pass;
 use rustc::hir::*;
 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
-use rustc::{declare_lint_pass, declare_tool_lint};
+use rustc_errors::Applicability;
+use rustc_session::declare_tool_lint;
 use syntax::ast::LitKind;
 
-use crate::utils::{span_lint, SpanlessEq};
+use crate::utils::{snippet_with_applicability, span_lint_and_sugg, SpanlessEq};
 
 declare_clippy_lint! {
     /// **What it does:** Checks for explicit bounds checking when casting.
@@ -26,6 +28,8 @@
     /// Could be written:
     ///
     /// ```rust
+    /// # use std::convert::TryFrom;
+    /// # let foo = 1;
     /// # let _ =
     /// i32::try_from(foo).is_ok()
     /// # ;
@@ -41,7 +45,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CheckedConversions {
     fn check_expr(&mut self, cx: &LateContext<'_, '_>, item: &Expr) {
         let result = if_chain! {
             if !in_external_macro(cx.sess(), item.span);
-            if let ExprKind::Binary(op, ref left, ref right) = &item.node;
+            if let ExprKind::Binary(op, ref left, ref right) = &item.kind;
 
             then {
                 match op.node {
@@ -54,16 +58,26 @@ fn check_expr(&mut self, cx: &LateContext<'_, '_>, item: &Expr) {
             }
         };
 
-        if let Some(cv) = result {
-            span_lint(
-                cx,
-                CHECKED_CONVERSIONS,
-                item.span,
-                &format!(
-                    "Checked cast can be simplified: `{}::try_from`",
-                    cv.to_type.unwrap_or_else(|| "IntegerType".to_string()),
-                ),
-            );
+        if_chain! {
+            if let Some(cv) = result;
+            if let Some(to_type) = cv.to_type;
+
+            then {
+                let mut applicability = Applicability::MachineApplicable;
+                let snippet = snippet_with_applicability(cx, cv.expr_to_cast.span, "_", &mut
+                                applicability);
+                span_lint_and_sugg(
+                    cx,
+                    CHECKED_CONVERSIONS,
+                    item.span,
+                    "Checked cast can be simplified.",
+                    "try",
+                    format!("{}::try_from({}).is_ok()",
+                            to_type,
+                            snippet),
+                    applicability
+                );
+            }
         }
     }
 }
@@ -91,7 +105,7 @@ fn double_check<'a>(cx: &LateContext<'_, '_>, left: &'a Expr, right: &'a Expr) -
 struct Conversion<'a> {
     cvt: ConversionType,
     expr_to_cast: &'a Expr,
-    to_type: Option<String>,
+    to_type: Option<&'a str>,
 }
 
 /// The kind of conversion that is checked
@@ -123,14 +137,12 @@ pub fn is_compatible(&self, other: &Self, cx: &LateContext<'_, '_>) -> bool {
 
     /// Checks if the to-type is the same (if there is a type constraint)
     fn has_compatible_to_type(&self, other: &Self) -> bool {
-        transpose(self.to_type.as_ref(), other.to_type.as_ref())
-            .map(|(l, r)| l == r)
-            .unwrap_or(true)
+        transpose(self.to_type.as_ref(), other.to_type.as_ref()).map_or(true, |(l, r)| l == r)
     }
 
     /// Try to construct a new conversion if the conversion type is valid
-    fn try_new<'b>(expr_to_cast: &'a Expr, from_type: &'b str, to_type: String) -> Option<Conversion<'a>> {
-        ConversionType::try_new(from_type, &to_type).map(|cvt| Conversion {
+    fn try_new(expr_to_cast: &'a Expr, from_type: &str, to_type: &'a str) -> Option<Conversion<'a>> {
+        ConversionType::try_new(from_type, to_type).map(|cvt| Conversion {
             cvt,
             expr_to_cast,
             to_type: Some(to_type),
@@ -149,14 +161,15 @@ fn new_any(expr_to_cast: &'a Expr) -> Conversion<'a> {
 
 impl ConversionType {
     /// Creates a conversion type if the type is allowed & conversion is valid
-    fn try_new(from: &str, to: &str) -> Option<ConversionType> {
-        if UNSIGNED_TYPES.contains(&from) {
-            Some(ConversionType::FromUnsigned)
-        } else if SIGNED_TYPES.contains(&from) {
-            if UNSIGNED_TYPES.contains(&to) {
-                Some(ConversionType::SignedToUnsigned)
-            } else if SIGNED_TYPES.contains(&to) {
-                Some(ConversionType::SignedToSigned)
+    #[must_use]
+    fn try_new(from: &str, to: &str) -> Option<Self> {
+        if UINTS.contains(&from) {
+            Some(Self::FromUnsigned)
+        } else if SINTS.contains(&from) {
+            if UINTS.contains(&to) {
+                Some(Self::SignedToUnsigned)
+            } else if SINTS.contains(&to) {
+                Some(Self::SignedToSigned)
             } else {
                 None
             }
@@ -169,12 +182,12 @@ fn try_new(from: &str, to: &str) -> Option<ConversionType> {
 /// Check for `expr <= (to_type::max_value() as from_type)`
 fn check_upper_bound(expr: &Expr) -> Option<Conversion<'_>> {
     if_chain! {
-         if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node;
+         if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind;
          if let Some((candidate, check)) = normalize_le_ge(op, left, right);
-         if let Some((from, to)) = get_types_from_cast(check, "max_value", INT_TYPES);
+         if let Some((from, to)) = get_types_from_cast(check, MAX_VALUE, INTS);
 
          then {
-             Conversion::try_new(candidate, &from, to)
+             Conversion::try_new(candidate, from, to)
          } else {
             None
         }
@@ -188,7 +201,7 @@ fn check_function<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion
     }
 
     // First of we need a binary containing the expression & the cast
-    if let ExprKind::Binary(ref op, ref left, ref right) = &expr.node {
+    if let ExprKind::Binary(ref op, ref left, ref right) = &expr.kind {
         normalize_le_ge(op, right, left).and_then(|(l, r)| check_function(l, r))
     } else {
         None
@@ -198,7 +211,7 @@ fn check_function<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion
 /// Check for `expr >= 0`
 fn check_lower_bound_zero<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
     if_chain! {
-        if let ExprKind::Lit(ref lit) = &check.node;
+        if let ExprKind::Lit(ref lit) = &check.kind;
         if let LitKind::Int(0, _) = &lit.node;
 
         then {
@@ -211,43 +224,43 @@ fn check_lower_bound_zero<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Co
 
 /// Check for `expr >= (to_type::min_value() as from_type)`
 fn check_lower_bound_min<'a>(candidate: &'a Expr, check: &'a Expr) -> Option<Conversion<'a>> {
-    if let Some((from, to)) = get_types_from_cast(check, "min_value", SIGNED_TYPES) {
-        Conversion::try_new(candidate, &from, to)
+    if let Some((from, to)) = get_types_from_cast(check, MIN_VALUE, SINTS) {
+        Conversion::try_new(candidate, from, to)
     } else {
         None
     }
 }
 
 /// Tries to extract the from- and to-type from a cast expression
-fn get_types_from_cast(expr: &Expr, func: &str, types: &[&str]) -> Option<(String, String)> {
+fn get_types_from_cast<'a>(expr: &'a Expr, func: &'a str, types: &'a [&str]) -> Option<(&'a str, &'a str)> {
     // `to_type::maxmin_value() as from_type`
-    let call_from_cast: Option<(&Expr, String)> = if_chain! {
+    let call_from_cast: Option<(&Expr, &str)> = if_chain! {
         // to_type::maxmin_value(), from_type
-        if let ExprKind::Cast(ref limit, ref from_type) = &expr.node;
-        if let TyKind::Path(ref from_type_path) = &from_type.node;
-        if let Some(from_type_str) = int_ty_to_str(from_type_path);
+        if let ExprKind::Cast(ref limit, ref from_type) = &expr.kind;
+        if let TyKind::Path(ref from_type_path) = &from_type.kind;
+        if let Some(from_sym) = int_ty_to_sym(from_type_path);
 
         then {
-            Some((limit, from_type_str.to_string()))
+            Some((limit, from_sym))
         } else {
             None
         }
     };
 
     // `from_type::from(to_type::maxmin_value())`
-    let limit_from: Option<(&Expr, String)> = call_from_cast.or_else(|| {
+    let limit_from: Option<(&Expr, &str)> = call_from_cast.or_else(|| {
         if_chain! {
             // `from_type::from, to_type::maxmin_value()`
-            if let ExprKind::Call(ref from_func, ref args) = &expr.node;
+            if let ExprKind::Call(ref from_func, ref args) = &expr.kind;
             // `to_type::maxmin_value()`
             if args.len() == 1;
             if let limit = &args[0];
             // `from_type::from`
-            if let ExprKind::Path(ref path) = &from_func.node;
-            if let Some(from_type) = get_implementing_type(path, INT_TYPES, "from");
+            if let ExprKind::Path(ref path) = &from_func.kind;
+            if let Some(from_sym) = get_implementing_type(path, INTS, FROM);
 
             then {
-                Some((limit, from_type))
+                Some((limit, from_sym))
             } else {
                 None
             }
@@ -256,9 +269,9 @@ fn get_types_from_cast(expr: &Expr, func: &str, types: &[&str]) -> Option<(Strin
 
     if let Some((limit, from_type)) = limit_from {
         if_chain! {
-            if let ExprKind::Call(ref fun_name, _) = &limit.node;
+            if let ExprKind::Call(ref fun_name, _) = &limit.kind;
             // `to_type, maxmin_value`
-            if let ExprKind::Path(ref path) = &fun_name.node;
+            if let ExprKind::Path(ref path) = &fun_name.kind;
             // `to_type`
             if let Some(to_type) = get_implementing_type(path, types, func);
 
@@ -274,17 +287,16 @@ fn get_types_from_cast(expr: &Expr, func: &str, types: &[&str]) -> Option<(Strin
 }
 
 /// Gets the type which implements the called function
-fn get_implementing_type(path: &QPath, candidates: &[&str], function: &str) -> Option<String> {
+fn get_implementing_type<'a>(path: &QPath, candidates: &'a [&str], function: &str) -> Option<&'a str> {
     if_chain! {
         if let QPath::TypeRelative(ref ty, ref path) = &path;
-        if path.ident.name == function;
-        if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.node;
+        if path.ident.name.as_str() == function;
+        if let TyKind::Path(QPath::Resolved(None, ref tp)) = &ty.kind;
         if let [int] = &*tp.segments;
-        let name = int.ident.as_str().get();
-        if candidates.contains(&name);
+        let name = &int.ident.name.as_str();
 
         then {
-            Some(name.to_string())
+            candidates.iter().find(|c| name == *c).cloned()
         } else {
             None
         }
@@ -292,16 +304,14 @@ fn get_implementing_type(path: &QPath, candidates: &[&str], function: &str) -> O
 }
 
 /// Gets the type as a string, if it is a supported integer
-fn int_ty_to_str(path: &QPath) -> Option<&str> {
+fn int_ty_to_sym(path: &QPath) -> Option<&str> {
     if_chain! {
         if let QPath::Resolved(_, ref path) = *path;
         if let [ty] = &*path.segments;
+        let name = &ty.ident.name.as_str();
 
         then {
-            INT_TYPES
-                .iter()
-                .find(|c| (&ty.ident.name) == *c)
-                .cloned()
+            INTS.iter().find(|c| name == *c).cloned()
         } else {
             None
         }
@@ -317,7 +327,7 @@ fn transpose<T, U>(lhs: Option<T>, rhs: Option<U>) -> Option<(T, U)> {
 }
 
 /// Will return the expressions as if they were expr1 <= expr2
-fn normalize_le_ge<'a>(op: &'a BinOp, left: &'a Expr, right: &'a Expr) -> Option<(&'a Expr, &'a Expr)> {
+fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr, right: &'a Expr) -> Option<(&'a Expr, &'a Expr)> {
     match op.node {
         BinOpKind::Le => Some((left, right)),
         BinOpKind::Ge => Some((right, left)),
@@ -325,8 +335,11 @@ fn normalize_le_ge<'a>(op: &'a BinOp, left: &'a Expr, right: &'a Expr) -> Option
     }
 }
 
-const UNSIGNED_TYPES: &[&str] = &["u8", "u16", "u32", "u64", "u128", "usize"];
-const SIGNED_TYPES: &[&str] = &["i8", "i16", "i32", "i64", "i128", "isize"];
-const INT_TYPES: &[&str] = &[
-    "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
-];
+// Constants
+const FROM: &str = "from";
+const MAX_VALUE: &str = "max_value";
+const MIN_VALUE: &str = "min_value";
+
+const UINTS: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
+const SINTS: &[&str] = &["i8", "i16", "i32", "i64", "isize"];
+const INTS: &[&str] = &["u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize"];