]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/ptr_as_ptr.rs
Fix FN in `iter_cloned_collect` with a large array
[rust.git] / clippy_lints / src / casts / ptr_as_ptr.rs
1 use std::borrow::Cow;
2
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::meets_msrv;
5 use clippy_utils::sugg::Sugg;
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{Expr, ExprKind, Mutability, TyKind};
9 use rustc_lint::LateContext;
10 use rustc_middle::ty::{self, TypeAndMut};
11 use rustc_semver::RustcVersion;
12
13 use super::PTR_AS_PTR;
14
15 const PTR_AS_PTR_MSRV: RustcVersion = RustcVersion::new(1, 38, 0);
16
17 pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: &Option<RustcVersion>) {
18     if !meets_msrv(msrv.as_ref(), &PTR_AS_PTR_MSRV) {
19         return;
20     }
21
22     if_chain! {
23         if let ExprKind::Cast(cast_expr, cast_to_hir_ty) = expr.kind;
24         let (cast_from, cast_to) = (cx.typeck_results().expr_ty(cast_expr), cx.typeck_results().expr_ty(expr));
25         if let ty::RawPtr(TypeAndMut { mutbl: from_mutbl, .. }) = cast_from.kind();
26         if let ty::RawPtr(TypeAndMut { ty: to_pointee_ty, mutbl: to_mutbl }) = cast_to.kind();
27         if matches!((from_mutbl, to_mutbl),
28             (Mutability::Not, Mutability::Not) | (Mutability::Mut, Mutability::Mut));
29         // The `U` in `pointer::cast` have to be `Sized`
30         // as explained here: https://github.com/rust-lang/rust/issues/60602.
31         if to_pointee_ty.is_sized(cx.tcx.at(expr.span), cx.param_env);
32         then {
33             let mut applicability = Applicability::MachineApplicable;
34             let cast_expr_sugg = Sugg::hir_with_applicability(cx, cast_expr, "_", &mut applicability);
35             let turbofish = match &cast_to_hir_ty.kind {
36                     TyKind::Infer => Cow::Borrowed(""),
37                     TyKind::Ptr(mut_ty) if matches!(mut_ty.ty.kind, TyKind::Infer) => Cow::Borrowed(""),
38                     _ => Cow::Owned(format!("::<{}>", to_pointee_ty)),
39                 };
40             span_lint_and_sugg(
41                 cx,
42                 PTR_AS_PTR,
43                 expr.span,
44                 "`as` casting between raw pointers without changing its mutability",
45                 "try `pointer::cast`, a safer alternative",
46                 format!("{}.cast{}()", cast_expr_sugg.maybe_par(), turbofish),
47                 applicability,
48             );
49         }
50     }
51 }