about summary refs log tree commit diff
path: root/clippy_lints/src/casts
diff options
context:
space:
mode:
authorPhilipp Krones <hello@philkrones.com>2023-11-16 19:13:24 +0100
committerPhilipp Krones <hello@philkrones.com>2023-11-16 19:13:24 +0100
commit6246f0446afbe9abff18e8cc1ebaae7505f7cd9e (patch)
tree50ef81f3e7465a1187443aeb40d80d293f664884 /clippy_lints/src/casts
parent9aa2330e41b9d6e25fb357b54f5ae98448543752 (diff)
downloadrust-6246f0446afbe9abff18e8cc1ebaae7505f7cd9e.tar.gz
rust-6246f0446afbe9abff18e8cc1ebaae7505f7cd9e.zip
Merge commit 'edb720b199083f4107b858a8761648065bf38d86' into clippyup
Diffstat (limited to 'clippy_lints/src/casts')
-rw-r--r--clippy_lints/src/casts/cast_possible_wrap.rs13
-rw-r--r--clippy_lints/src/casts/cast_sign_loss.rs25
-rw-r--r--clippy_lints/src/casts/cast_slice_different_sizes.rs37
-rw-r--r--clippy_lints/src/casts/cast_slice_from_raw_parts.rs57
-rw-r--r--clippy_lints/src/casts/char_lit_as_u8.rs50
-rw-r--r--clippy_lints/src/casts/ptr_cast_constness.rs53
-rw-r--r--clippy_lints/src/casts/unnecessary_cast.rs98
7 files changed, 161 insertions, 172 deletions
diff --git a/clippy_lints/src/casts/cast_possible_wrap.rs b/clippy_lints/src/casts/cast_possible_wrap.rs
index ffa571abb39..2ddb0f00ecd 100644
--- a/clippy_lints/src/casts/cast_possible_wrap.rs
+++ b/clippy_lints/src/casts/cast_possible_wrap.rs
@@ -1,5 +1,6 @@
+use clippy_utils::diagnostics::span_lint_and_then;
 use rustc_hir::Expr;
-use rustc_lint::{LateContext, LintContext};
+use rustc_lint::LateContext;
 use rustc_middle::ty::Ty;
 
 use super::{utils, CAST_POSSIBLE_WRAP};
@@ -78,13 +79,11 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca
         ),
     };
 
-    cx.struct_span_lint(CAST_POSSIBLE_WRAP, expr.span, message, |diag| {
+    span_lint_and_then(cx, CAST_POSSIBLE_WRAP, expr.span, &message, |diag| {
         if let EmitState::LintOnPtrSize(16) = should_lint {
             diag
-            .note("`usize` and `isize` may be as small as 16 bits on some platforms")
-            .note("for more information see https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types")
-        } else {
-            diag
-        }
+                .note("`usize` and `isize` may be as small as 16 bits on some platforms")
+                .note("for more information see https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types");
+        };
     });
 }
diff --git a/clippy_lints/src/casts/cast_sign_loss.rs b/clippy_lints/src/casts/cast_sign_loss.rs
index a83dfd94dc2..bd12ee40628 100644
--- a/clippy_lints/src/casts/cast_sign_loss.rs
+++ b/clippy_lints/src/casts/cast_sign_loss.rs
@@ -1,7 +1,6 @@
 use clippy_utils::consts::{constant, Constant};
 use clippy_utils::diagnostics::span_lint;
 use clippy_utils::{method_chain_args, sext};
-use if_chain::if_chain;
 use rustc_hir::{Expr, ExprKind};
 use rustc_lint::LateContext;
 use rustc_middle::ty::{self, Ty};
@@ -28,13 +27,11 @@ fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast
 
             // Don't lint for positive constants.
             let const_val = constant(cx, cx.typeck_results(), cast_op);
-            if_chain! {
-                if let Some(Constant::Int(n)) = const_val;
-                if let ty::Int(ity) = *cast_from.kind();
-                if sext(cx.tcx, n, ity) >= 0;
-                then {
-                    return false;
-                }
+            if let Some(Constant::Int(n)) = const_val
+                && let ty::Int(ity) = *cast_from.kind()
+                && sext(cx.tcx, n, ity) >= 0
+            {
+                return false;
             }
 
             // Don't lint for the result of methods that always return non-negative values.
@@ -42,13 +39,11 @@ fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast
                 let mut method_name = path.ident.name.as_str();
                 let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
 
-                if_chain! {
-                    if method_name == "unwrap";
-                    if let Some(arglist) = method_chain_args(cast_op, &["unwrap"]);
-                    if let ExprKind::MethodCall(inner_path, ..) = &arglist[0].0.kind;
-                    then {
-                        method_name = inner_path.ident.name.as_str();
-                    }
+                if method_name == "unwrap"
+                    && let Some(arglist) = method_chain_args(cast_op, &["unwrap"])
+                    && let ExprKind::MethodCall(inner_path, ..) = &arglist[0].0.kind
+                {
+                    method_name = inner_path.ident.name.as_str();
                 }
 
                 if allowed_methods.iter().any(|&name| method_name == name) {
diff --git a/clippy_lints/src/casts/cast_slice_different_sizes.rs b/clippy_lints/src/casts/cast_slice_different_sizes.rs
index d1410402913..2a9f7fec172 100644
--- a/clippy_lints/src/casts/cast_slice_different_sizes.rs
+++ b/clippy_lints/src/casts/cast_slice_different_sizes.rs
@@ -1,7 +1,6 @@
 use clippy_config::msrvs::{self, Msrv};
 use clippy_utils::diagnostics::span_lint_and_then;
 use clippy_utils::source;
-use if_chain::if_chain;
 use rustc_ast::Mutability;
 use rustc_hir::{Expr, ExprKind, Node};
 use rustc_lint::LateContext;
@@ -69,26 +68,24 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, msrv: &Msrv
 
 fn is_child_of_cast(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
     let map = cx.tcx.hir();
-    if_chain! {
-        if let Some(parent_id) = map.opt_parent_id(expr.hir_id);
-        if let Some(parent) = map.find(parent_id);
-        then {
-            let expr = match parent {
-                Node::Block(block) => {
-                    if let Some(parent_expr) = block.expr {
-                        parent_expr
-                    } else {
-                        return false;
-                    }
-                },
-                Node::Expr(expr) => expr,
-                _ => return false,
-            };
+    if let Some(parent_id) = map.opt_parent_id(expr.hir_id)
+        && let Some(parent) = map.find(parent_id)
+    {
+        let expr = match parent {
+            Node::Block(block) => {
+                if let Some(parent_expr) = block.expr {
+                    parent_expr
+                } else {
+                    return false;
+                }
+            },
+            Node::Expr(expr) => expr,
+            _ => return false,
+        };
 
-            matches!(expr.kind, ExprKind::Cast(..))
-        } else {
-            false
-        }
+        matches!(expr.kind, ExprKind::Cast(..))
+    } else {
+        false
     }
 }
 
diff --git a/clippy_lints/src/casts/cast_slice_from_raw_parts.rs b/clippy_lints/src/casts/cast_slice_from_raw_parts.rs
index badadf2c9f6..3db1e3e6d97 100644
--- a/clippy_lints/src/casts/cast_slice_from_raw_parts.rs
+++ b/clippy_lints/src/casts/cast_slice_from_raw_parts.rs
@@ -1,7 +1,6 @@
 use clippy_config::msrvs::{self, Msrv};
 use clippy_utils::diagnostics::span_lint_and_sugg;
 use clippy_utils::source::snippet_with_context;
-use if_chain::if_chain;
 use rustc_errors::Applicability;
 use rustc_hir::def_id::DefId;
 use rustc_hir::{Expr, ExprKind};
@@ -25,34 +24,32 @@ fn raw_parts_kind(cx: &LateContext<'_>, did: DefId) -> Option<RawPartsKind> {
 }
 
 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_to: Ty<'_>, msrv: &Msrv) {
-    if_chain! {
-        if msrv.meets(msrvs::PTR_SLICE_RAW_PARTS);
-        if let ty::RawPtr(ptrty) = cast_to.kind();
-        if let ty::Slice(_) = ptrty.ty.kind();
-        if let ExprKind::Call(fun, [ptr_arg, len_arg]) = cast_expr.peel_blocks().kind;
-        if let ExprKind::Path(ref qpath) = fun.kind;
-        if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
-        if let Some(rpk) = raw_parts_kind(cx, fun_def_id);
-        let ctxt = expr.span.ctxt();
-        if cast_expr.span.ctxt() == ctxt;
-        then {
-            let func = match rpk {
-                RawPartsKind::Immutable => "from_raw_parts",
-                RawPartsKind::Mutable => "from_raw_parts_mut"
-            };
-            let span = expr.span;
-            let mut applicability = Applicability::MachineApplicable;
-            let ptr = snippet_with_context(cx, ptr_arg.span, ctxt, "ptr", &mut applicability).0;
-            let len = snippet_with_context(cx, len_arg.span, ctxt, "len", &mut applicability).0;
-            span_lint_and_sugg(
-                cx,
-                CAST_SLICE_FROM_RAW_PARTS,
-                span,
-                &format!("casting the result of `{func}` to {cast_to}"),
-                "replace with",
-                format!("core::ptr::slice_{func}({ptr}, {len})"),
-                applicability
-            );
-        }
+    if msrv.meets(msrvs::PTR_SLICE_RAW_PARTS)
+        && let ty::RawPtr(ptrty) = cast_to.kind()
+        && let ty::Slice(_) = ptrty.ty.kind()
+        && let ExprKind::Call(fun, [ptr_arg, len_arg]) = cast_expr.peel_blocks().kind
+        && let ExprKind::Path(ref qpath) = fun.kind
+        && let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id()
+        && let Some(rpk) = raw_parts_kind(cx, fun_def_id)
+        && let ctxt = expr.span.ctxt()
+        && cast_expr.span.ctxt() == ctxt
+    {
+        let func = match rpk {
+            RawPartsKind::Immutable => "from_raw_parts",
+            RawPartsKind::Mutable => "from_raw_parts_mut",
+        };
+        let span = expr.span;
+        let mut applicability = Applicability::MachineApplicable;
+        let ptr = snippet_with_context(cx, ptr_arg.span, ctxt, "ptr", &mut applicability).0;
+        let len = snippet_with_context(cx, len_arg.span, ctxt, "len", &mut applicability).0;
+        span_lint_and_sugg(
+            cx,
+            CAST_SLICE_FROM_RAW_PARTS,
+            span,
+            &format!("casting the result of `{func}` to {cast_to}"),
+            "replace with",
+            format!("core::ptr::slice_{func}({ptr}, {len})"),
+            applicability,
+        );
     }
 }
diff --git a/clippy_lints/src/casts/char_lit_as_u8.rs b/clippy_lints/src/casts/char_lit_as_u8.rs
index 82e07c98a7e..a7d3868f76c 100644
--- a/clippy_lints/src/casts/char_lit_as_u8.rs
+++ b/clippy_lints/src/casts/char_lit_as_u8.rs
@@ -1,6 +1,5 @@
 use clippy_utils::diagnostics::span_lint_and_then;
 use clippy_utils::source::snippet_with_applicability;
-use if_chain::if_chain;
 use rustc_ast::LitKind;
 use rustc_errors::Applicability;
 use rustc_hir::{Expr, ExprKind};
@@ -10,32 +9,31 @@ use rustc_middle::ty::{self, UintTy};
 use super::CHAR_LIT_AS_U8;
 
 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
-    if_chain! {
-        if let ExprKind::Cast(e, _) = &expr.kind;
-        if let ExprKind::Lit(l) = &e.kind;
-        if let LitKind::Char(c) = l.node;
-        if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
-        then {
-            let mut applicability = Applicability::MachineApplicable;
-            let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
+    if let ExprKind::Cast(e, _) = &expr.kind
+        && let ExprKind::Lit(l) = &e.kind
+        && let LitKind::Char(c) = l.node
+        && ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind()
+    {
+        let mut applicability = Applicability::MachineApplicable;
+        let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
 
-            span_lint_and_then(
-                cx,
-                CHAR_LIT_AS_U8,
-                expr.span,
-                "casting a character literal to `u8` truncates",
-                |diag| {
-                    diag.note("`char` is four bytes wide, but `u8` is a single byte");
+        span_lint_and_then(
+            cx,
+            CHAR_LIT_AS_U8,
+            expr.span,
+            "casting a character literal to `u8` truncates",
+            |diag| {
+                diag.note("`char` is four bytes wide, but `u8` is a single byte");
 
-                    if c.is_ascii() {
-                        diag.span_suggestion(
-                            expr.span,
-                            "use a byte literal instead",
-                            format!("b{snippet}"),
-                            applicability,
-                        );
-                    }
-            });
-        }
+                if c.is_ascii() {
+                    diag.span_suggestion(
+                        expr.span,
+                        "use a byte literal instead",
+                        format!("b{snippet}"),
+                        applicability,
+                    );
+                }
+            },
+        );
     }
 }
diff --git a/clippy_lints/src/casts/ptr_cast_constness.rs b/clippy_lints/src/casts/ptr_cast_constness.rs
index 0172e933649..ff069860a11 100644
--- a/clippy_lints/src/casts/ptr_cast_constness.rs
+++ b/clippy_lints/src/casts/ptr_cast_constness.rs
@@ -1,7 +1,6 @@
 use clippy_config::msrvs::{self, Msrv};
 use clippy_utils::diagnostics::span_lint_and_sugg;
 use clippy_utils::sugg::Sugg;
-use if_chain::if_chain;
 use rustc_errors::Applicability;
 use rustc_hir::{Expr, Mutability};
 use rustc_lint::LateContext;
@@ -17,29 +16,35 @@ pub(super) fn check<'tcx>(
     cast_to: Ty<'tcx>,
     msrv: &Msrv,
 ) {
-    if_chain! {
-        if msrv.meets(msrvs::POINTER_CAST_CONSTNESS);
-        if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, ty: from_ty }) = cast_from.kind();
-        if let ty::RawPtr(TypeAndMut { mutbl: to_mutbl, ty: to_ty }) = cast_to.kind();
-        if matches!((from_mutbl, to_mutbl),
-            (Mutability::Not, Mutability::Mut) | (Mutability::Mut, Mutability::Not));
-        if from_ty == to_ty;
-        then {
-            let sugg = Sugg::hir(cx, cast_expr, "_");
-            let constness = match *to_mutbl {
-                Mutability::Not => "const",
-                Mutability::Mut => "mut",
-            };
+    if msrv.meets(msrvs::POINTER_CAST_CONSTNESS)
+        && let ty::RawPtr(TypeAndMut {
+            mutbl: from_mutbl,
+            ty: from_ty,
+        }) = cast_from.kind()
+        && let ty::RawPtr(TypeAndMut {
+            mutbl: to_mutbl,
+            ty: to_ty,
+        }) = cast_to.kind()
+        && matches!(
+            (from_mutbl, to_mutbl),
+            (Mutability::Not, Mutability::Mut) | (Mutability::Mut, Mutability::Not)
+        )
+        && from_ty == to_ty
+    {
+        let sugg = Sugg::hir(cx, cast_expr, "_");
+        let constness = match *to_mutbl {
+            Mutability::Not => "const",
+            Mutability::Mut => "mut",
+        };
 
-            span_lint_and_sugg(
-                cx,
-                PTR_CAST_CONSTNESS,
-                expr.span,
-                "`as` casting between raw pointers while changing only its constness",
-                &format!("try `pointer::cast_{constness}`, a safer alternative"),
-                format!("{}.cast_{constness}()", sugg.maybe_par()),
-                Applicability::MachineApplicable,
-            );
-        }
+        span_lint_and_sugg(
+            cx,
+            PTR_CAST_CONSTNESS,
+            expr.span,
+            "`as` casting between raw pointers while changing only its constness",
+            &format!("try `pointer::cast_{constness}`, a safer alternative"),
+            format!("{}.cast_{constness}()", sugg.maybe_par()),
+            Applicability::MachineApplicable,
+        );
     }
 }
diff --git a/clippy_lints/src/casts/unnecessary_cast.rs b/clippy_lints/src/casts/unnecessary_cast.rs
index 61bfce07e1a..849920bb76d 100644
--- a/clippy_lints/src/casts/unnecessary_cast.rs
+++ b/clippy_lints/src/casts/unnecessary_cast.rs
@@ -3,7 +3,6 @@ use clippy_utils::numeric_literal::NumericLiteral;
 use clippy_utils::source::snippet_opt;
 use clippy_utils::visitors::{for_each_expr, Visitable};
 use clippy_utils::{get_parent_expr, get_parent_node, is_hir_ty_cfg_dependant, is_ty_alias, path_to_local};
-use if_chain::if_chain;
 use rustc_ast::{LitFloatType, LitIntType, LitKind};
 use rustc_errors::Applicability;
 use rustc_hir::def::{DefKind, Res};
@@ -25,40 +24,40 @@ pub(super) fn check<'tcx>(
 ) -> bool {
     let cast_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
 
-    if_chain! {
-        if let ty::RawPtr(..) = cast_from.kind();
+    if let ty::RawPtr(..) = cast_from.kind()
         // check both mutability and type are the same
-        if cast_from.kind() == cast_to.kind();
-        if let ExprKind::Cast(_, cast_to_hir) = expr.kind;
+        && cast_from.kind() == cast_to.kind()
+        && let ExprKind::Cast(_, cast_to_hir) = expr.kind
         // Ignore casts to e.g. type aliases and infer types
         // - p as pointer_alias
         // - p as _
-        if let TyKind::Ptr(to_pointee) = cast_to_hir.kind;
-        then {
-            match to_pointee.ty.kind {
-                // Ignore casts to pointers that are aliases or cfg dependant, e.g.
-                // - p as *const std::ffi::c_char (alias)
-                // - p as *const std::os::raw::c_char (cfg dependant)
-                TyKind::Path(qpath) => {
-                    if is_ty_alias(&qpath) || is_hir_ty_cfg_dependant(cx, to_pointee.ty) {
-                        return false;
-                    }
-                },
-                // Ignore `p as *const _`
-                TyKind::Infer => return false,
-                _ => {},
-            }
-
-            span_lint_and_sugg(
-                cx,
-                UNNECESSARY_CAST,
-                expr.span,
-                &format!("casting raw pointers to the same type and constness is unnecessary (`{cast_from}` -> `{cast_to}`)"),
-                "try",
-                cast_str.clone(),
-                Applicability::MaybeIncorrect,
-            );
+        && let TyKind::Ptr(to_pointee) = cast_to_hir.kind
+    {
+        match to_pointee.ty.kind {
+            // Ignore casts to pointers that are aliases or cfg dependant, e.g.
+            // - p as *const std::ffi::c_char (alias)
+            // - p as *const std::os::raw::c_char (cfg dependant)
+            TyKind::Path(qpath) => {
+                if is_ty_alias(&qpath) || is_hir_ty_cfg_dependant(cx, to_pointee.ty) {
+                    return false;
+                }
+            },
+            // Ignore `p as *const _`
+            TyKind::Infer => return false,
+            _ => {},
         }
+
+        span_lint_and_sugg(
+            cx,
+            UNNECESSARY_CAST,
+            expr.span,
+            &format!(
+                "casting raw pointers to the same type and constness is unnecessary (`{cast_from}` -> `{cast_to}`)"
+            ),
+            "try",
+            cast_str.clone(),
+            Applicability::MaybeIncorrect,
+        );
     }
 
     // skip cast of local that is a type alias
@@ -86,14 +85,12 @@ pub(super) fn check<'tcx>(
     }
 
     // skip cast to non-primitive type
-    if_chain! {
-        if let ExprKind::Cast(_, cast_to) = expr.kind;
-        if let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind;
-        if let Res::PrimTy(_) = path.res;
-        then {}
-        else {
-            return false;
-        }
+    if let ExprKind::Cast(_, cast_to) = expr.kind
+        && let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind
+        && let Res::PrimTy(_) = path.res
+    {
+    } else {
+        return false;
     }
 
     // skip cast of fn call that returns type alias
@@ -106,18 +103,19 @@ pub(super) fn check<'tcx>(
     if let Some(lit) = get_numeric_literal(cast_expr) {
         let literal_str = &cast_str;
 
-        if_chain! {
-            if let LitKind::Int(n, _) = lit.node;
-            if let Some(src) = snippet_opt(cx, cast_expr.span);
-            if cast_to.is_floating_point();
-            if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
-            let from_nbits = 128 - n.leading_zeros();
-            let to_nbits = fp_ty_mantissa_nbits(cast_to);
-            if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
-            then {
-                lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
-                return true
-            }
+        if let LitKind::Int(n, _) = lit.node
+            && let Some(src) = snippet_opt(cx, cast_expr.span)
+            && cast_to.is_floating_point()
+            && let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node)
+            && let from_nbits = 128 - n.leading_zeros()
+            && let to_nbits = fp_ty_mantissa_nbits(cast_to)
+            && from_nbits != 0
+            && to_nbits != 0
+            && from_nbits <= to_nbits
+            && num_lit.is_decimal()
+        {
+            lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
+            return true;
         }
 
         match lit.node {