Skip to main content

rustc_hir_typeck/
cast.rs

1//! Code for type-checking cast expressions.
2//!
3//! A cast `e as U` is valid if one of the following holds:
4//! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
5//! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
6//!    pointer_kind(`T`) = pointer_kind(`U_0`); *ptr-ptr-cast*
7//! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
8//! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
9//! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
10//! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
11//! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
12//! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
13//! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
14//! * `e` is a function pointer type and `U` has type `*T`,
15//!   while `T: Sized`; *fptr-ptr-cast*
16//! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
17//!
18//! where `&.T` and `*T` are references of either mutability,
19//! and where pointer_kind(`T`) is the kind of the unsize info
20//! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or
21//! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
22//!
23//! Note that lengths are not adjusted when casting raw slices -
24//! `T: *const [u16] as *const [u8]` creates a slice that only includes
25//! half of the original memory.
26//!
27//! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
28//! expression, `e as U2` is not necessarily so (in fact it will only be valid if
29//! `U1` coerces to `U2`).
30
31use rustc_data_structures::fx::FxHashSet;
32use rustc_errors::codes::*;
33use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
34use rustc_hir::def_id::{DefId, LocalDefId};
35use rustc_hir::{self as hir, ExprKind};
36use rustc_infer::infer::DefineOpaqueTypes;
37use rustc_infer::traits::ObligationCauseCode;
38use rustc_lint_defs::builtin::{TRIVIAL_CASTS, TRIVIAL_NUMERIC_CASTS};
39use rustc_macros::{TypeFoldable, TypeVisitable};
40use rustc_middle::mir::Mutability;
41use rustc_middle::ty::adjustment::AllowTwoPhase;
42use rustc_middle::ty::cast::CastTy;
43use rustc_middle::ty::error::TypeError;
44use rustc_middle::ty::{
45    self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, Unnormalized, VariantDef, elaborate,
46};
47use rustc_span::{DUMMY_SP, Span, bug, span_bug, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use rustc_trait_selection::traits::{self, ObligationCtxt, TraitEngine};
50use tracing::{debug, instrument};
51
52use super::FnCtxt;
53use crate::{diagnostics, type_error_struct};
54
55/// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
56/// (or rustc_hir_typeck/src/cast.rs).
57#[derive(#[automatically_derived]impl ::core::marker::Copy for CastKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CastKind {
}
#[automatically_derived]impl ::core::clone::Clone for CastKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CastKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "PtrPtrCast PtrAddrCast AddrPtrCast NumericCast EnumCast PrimIntCast U8CharCast ArrayPtrCast FnPtrPtrCast FnPtrAddrCast",
            match self {
                CastKind::PtrPtrCast => 0usize,
                CastKind::PtrAddrCast => 11usize,
                CastKind::AddrPtrCast => 23usize,
                CastKind::NumericCast => 35usize,
                CastKind::EnumCast => 47usize,
                CastKind::PrimIntCast => 56usize,
                CastKind::U8CharCast => 68usize,
                CastKind::ArrayPtrCast => 79usize,
                CastKind::FnPtrPtrCast => 92usize,
                CastKind::FnPtrAddrCast => 105usize,
            })
    }
}Debug)]
58pub enum CastKind {
59    PtrPtrCast,
60    PtrAddrCast,
61    AddrPtrCast,
62    NumericCast,
63    EnumCast,
64    PrimIntCast,
65    U8CharCast,
66    ArrayPtrCast,
67    FnPtrPtrCast,
68    FnPtrAddrCast,
69}
70
71/// Reifies a cast check to be checked once we have full type information for
72/// a function context.
73#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for CastCheck<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "CastCheck expr expr_ty expr_span cast_ty cast_span span body_def_id";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.expr, &self.expr_ty, &self.expr_span, &self.cast_ty,
                        &self.cast_span, &self.span, &&self.body_def_id];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug)]
74pub(crate) struct CastCheck<'tcx> {
75    /// The expression whose value is being casted
76    expr: &'tcx hir::Expr<'tcx>,
77    /// The source type for the cast expression
78    expr_ty: Ty<'tcx>,
79    expr_span: Span,
80    /// The target type. That is, the type we are casting to.
81    cast_ty: Ty<'tcx>,
82    cast_span: Span,
83    span: Span,
84    pub body_def_id: LocalDefId,
85}
86
87/// The kind of pointer and associated metadata (thin, length or vtable) - we
88/// only allow casts between wide pointers if their metadata have the same
89/// kind.
90#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for PointerKind<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Thin => ::core::fmt::Formatter::write_str(f, "Thin"),
            Self::VTable(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "VTable", &__self_0),
            Self::Length => ::core::fmt::Formatter::write_str(f, "Length"),
            Self::OfAlias(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OfAlias", &__self_0),
            Self::OfParam(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OfParam", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl<'tcx> ::core::marker::Copy for PointerKind<'tcx>
    {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for PointerKind<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for PointerKind<'tcx>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<&'tcx ty::List<ty::Binder<'tcx,
                ty::ExistentialPredicate<'tcx>>>>;
        let _: ::core::clone::AssertParamIsClone<ty::AliasTy<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ty::ParamTy>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    PointerKind<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for
    PointerKind<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::VTable(__self_0), Self::VTable(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OfAlias(__self_0), Self::OfAlias(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OfParam(__self_0), Self::OfParam(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl<'tcx> ::core::cmp::Eq for PointerKind<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<&'tcx ty::List<ty::Binder<'tcx,
                ty::ExistentialPredicate<'tcx>>>>;
        let _: ::core::cmp::AssertParamIsEq<ty::AliasTy<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ty::ParamTy>;
    }
}Eq, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PointerKind<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    PointerKind::Thin => {}
                    PointerKind::VTable(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    PointerKind::Length => {}
                    PointerKind::OfAlias(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    PointerKind::OfParam(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PointerKind<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        PointerKind::Thin => { PointerKind::Thin }
                        PointerKind::VTable(__binding_0) => {
                            PointerKind::VTable(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        PointerKind::Length => { PointerKind::Length }
                        PointerKind::OfAlias(__binding_0) => {
                            PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        PointerKind::OfParam(__binding_0) => {
                            PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    PointerKind::Thin => { PointerKind::Thin }
                    PointerKind::VTable(__binding_0) => {
                        PointerKind::VTable(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    PointerKind::Length => { PointerKind::Length }
                    PointerKind::OfAlias(__binding_0) => {
                        PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    PointerKind::OfParam(__binding_0) => {
                        PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable)]
91enum PointerKind<'tcx> {
92    /// No metadata attached, ie pointer to sized type or foreign type
93    Thin,
94    /// A trait object
95    VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
96    /// Slice
97    Length,
98    /// The unsize info of this projection or opaque type
99    OfAlias(ty::AliasTy<'tcx>),
100    /// The unsize info of this parameter
101    OfParam(ty::ParamTy),
102}
103
104impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
105    /// Returns the kind of unsize information of t, or None
106    /// if t is unknown.
107    fn pointer_kind(
108        &self,
109        t: Ty<'tcx>,
110        span: Span,
111    ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
112        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:112",
                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                        ::tracing_core::__macro_support::Option::Some(112u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
                                                    t, span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
113
114        let t = self.deeply_resolve_ignoring_regions(t);
115        t.error_reported()?;
116
117        if self.type_is_sized_modulo_regions(self.param_env, t) {
118            return Ok(Some(PointerKind::Thin));
119        }
120
121        let t = self.deeply_resolve_ignoring_regions_with_obligations(t);
122
123        Ok(match *t.kind() {
124            ty::Slice(_) | ty::Str => Some(PointerKind::Length),
125            ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
126            ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
127                None => Some(PointerKind::Thin),
128                Some(f) => {
129                    let field_ty = self.field_ty(span, f, args);
130                    self.pointer_kind(field_ty, span)?
131                }
132            },
133            ty::Tuple(fields) => match fields.last() {
134                None => Some(PointerKind::Thin),
135                Some(&f) => self.pointer_kind(f, span)?,
136            },
137
138            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
139
140            // Pointers to foreign types are thin, despite being unsized
141            ty::Foreign(..) => Some(PointerKind::Thin),
142            // We should really try to normalize here.
143            ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
144            ty::Param(p) => Some(PointerKind::OfParam(p)),
145            // Insufficient type information.
146            ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
147
148            ty::Bool
149            | ty::Char
150            | ty::Int(..)
151            | ty::Uint(..)
152            | ty::Float(_)
153            | ty::Array(..)
154            | ty::CoroutineWitness(..)
155            | ty::RawPtr(_, _)
156            | ty::Ref(..)
157            | ty::Pat(..)
158            | ty::FnDef(..)
159            | ty::FnPtr(..)
160            | ty::Closure(..)
161            | ty::CoroutineClosure(..)
162            | ty::Coroutine(..)
163            | ty::Adt(..)
164            | ty::Never
165            | ty::Error(_) => {
166                let guar = self
167                    .dcx()
168                    .span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0:?}` should be sized but is not?",
                t))
    })format!("`{t:?}` should be sized but is not?"));
169                return Err(guar);
170            }
171
172            // FIXME(scrabsha)
173            ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
174        })
175    }
176}
177
178#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for CastError<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ErrorGuaranteed(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ErrorGuaranteed", &__self_0),
            Self::CastToBool =>
                ::core::fmt::Formatter::write_str(f, "CastToBool"),
            Self::CastToChar =>
                ::core::fmt::Formatter::write_str(f, "CastToChar"),
            Self::DifferingKinds { src_kind: __self_0, dst_kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "DifferingKinds src_kind dst_kind", __self_0, &__self_1),
            Self::SizedUnsizedCast =>
                ::core::fmt::Formatter::write_str(f, "SizedUnsizedCast"),
            Self::IllegalCast =>
                ::core::fmt::Formatter::write_str(f, "IllegalCast"),
            Self::NeedDeref =>
                ::core::fmt::Formatter::write_str(f, "NeedDeref"),
            Self::NeedViaPtr =>
                ::core::fmt::Formatter::write_str(f, "NeedViaPtr"),
            Self::NeedViaThinPtr =>
                ::core::fmt::Formatter::write_str(f, "NeedViaThinPtr"),
            Self::NeedViaInt =>
                ::core::fmt::Formatter::write_str(f, "NeedViaInt"),
            Self::NonScalar =>
                ::core::fmt::Formatter::write_str(f, "NonScalar"),
            Self::UnknownExprPtrKind =>
                ::core::fmt::Formatter::write_str(f, "UnknownExprPtrKind"),
            Self::UnknownCastPtrKind =>
                ::core::fmt::Formatter::write_str(f, "UnknownCastPtrKind"),
            Self::CastEnumDrop =>
                ::core::fmt::Formatter::write_str(f, "CastEnumDrop"),
            Self::IntToWideCast(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "IntToWideCast", &__self_0),
            Self::ForeignNonExhaustiveAdt =>
                ::core::fmt::Formatter::write_str(f,
                    "ForeignNonExhaustiveAdt"),
            Self::PtrPtrAddingAutoTrait(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "PtrPtrAddingAutoTrait", &__self_0),
        }
    }
}Debug)]
179enum CastError<'tcx> {
180    ErrorGuaranteed(ErrorGuaranteed),
181
182    CastToBool,
183    CastToChar,
184    DifferingKinds {
185        src_kind: PointerKind<'tcx>,
186        dst_kind: PointerKind<'tcx>,
187    },
188    /// Cast of thin to wide raw ptr (e.g., `*const () as *const [u8]`).
189    SizedUnsizedCast,
190    IllegalCast,
191    NeedDeref,
192    NeedViaPtr,
193    NeedViaThinPtr,
194    NeedViaInt,
195    NonScalar,
196    UnknownExprPtrKind,
197    UnknownCastPtrKind,
198    CastEnumDrop,
199    /// Cast of int to (possibly) wide raw pointer.
200    ///
201    /// Argument is the specific name of the metadata in plain words, such as "a vtable"
202    /// or "a length". If this argument is None, then the metadata is unknown, for example,
203    /// when we're typechecking a type parameter with a ?Sized bound.
204    IntToWideCast(Option<&'static str>),
205    ForeignNonExhaustiveAdt,
206    PtrPtrAddingAutoTrait(Vec<DefId>),
207}
208
209impl From<ErrorGuaranteed> for CastError<'_> {
210    fn from(err: ErrorGuaranteed) -> Self {
211        CastError::ErrorGuaranteed(err)
212    }
213}
214
215fn make_invalid_casting_error<'a, 'tcx>(
216    span: Span,
217    expr_ty: Ty<'tcx>,
218    cast_ty: Ty<'tcx>,
219    fcx: &FnCtxt<'a, 'tcx>,
220) -> Diag<'a> {
221    {
    let mut err =
        {
            fcx.dcx().struct_span_err(span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("casting `{0}` as `{1}` is invalid",
                                    fcx.ty_to_string(expr_ty), fcx.ty_to_string(cast_ty)))
                        })).with_code(E0606)
        };
    if expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
222        fcx.dcx(),
223        span,
224        expr_ty,
225        E0606,
226        "casting `{}` as `{}` is invalid",
227        fcx.ty_to_string(expr_ty),
228        fcx.ty_to_string(cast_ty)
229    )
230}
231
232/// If a cast from `from_ty` to `to_ty` is valid, returns a `Some` containing the kind
233/// of the cast.
234///
235/// This is a helper used from clippy.
236pub fn check_cast<'tcx>(
237    tcx: TyCtxt<'tcx>,
238    param_env: ty::ParamEnv<'tcx>,
239    e: &'tcx hir::Expr<'tcx>,
240    from_ty: Ty<'tcx>,
241    to_ty: Ty<'tcx>,
242) -> Option<CastKind> {
243    let hir_id = e.hir_id;
244    let local_def_id = hir_id.owner.def_id;
245
246    let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
247    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
248    fn_ctxt.write_ty(hir_id, from_ty);
249
250    if let Ok(check) = CastCheck::new(
251        &fn_ctxt, e, from_ty, to_ty,
252        // We won't show any errors to the user, so the span is irrelevant here.
253        DUMMY_SP, DUMMY_SP,
254    ) {
255        check.do_check(&fn_ctxt).ok()
256    } else {
257        None
258    }
259}
260
261impl<'a, 'tcx> CastCheck<'tcx> {
262    pub(crate) fn new(
263        fcx: &FnCtxt<'a, 'tcx>,
264        expr: &'tcx hir::Expr<'tcx>,
265        expr_ty: Ty<'tcx>,
266        cast_ty: Ty<'tcx>,
267        cast_span: Span,
268        span: Span,
269    ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
270        let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
271        let check = CastCheck {
272            expr,
273            expr_ty,
274            expr_span,
275            cast_ty,
276            cast_span,
277            span,
278            body_def_id: fcx.body_def_id,
279        };
280
281        // For better error messages, check for some obviously unsized
282        // cases now. We do a more thorough check at the end, once
283        // inference is more completely known.
284        match cast_ty.kind() {
285            ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
286            _ => Ok(check),
287        }
288    }
289
290    fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
291        match e {
292            CastError::ErrorGuaranteed(_) => {
293                // an error has already been reported
294            }
295            CastError::NeedDeref => {
296                let mut err =
297                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
298
299                if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
300                    // get just the borrow part of the expression
301                    let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
302                    err.span_suggestion_verbose(
303                        span,
304                        "remove the unneeded borrow",
305                        "",
306                        Applicability::MachineApplicable,
307                    );
308                } else {
309                    err.span_suggestion_verbose(
310                        self.expr_span.shrink_to_lo(),
311                        "dereference the expression",
312                        "*",
313                        Applicability::MachineApplicable,
314                    );
315                }
316
317                err.emit();
318            }
319            CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
320                let mut err =
321                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
322
323                if self.cast_ty.is_integral() {
324                    if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
325                        && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
326                        && let ty::Adt(adt_def, _) = *inner_ty.kind()
327                        && adt_def.is_enum()
328                        && adt_def.is_payloadfree()
329                    {
330                        err.span_suggestion_verbose(
331                            self.expr_span.shrink_to_lo(),
332                            "try dereferencing before the cast",
333                            "*",
334                            Applicability::MaybeIncorrect,
335                        );
336                        if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
337                            err.span_suggestion_verbose(
338                                fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
339                                "add `#[derive(Copy, Clone)]` to the enum definition",
340                                "#[derive(Copy, Clone)]\n",
341                                Applicability::MaybeIncorrect,
342                            );
343                        }
344                    } else {
345                        err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cast through {0} first",
                match e {
                    CastError::NeedViaPtr => "a raw pointer",
                    CastError::NeedViaThinPtr => "a thin pointer",
                    e => {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("control flow means we should never encounter a {0:?}",
                                    e)));
                    }
                }))
    })format!(
346                            "cast through {} first",
347                            match e {
348                                CastError::NeedViaPtr => "a raw pointer",
349                                CastError::NeedViaThinPtr => "a thin pointer",
350                                e => unreachable!(
351                                    "control flow means we should never encounter a {e:?}"
352                                ),
353                            }
354                        ));
355                    }
356                }
357
358                self.try_suggest_collection_to_bool(fcx, &mut err);
359
360                err.emit();
361            }
362            CastError::NeedViaInt => {
363                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
364                    .with_help("cast through an integer first")
365                    .emit();
366            }
367            CastError::IllegalCast => {
368                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
369            }
370            CastError::DifferingKinds { src_kind, dst_kind } => {
371                let mut err =
372                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
373
374                match (src_kind, dst_kind) {
375                    (PointerKind::VTable(_), PointerKind::VTable(_)) => {
376                        err.note("the trait objects may have different vtables");
377                    }
378                    (
379                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
380                        PointerKind::OfParam(_)
381                        | PointerKind::OfAlias(_)
382                        | PointerKind::VTable(_)
383                        | PointerKind::Length,
384                    )
385                    | (
386                        PointerKind::VTable(_) | PointerKind::Length,
387                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
388                    ) => {
389                        err.note("the pointers may have different metadata");
390                    }
391                    (PointerKind::VTable(_), PointerKind::Length)
392                    | (PointerKind::Length, PointerKind::VTable(_)) => {
393                        err.note("the pointers have different metadata");
394                    }
395                    (
396                        PointerKind::Thin,
397                        PointerKind::Thin
398                        | PointerKind::VTable(_)
399                        | PointerKind::Length
400                        | PointerKind::OfParam(_)
401                        | PointerKind::OfAlias(_),
402                    )
403                    | (
404                        PointerKind::VTable(_)
405                        | PointerKind::Length
406                        | PointerKind::OfParam(_)
407                        | PointerKind::OfAlias(_),
408                        PointerKind::Thin,
409                    )
410                    | (PointerKind::Length, PointerKind::Length) => {
411                        ::rustc_span::macros::bug_impl(Some(self.span),
    format_args!("unexpected cast error: {0:?}", e), Location::caller())span_bug!(self.span, "unexpected cast error: {e:?}")
412                    }
413                }
414
415                err.emit();
416            }
417            CastError::CastToBool => {
418                let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
419                let help = if self.expr_ty.is_numeric() {
420                    diagnostics::CannotCastToBoolHelp::Numeric(
421                        self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
422                    )
423                } else {
424                    diagnostics::CannotCastToBoolHelp::Unsupported(self.span)
425                };
426                fcx.dcx().emit_err(diagnostics::CannotCastToBool {
427                    span: self.span,
428                    expr_ty,
429                    help,
430                });
431            }
432            CastError::CastToChar => {
433                let mut err = {
    let mut err =
        {
            fcx.dcx().struct_span_err(self.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("only `u8` can be cast as `char`, not `{0}`",
                                    self.expr_ty))
                        })).with_code(E0604)
        };
    if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
434                    fcx.dcx(),
435                    self.span,
436                    self.expr_ty,
437                    E0604,
438                    "only `u8` can be cast as `char`, not `{}`",
439                    self.expr_ty
440                );
441                err.span_label(self.span, "invalid cast");
442                if self.expr_ty.is_numeric() {
443                    if self.expr_ty == fcx.tcx.types.u32 {
444                        err.multipart_suggestion(
445                            "consider using `char::from_u32` instead",
446                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
                (self.expr_span.shrink_to_hi().to(self.cast_span),
                    ")".to_string())]))vec![
447                                (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
448                                (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
449                            ],
450                            Applicability::MachineApplicable,
451                        );
452                    } else if self.expr_ty == fcx.tcx.types.i8 {
453                        err.span_help(self.span, "consider casting from `u8` instead");
454                    } else {
455                        err.span_help(
456                            self.span,
457                            "consider using `char::from_u32` instead (via a `u32`)",
458                        );
459                    };
460                }
461                err.emit();
462            }
463            CastError::NonScalar => {
464                let mut err = {
    let mut err =
        {
            fcx.dcx().struct_span_err(self.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("non-primitive cast: `{0}` as `{1}`",
                                    self.expr_ty, fcx.ty_to_string(self.cast_ty)))
                        })).with_code(E0605)
        };
    if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
465                    fcx.dcx(),
466                    self.span,
467                    self.expr_ty,
468                    E0605,
469                    "non-primitive cast: `{}` as `{}`",
470                    self.expr_ty,
471                    fcx.ty_to_string(self.cast_ty)
472                );
473
474                if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
475                    && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
476                {
477                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
                snippet))
    })format!(
478                        "casting reference expression `{}` because `&` binds tighter than `as`",
479                        snippet
480                    ));
481                }
482
483                let mut sugg = None;
484                let mut sugg_mutref = false;
485                if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
486                    if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
487                        && fcx.may_coerce(
488                            Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
489                            self.cast_ty,
490                        )
491                    {
492                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
    })format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
493                    } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
494                        && expr_mutbl == Mutability::Not
495                        && mutbl == Mutability::Mut
496                        && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
497                    {
498                        sugg_mutref = true;
499                    }
500
501                    if !sugg_mutref
502                        && sugg == None
503                        && fcx.may_coerce(
504                            Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
505                            self.cast_ty,
506                        )
507                    {
508                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
509                    }
510                } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
511                    && fcx.may_coerce(
512                        Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
513                        self.cast_ty,
514                    )
515                {
516                    sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
517                }
518                if sugg_mutref {
519                    err.span_label(self.span, "invalid cast");
520                    err.span_note(self.expr_span, "this reference is immutable");
521                    err.span_note(self.cast_span, "trying to cast to a mutable reference type");
522                } else if let Some((sugg, remove_cast)) = sugg {
523                    err.span_label(self.span, "invalid cast");
524
525                    let has_parens = fcx
526                        .tcx
527                        .sess
528                        .source_map()
529                        .span_to_snippet(self.expr_span)
530                        .is_ok_and(|snip| snip.starts_with('('));
531
532                    // Very crude check to see whether the expression must be wrapped
533                    // in parentheses for the suggestion to work (issue #89497).
534                    // Can/should be extended in the future.
535                    let needs_parens =
536                        !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    hir::ExprKind::Cast(..) => true,
    _ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
537
538                    let mut suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.expr_span.shrink_to_lo(), sugg)]))vec![(self.expr_span.shrink_to_lo(), sugg)];
539                    if needs_parens {
540                        suggestion[0].1 += "(";
541                        suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
542                    }
543                    if remove_cast {
544                        suggestion.push((
545                            self.expr_span.shrink_to_hi().to(self.cast_span),
546                            String::new(),
547                        ));
548                    }
549
550                    err.multipart_suggestion(
551                        "consider borrowing the value",
552                        suggestion,
553                        Applicability::MachineApplicable,
554                    );
555                } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
    _ => false,
}matches!(
556                    self.cast_ty.kind(),
557                    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
558                ) {
559                    // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
560                    if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
561                        let ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
562                        let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
563                        if fcx
564                            .infcx
565                            .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
566                            .must_apply_modulo_regions()
567                        {
568                            let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
569                                fcx.tcx.value_path_str_with_args(def.did(), *args)
570                            } else {
571                                self.cast_ty.to_string()
572                            };
573                            err.multipart_suggestion(
574                                "consider using the `From` trait instead",
575                                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.expr_span.shrink_to_lo(),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}::from(", to_ty))
                        })),
                (self.expr_span.shrink_to_hi().to(self.cast_span),
                    ")".to_string())]))vec![
576                                    (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
577                                    (
578                                        self.expr_span.shrink_to_hi().to(self.cast_span),
579                                        ")".to_string(),
580                                    ),
581                                ],
582                                Applicability::MaybeIncorrect,
583                            );
584                        }
585                    }
586
587                    let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
588                        && adt.is_enum()
589                        && self.cast_ty.is_numeric()
590                    {
591                        (
592                            "an `as` expression can be used to convert enum types to numeric \
593                             types only if the enum type is unit-only or field-less",
594                            Some(
595                                "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
596                            ),
597                        )
598                    } else {
599                        (
600                            "an `as` expression can only be used to convert between primitive \
601                             types or to coerce to a specific trait object",
602                            None,
603                        )
604                    };
605
606                    err.span_label(self.span, msg);
607
608                    if let Some(note) = note {
609                        err.note(note);
610                    }
611                } else {
612                    err.span_label(self.span, "invalid cast");
613                }
614
615                fcx.suggest_closure_to_fn_ptr_coercion(
616                    &mut err,
617                    self.expr,
618                    self.cast_ty,
619                    self.expr_ty,
620                );
621                self.try_suggest_collection_to_bool(fcx, &mut err);
622
623                err.emit();
624            }
625            CastError::SizedUnsizedCast => {
626                let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
627                let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
628                fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer {
629                    span: self.span,
630                    expr_ty,
631                    cast_ty,
632                    teach: fcx.tcx.sess.teach(E0607),
633                });
634            }
635            CastError::IntToWideCast(known_metadata) => {
636                let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
637                let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
638                let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
639                let metadata = known_metadata.unwrap_or("type-specific metadata");
640                let known_wide = known_metadata.is_some();
641                let span = self.cast_span;
642                let param_note = (!known_wide)
643                    .then(|| match cast_ty.kind() {
644                        ty::RawPtr(pointee, _) => match pointee.kind() {
645                            ty::Param(param) => {
646                                Some(diagnostics::IntToWideParamNote { param: param.name })
647                            }
648                            _ => None,
649                        },
650                        _ => None,
651                    })
652                    .flatten();
653                fcx.dcx().emit_err(diagnostics::IntToWide {
654                    span,
655                    metadata,
656                    expr_ty,
657                    cast_ty,
658                    expr_if_nightly,
659                    known_wide,
660                    param_note,
661                });
662            }
663            CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
664                let unknown_cast_to = match e {
665                    CastError::UnknownCastPtrKind => true,
666                    CastError::UnknownExprPtrKind => false,
667                    e => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("control flow means we should never encounter a {0:?}",
                e)));
}unreachable!("control flow means we should never encounter a {e:?}"),
668                };
669                let (span, sub) = if unknown_cast_to {
670                    (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span))
671                } else {
672                    (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span))
673                };
674                fcx.dcx().emit_err(diagnostics::CastUnknownPointer {
675                    span,
676                    to: unknown_cast_to,
677                    sub,
678                });
679            }
680            CastError::CastEnumDrop => {
681                let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
682                let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
683
684                fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty });
685            }
686            CastError::ForeignNonExhaustiveAdt => {
687                make_invalid_casting_error(
688                    self.span,
689                    self.expr_ty,
690                    self.cast_ty,
691                    fcx,
692                )
693                .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
694                .emit();
695            }
696            CastError::PtrPtrAddingAutoTrait(added) => {
697                fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject {
698                    span: self.span,
699                    traits_len: added.len(),
700                    traits: {
701                        let mut traits: Vec<_> = added
702                            .into_iter()
703                            .map(|trait_did| fcx.tcx.def_path_str(trait_did))
704                            .collect();
705
706                        traits.sort();
707                        traits.into()
708                    },
709                });
710            }
711        }
712    }
713
714    fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
715        if let Err(err) = self.cast_ty.error_reported() {
716            return err;
717        }
718        if let Err(err) = self.expr_ty.error_reported() {
719            return err;
720        }
721
722        let tstr = fcx.ty_to_string(self.cast_ty);
723        let mut err = {
    let mut err =
        {
            fcx.dcx().struct_span_err(self.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("cast to unsized type: `{0}` as `{1}`",
                                    fcx.deeply_resolve_ignoring_regions(self.expr_ty), tstr))
                        })).with_code(E0620)
        };
    if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
724            fcx.dcx(),
725            self.span,
726            self.expr_ty,
727            E0620,
728            "cast to unsized type: `{}` as `{}`",
729            fcx.deeply_resolve_ignoring_regions(self.expr_ty),
730            tstr
731        );
732        match self.expr_ty.kind() {
733            ty::Ref(_, _, mt) => {
734                let mtstr = mt.prefix_str();
735                err.span_suggestion_verbose(
736                    self.cast_span.shrink_to_lo(),
737                    "consider casting to a reference instead",
738                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mtstr))
    })format!("&{mtstr}"),
739                    Applicability::MachineApplicable,
740                );
741            }
742            ty::Adt(def, ..) if def.is_box() => {
743                err.multipart_suggestion(
744                    "you can cast to a `Box` instead",
745                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.cast_span.shrink_to_lo(), "Box<".to_string()),
                (self.cast_span.shrink_to_hi(), ">".to_string())]))vec![
746                        (self.cast_span.shrink_to_lo(), "Box<".to_string()),
747                        (self.cast_span.shrink_to_hi(), ">".to_string()),
748                    ],
749                    Applicability::MachineApplicable,
750                );
751            }
752            _ => {
753                err.span_help(self.expr_span, "consider using a box or reference as appropriate");
754            }
755        }
756        err.emit_err()
757    }
758
759    fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
760        if self.is_non_trivial_ref_trait_object_upcast(fcx) {
761            return;
762        }
763
764        let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
765            (true, TRIVIAL_NUMERIC_CASTS)
766        } else {
767            (false, TRIVIAL_CASTS)
768        };
769        let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
770        let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
771        fcx.tcx.emit_node_span_lint(
772            lint,
773            self.expr.hir_id,
774            self.span,
775            diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
776        );
777    }
778
779    // A trait-object upcast from a method receiver, such as
780    // `(other as &dyn Any).downcast_ref::<u32>()`,
781    // is not trivial, because it may change the method resolution, we want to skip the lint in this case.
782    // see issue #148219
783    fn is_non_trivial_ref_trait_object_upcast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
784        if !#[allow(non_exhaustive_omitted_patterns)] match (self.expr_ty.kind(),
        self.cast_ty.kind()) {
    (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _)) if
        #[allow(non_exhaustive_omitted_patterns)] match (from_ty.kind(),
                to_ty.kind()) {
            (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if
                from_data != to_data => true,
            _ => false,
        } => true,
    _ => false,
}matches!(
785            (self.expr_ty.kind(), self.cast_ty.kind()),
786            (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _))
787                if matches!(
788                    (from_ty.kind(), to_ty.kind()),
789                    (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if from_data != to_data
790                )
791        ) {
792            return false;
793        }
794
795        let hir::Node::Expr(cast_expr) = fcx.tcx.parent_hir_node(self.expr.hir_id) else {
796            return false;
797        };
798        let hir::Node::Expr(parent) = fcx.tcx.parent_hir_node(cast_expr.hir_id) else {
799            return false;
800        };
801
802        #[allow(non_exhaustive_omitted_patterns)] match parent.kind {
    hir::ExprKind::MethodCall(_, receiver, ..) if
        receiver.hir_id == cast_expr.hir_id => true,
    _ => false,
}matches!(
803            parent.kind,
804            hir::ExprKind::MethodCall(_, receiver, ..) if receiver.hir_id == cast_expr.hir_id
805        )
806    }
807
808    fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
809        if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
810            && fcx.deeply_resolve_ignoring_regions(self.expr_ty).is_ty_var()
811            && fcx.deeply_resolve_ignoring_regions(fcx.node_ty(idx.hir_id)).is_ty_var()
812        {
813            index_operand_ambiguity_span(idx)
814        } else {
815            self.expr_span
816        }
817    }
818
819    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check",
                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                                    ::tracing_core::__macro_support::Option::Some(819u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let expr_span = self.expr_span_for_type_resolution(fcx);
            self.expr_ty =
                fcx.structurally_resolve_type(expr_span, self.expr_ty);
            self.cast_ty =
                fcx.deeply_resolve_ignoring_regions_with_obligations(self.cast_ty);
            if self.cast_ty.is_ty_var() {
                self.cast_ty =
                    if let Some(guar) =
                            self.try_report_ambiguous_binop_for_infer_cast(fcx) {
                        let err = Ty::new_error(fcx.tcx, guar);
                        fcx.demand_suptype(self.cast_span, err, self.cast_ty);
                        err
                    } else {
                        fcx.type_must_be_known_at_this_point(self.cast_span,
                            self.cast_ty)
                    };
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:834",
                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                                    ::tracing_core::__macro_support::Option::Some(834u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_cast({0}, {1:?} as {2:?})",
                                                                self.expr.hir_id, self.expr_ty, self.cast_ty) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
                    && !self.cast_ty.has_infer_types() {
                self.report_cast_to_unsized_type(fcx);
            } else if self.expr_ty.references_error() ||
                    self.cast_ty.references_error()
                {} else {
                match self.try_coercion_cast(fcx) {
                    Ok(()) => {
                        if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:852",
                                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(852u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" -> PointerCast")
                                                                        as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                        } else {
                            self.trivial_cast_lint(fcx);
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:855",
                                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(855u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" -> CoercionCast")
                                                                        as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
                        }
                    }
                    Err(_) => {
                        match self.do_check(fcx) {
                            Ok(k) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:864",
                                                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(864u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" -> {0:?}",
                                                                                    k) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                            }
                            Err(e) => self.report_cast_error(fcx, e),
                        };
                    }
                };
            }
        }
    }
}#[instrument(skip(fcx), level = "debug")]
820    pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
821        let expr_span = self.expr_span_for_type_resolution(fcx);
822        self.expr_ty = fcx.structurally_resolve_type(expr_span, self.expr_ty);
823        self.cast_ty = fcx.deeply_resolve_ignoring_regions_with_obligations(self.cast_ty);
824        if self.cast_ty.is_ty_var() {
825            self.cast_ty = if let Some(guar) = self.try_report_ambiguous_binop_for_infer_cast(fcx) {
826                let err = Ty::new_error(fcx.tcx, guar);
827                fcx.demand_suptype(self.cast_span, err, self.cast_ty);
828                err
829            } else {
830                fcx.type_must_be_known_at_this_point(self.cast_span, self.cast_ty)
831            };
832        }
833
834        debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
835
836        if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
837            && !self.cast_ty.has_infer_types()
838        {
839            self.report_cast_to_unsized_type(fcx);
840        } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
841            // No sense in giving duplicate error messages
842        } else {
843            match self.try_coercion_cast(fcx) {
844                Ok(()) => {
845                    if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
846                        // When casting a raw pointer to another raw pointer, we cannot convert the cast into
847                        // a coercion because the pointee types might only differ in regions, which HIR typeck
848                        // cannot distinguish. This would cause us to erroneously discard a cast which will
849                        // lead to a borrowck error like #113257.
850                        // We still did a coercion above to unify inference variables for `ptr as _` casts.
851                        // This does cause us to miss some trivial casts in the trivial cast lint.
852                        debug!(" -> PointerCast");
853                    } else {
854                        self.trivial_cast_lint(fcx);
855                        debug!(" -> CoercionCast");
856                        fcx.typeck_results
857                            .borrow_mut()
858                            .set_coercion_cast(self.expr.hir_id.local_id);
859                    }
860                }
861                Err(_) => {
862                    match self.do_check(fcx) {
863                        Ok(k) => {
864                            debug!(" -> {:?}", k);
865                        }
866                        Err(e) => self.report_cast_error(fcx, e),
867                    };
868                }
869            };
870        }
871    }
872
873    /// Prefer a pending operator ambiguity over a generic `as _` inference failure.
874    #[cold]
875    fn try_report_ambiguous_binop_for_infer_cast(
876        &self,
877        fcx: &FnCtxt<'a, 'tcx>,
878    ) -> Option<ErrorGuaranteed> {
879        let errors: Vec<_> = fcx
880            .fulfillment_cx
881            .borrow()
882            .pending_obligations()
883            .into_iter()
884            .filter_map(|mut obligation| {
885                let predicate = fcx.deeply_resolve_ignoring_regions(obligation.predicate);
886                if !#[allow(non_exhaustive_omitted_patterns)] match predicate.kind().skip_binder()
    {
    ty::PredicateKind::Clause(ty::ClauseKind::Trait(_)) => true,
    _ => false,
}matches!(
887                    predicate.kind().skip_binder(),
888                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(_))
889                ) {
890                    return None;
891                }
892                let cast_span = self.cast_span;
893
894                let ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. } =
895                    obligation.cause.code()
896                else {
897                    return None;
898                };
899                let lhs_ty = fcx.deeply_resolve_ignoring_regions(fcx.node_ty(*lhs_hir_id));
900                let rhs_ty = fcx.deeply_resolve_ignoring_regions(fcx.node_ty(*rhs_hir_id));
901
902                if (fcx.tcx.hir_span(*lhs_hir_id).contains(cast_span)
903                    && lhs_ty.contains(self.cast_ty))
904                    || (rhs_span.contains(cast_span) && rhs_ty.contains(self.cast_ty))
905                {
906                    obligation.cause.span = cast_span;
907                    obligation.predicate = predicate;
908
909                    let ocx = ObligationCtxt::new_with_diagnostics(&fcx.infcx);
910                    ocx.register_obligation(obligation);
911                    ocx.evaluate_obligations_error_on_ambiguity().into_iter().find(|error| {
912                        #[allow(non_exhaustive_omitted_patterns)] match error.code {
    traits::FulfillmentErrorCode::Ambiguity { overflow: None } => true,
    _ => false,
}matches!(
913                            error.code,
914                            traits::FulfillmentErrorCode::Ambiguity { overflow: None }
915                        )
916                    })
917                } else {
918                    None
919                }
920            })
921            .collect();
922
923        if errors.is_empty() {
924            None
925        } else {
926            Some(fcx.err_ctxt().report_fulfillment_errors(errors.into()))
927        }
928    }
929
930    /// Checks a cast, and report an error if one exists. In some cases, this
931    /// can return Ok and create type errors in the fcx rather than returning
932    /// directly. coercion-cast is handled in check instead of here.
933    fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
934        use rustc_middle::ty::cast::CastTy::*;
935
936        let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
937        {
938            (Some(t_from), Some(t_cast)) => (t_from, t_cast),
939            // Function item types may need to be reified before casts.
940            (None, Some(t_cast)) => {
941                match *self.expr_ty.kind() {
942                    ty::FnDef(..) => {
943                        // Attempt a coercion to a fn pointer type.
944                        let f = fcx.normalize(
945                            self.expr_span,
946                            Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
947                        );
948                        let res = fcx.coerce(
949                            self.expr,
950                            self.expr_ty,
951                            Ty::new_fn_ptr(fcx.tcx, f),
952                            AllowTwoPhase::No,
953                            None,
954                        );
955                        if let Err(TypeError::IntrinsicCast) = res {
956                            return Err(CastError::IllegalCast);
957                        }
958                        if res.is_err() {
959                            return Err(CastError::NonScalar);
960                        }
961                        (FnPtr, t_cast)
962                    }
963                    // Special case some errors for references, and check for
964                    // array-ptr-casts. `Ref` is not a CastTy because the cast
965                    // is split into a coercion to a pointer type, followed by
966                    // a cast.
967                    ty::Ref(_, inner_ty, mutbl) => {
968                        return match t_cast {
969                            Int | CEnum | Bool | Char | Float => match *inner_ty.kind() {
970                                ty::Int(_)
971                                | ty::Uint(_)
972                                | ty::Float(_)
973                                | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
974                                    Err(CastError::NeedDeref)
975                                }
976                                _ => Err(CastError::NeedViaPtr),
977                            },
978                            // array-ptr-cast
979                            Ptr(mt) => {
980                                if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
981                                    return Err(CastError::IllegalCast);
982                                }
983                                self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
984                            }
985                            _ => Err(CastError::NonScalar),
986                        };
987                    }
988                    _ => return Err(CastError::NonScalar),
989                }
990            }
991            _ => return Err(CastError::NonScalar),
992        };
993        if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
994            && !adt_def.did().is_local()
995            && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
996        {
997            return Err(CastError::ForeignNonExhaustiveAdt);
998        }
999        match (t_from, t_cast) {
1000            // These types have invariants! can't cast into them.
1001            (_, CEnum | FnPtr) => Err(CastError::NonScalar),
1002
1003            // * -> Bool
1004            (_, Bool) => Err(CastError::CastToBool),
1005
1006            // * -> Char
1007            (Int, Char) if self.expr_ty == fcx.tcx.types.u8 => {
1008                Ok(CastKind::U8CharCast) // u8-char-cast
1009            }
1010            (_, Char) => Err(CastError::CastToChar),
1011
1012            // prim -> float,ptr
1013            (Bool | CEnum | Char, Float) => Err(CastError::NeedViaInt),
1014
1015            (Bool | CEnum | Char | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
1016                Err(CastError::IllegalCast)
1017            }
1018
1019            // ptr -> ptr
1020            (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
1021
1022            // ptr-addr-cast
1023            (Ptr(m_expr), Int) => self.check_ptr_addr_cast(fcx, m_expr),
1024
1025            (FnPtr, Int) => {
1026                // FIXME(#95489): there should eventually be a lint for these casts
1027                Ok(CastKind::FnPtrAddrCast)
1028            }
1029            // addr-ptr-cast
1030            (Int, Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
1031            // fn-ptr-cast
1032            (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
1033
1034            // enum -> int
1035            (CEnum, Int) => self.check_enum_cast(fcx),
1036
1037            // prim -> prim
1038            (Char | Bool, Int) => Ok(CastKind::PrimIntCast),
1039
1040            (Int | Float, Int | Float) => Ok(CastKind::NumericCast),
1041        }
1042    }
1043
1044    fn check_ptr_ptr_cast(
1045        &self,
1046        fcx: &FnCtxt<'a, 'tcx>,
1047        m_src: ty::TypeAndMut<'tcx>,
1048        m_dst: ty::TypeAndMut<'tcx>,
1049    ) -> Result<CastKind, CastError<'tcx>> {
1050        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs:1050",
                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/cast.rs"),
                        ::tracing_core::__macro_support::Option::Some(1050u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_ptr_ptr_cast m_src={0:?} m_dst={1:?}",
                                                    m_src, m_dst) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
1051        // ptr-ptr cast. metadata must match.
1052
1053        let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
1054        let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
1055
1056        // We can't cast if target pointer kind is unknown
1057        let Some(dst_kind) = dst_kind else {
1058            return Err(CastError::UnknownCastPtrKind);
1059        };
1060
1061        // Cast to thin pointer is OK
1062        if dst_kind == PointerKind::Thin {
1063            return Ok(CastKind::PtrPtrCast);
1064        }
1065
1066        // We can't cast to wide pointer if source pointer kind is unknown
1067        let Some(src_kind) = src_kind else {
1068            return Err(CastError::UnknownCastPtrKind);
1069        };
1070
1071        match (src_kind, dst_kind) {
1072            // thin -> fat? report invalid cast (don't complain about vtable kinds)
1073            (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
1074
1075            // trait object -> trait object? need to do additional checks
1076            (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
1077                match (src_tty.principal(), dst_tty.principal()) {
1078                    // A<dyn Src<...> + SrcAuto> -> B<dyn Dst<...> + DstAuto>. need to make sure
1079                    // - `Src` and `Dst` traits are the same
1080                    // - traits have the same generic arguments
1081                    // - projections are the same
1082                    // - `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`
1083                    //
1084                    // Note that trait upcasting goes through a different mechanism (`coerce_unsized`)
1085                    // and is unaffected by this check.
1086                    (Some(src_principal), Some(_)) => {
1087                        let tcx = fcx.tcx;
1088
1089                        // We need to reconstruct trait object types.
1090                        // `m_src` and `m_dst` won't work for us here because they will potentially
1091                        // contain wrappers, which we do not care about.
1092                        //
1093                        // e.g. we want to allow `dyn T -> (dyn T,)`, etc.
1094                        //
1095                        // We also need to skip auto traits to emit an FCW and not an error.
1096                        let src_obj = Ty::new_dynamic(
1097                            tcx,
1098                            tcx.mk_poly_existential_predicates(
1099                                &src_tty.without_auto_traits().collect::<Vec<_>>(),
1100                            ),
1101                            tcx.lifetimes.re_erased,
1102                        );
1103                        let dst_obj = Ty::new_dynamic(
1104                            tcx,
1105                            tcx.mk_poly_existential_predicates(
1106                                &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1107                            ),
1108                            tcx.lifetimes.re_erased,
1109                        );
1110
1111                        // `dyn Src = dyn Dst`, this checks for matching traits/generics/projections
1112                        // This is `fcx.demand_eqtype`, but inlined to give a better error.
1113                        let cause = fcx.misc(self.span);
1114                        if fcx
1115                            .at(&cause, fcx.param_env)
1116                            .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
1117                            .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
1118                            .is_err()
1119                        {
1120                            return Err(CastError::DifferingKinds { src_kind, dst_kind });
1121                        }
1122
1123                        // Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`.
1124                        // Emit an FCW otherwise.
1125                        let src_auto: FxHashSet<_> = src_tty
1126                            .auto_traits()
1127                            .chain(
1128                                elaborate::supertrait_def_ids(tcx, src_principal.def_id())
1129                                    .filter(|def_id| tcx.trait_is_auto(*def_id)),
1130                            )
1131                            .collect();
1132
1133                        let added = dst_tty
1134                            .auto_traits()
1135                            .filter(|trait_did| !src_auto.contains(trait_did))
1136                            .collect::<Vec<_>>();
1137
1138                        if !added.is_empty() {
1139                            return Err(CastError::PtrPtrAddingAutoTrait(added));
1140                        }
1141
1142                        Ok(CastKind::PtrPtrCast)
1143                    }
1144
1145                    // dyn Auto -> dyn Auto'? ok.
1146                    (None, None) => Ok(CastKind::PtrPtrCast),
1147
1148                    // dyn Trait -> dyn Auto? not ok (for now).
1149                    //
1150                    // Although dropping the principal is already allowed for unsizing coercions
1151                    // (e.g. `*const (dyn Trait + Auto)` to `*const dyn Auto`), dropping it is
1152                    // currently **NOT** allowed for (non-coercion) ptr-to-ptr casts (e.g
1153                    // `*const Foo` to `*const Bar` where `Foo` has a `dyn Trait + Auto` tail
1154                    // and `Bar` has a `dyn Auto` tail), because the underlying MIR operations
1155                    // currently work very differently:
1156                    //
1157                    // * A MIR unsizing coercion on raw pointers to trait objects (`*const dyn Src`
1158                    //   to `*const dyn Dst`) is currently equivalent to downcasting the source to
1159                    //   the concrete sized type that it was originally unsized from first (via a
1160                    //   ptr-to-ptr cast from `*const Src` to `*const T` with `T: Sized`) and then
1161                    //   unsizing this thin pointer to the target type (unsizing `*const T` to
1162                    //   `*const Dst`). In particular, this means that the pointer's metadata
1163                    //   (vtable) will semantically change, e.g. for const eval and miri, even
1164                    //   though the vtables will always be merged for codegen.
1165                    //
1166                    // * A MIR ptr-to-ptr cast is currently equivalent to a transmute and does not
1167                    //   change the pointer metadata (vtable) at all.
1168                    //
1169                    // In addition to this potentially surprising difference between coercion and
1170                    // non-coercion casts, casting away the principal with a MIR ptr-to-ptr cast
1171                    // is currently considered undefined behavior:
1172                    //
1173                    // As a validity invariant of pointers to trait objects, we currently require
1174                    // that the principal of the vtable in the pointer metadata exactly matches
1175                    // the principal of the pointee type, where "no principal" is also considered
1176                    // a kind of principal.
1177                    (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1178
1179                    // dyn Auto -> dyn Trait? not ok.
1180                    (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1181                }
1182            }
1183
1184            // fat -> fat? metadata kinds must match
1185            (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1186
1187            (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1188        }
1189    }
1190
1191    fn check_fptr_ptr_cast(
1192        &self,
1193        fcx: &FnCtxt<'a, 'tcx>,
1194        m_cast: ty::TypeAndMut<'tcx>,
1195    ) -> Result<CastKind, CastError<'tcx>> {
1196        // fptr-ptr cast. must be to thin ptr
1197
1198        match fcx.pointer_kind(m_cast.ty, self.span)? {
1199            None => Err(CastError::UnknownCastPtrKind),
1200            Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1201            _ => Err(CastError::IllegalCast),
1202        }
1203    }
1204
1205    fn check_ptr_addr_cast(
1206        &self,
1207        fcx: &FnCtxt<'a, 'tcx>,
1208        m_expr: ty::TypeAndMut<'tcx>,
1209    ) -> Result<CastKind, CastError<'tcx>> {
1210        // ptr-addr cast. must be from thin ptr
1211
1212        match fcx.pointer_kind(m_expr.ty, self.span)? {
1213            None => Err(CastError::UnknownExprPtrKind),
1214            Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1215            _ => Err(CastError::NeedViaThinPtr),
1216        }
1217    }
1218
1219    fn check_ref_cast(
1220        &self,
1221        fcx: &FnCtxt<'a, 'tcx>,
1222        mut m_expr: ty::TypeAndMut<'tcx>,
1223        mut m_cast: ty::TypeAndMut<'tcx>,
1224    ) -> Result<CastKind, CastError<'tcx>> {
1225        // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1226        m_expr.ty = fcx.deeply_resolve_ignoring_regions_with_obligations(m_expr.ty);
1227        m_cast.ty = fcx.deeply_resolve_ignoring_regions_with_obligations(m_cast.ty);
1228
1229        if m_expr.mutbl >= m_cast.mutbl
1230            && let ty::Array(ety, _) = m_expr.ty.kind()
1231            && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1232        {
1233            // Due to historical reasons we allow directly casting references of
1234            // arrays into raw pointers of their element type.
1235
1236            // Coerce to a raw pointer so that we generate RawPtr in MIR.
1237            let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1238            fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1239                .unwrap_or_else(|_| {
1240                    ::rustc_span::macros::bug_impl(None,
    format_args!("could not cast from reference to array to pointer to array ({0:?} to {1:?})",
        self.expr_ty, array_ptr_type), Location::caller())bug!(
1241                        "could not cast from reference to array to pointer to array ({:?} to {:?})",
1242                        self.expr_ty,
1243                        array_ptr_type,
1244                    )
1245                });
1246
1247            // this will report a type mismatch if needed
1248            fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1249            return Ok(CastKind::ArrayPtrCast);
1250        }
1251
1252        Err(CastError::IllegalCast)
1253    }
1254
1255    fn check_addr_ptr_cast(
1256        &self,
1257        fcx: &FnCtxt<'a, 'tcx>,
1258        m_cast: TypeAndMut<'tcx>,
1259    ) -> Result<CastKind, CastError<'tcx>> {
1260        // ptr-addr cast. pointer must be thin.
1261        match fcx.pointer_kind(m_cast.ty, self.span)? {
1262            None => Err(CastError::UnknownCastPtrKind),
1263            Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1264            Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1265            Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1266            Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1267                Err(CastError::IntToWideCast(None))
1268            }
1269        }
1270    }
1271
1272    fn check_enum_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
1273        if let ty::Adt(d, _) = self.expr_ty.kind()
1274            && d.has_dtor(fcx.tcx)
1275        {
1276            Err(CastError::CastEnumDrop)
1277        } else {
1278            Ok(CastKind::EnumCast)
1279        }
1280    }
1281
1282    fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1283        match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1284            Ok(_) => Ok(()),
1285            Err(err) => Err(err),
1286        }
1287    }
1288
1289    /// Attempt to suggest using `.is_empty` when trying to cast from a
1290    /// collection type to a boolean.
1291    fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1292        if self.cast_ty.is_bool() {
1293            let derefed = fcx
1294                .autoderef(self.expr_span, self.expr_ty)
1295                .silence_errors()
1296                .find(|t| #[allow(non_exhaustive_omitted_patterns)] match t.0.kind() {
    ty::Str | ty::Slice(..) => true,
    _ => false,
}matches!(t.0.kind(), ty::Str | ty::Slice(..)));
1297
1298            if let Some((deref_ty, _)) = derefed {
1299                // Give a note about what the expr derefs to.
1300                if deref_ty != self.expr_ty.peel_refs() {
1301                    err.subdiagnostic(diagnostics::DerefImplsIsEmpty {
1302                        span: self.expr_span,
1303                        deref_ty,
1304                    });
1305                }
1306
1307                // Create a multipart suggestion: add `!` and `.is_empty()` in
1308                // place of the cast.
1309                err.subdiagnostic(diagnostics::UseIsEmpty {
1310                    lo: self.expr_span.shrink_to_lo(),
1311                    hi: self.span.with_lo(self.expr_span.hi()),
1312                    expr_ty: self.expr_ty,
1313                });
1314            }
1315        }
1316    }
1317}
1318
1319fn index_operand_ambiguity_span(expr: &hir::Expr<'_>) -> Span {
1320    match expr.kind {
1321        hir::ExprKind::MethodCall(segment, ..) => segment.ident.span,
1322        _ => expr.span,
1323    }
1324}