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_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::mir::Mutability;
39use rustc_middle::ty::adjustment::AllowTwoPhase;
40use rustc_middle::ty::cast::{CastKind, CastTy};
41use rustc_middle::ty::error::TypeError;
42use rustc_middle::ty::{
43    self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, Unnormalized, VariantDef, elaborate,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::lint;
47use rustc_span::{DUMMY_SP, Span, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use tracing::{debug, instrument};
50
51use super::FnCtxt;
52use crate::{errors, type_error_struct};
53
54/// Reifies a cast check to be checked once we have full type information for
55/// a function context.
56#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CastCheck<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["expr", "expr_ty", "expr_span", "cast_ty", "cast_span", "span",
                        "body_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_id];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "CastCheck",
            names, values)
    }
}Debug)]
57pub(crate) struct CastCheck<'tcx> {
58    /// The expression whose value is being casted
59    expr: &'tcx hir::Expr<'tcx>,
60    /// The source type for the cast expression
61    expr_ty: Ty<'tcx>,
62    expr_span: Span,
63    /// The target type. That is, the type we are casting to.
64    cast_ty: Ty<'tcx>,
65    cast_span: Span,
66    span: Span,
67    pub body_id: LocalDefId,
68}
69
70/// The kind of pointer and associated metadata (thin, length or vtable) - we
71/// only allow casts between wide pointers if their metadata have the same
72/// kind.
73#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PointerKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PointerKind::Thin => ::core::fmt::Formatter::write_str(f, "Thin"),
            PointerKind::VTable(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "VTable",
                    &__self_0),
            PointerKind::Length =>
                ::core::fmt::Formatter::write_str(f, "Length"),
            PointerKind::OfAlias(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "OfAlias", &__self_0),
            PointerKind::OfParam(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "OfParam", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PointerKind<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for PointerKind<'tcx> {
    #[inline]
    fn clone(&self) -> PointerKind<'tcx> {
        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::cmp::PartialEq for PointerKind<'tcx> {
    #[inline]
    fn eq(&self, other: &PointerKind<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PointerKind::VTable(__self_0), PointerKind::VTable(__arg1_0))
                    => __self_0 == __arg1_0,
                (PointerKind::OfAlias(__self_0),
                    PointerKind::OfAlias(__arg1_0)) => __self_0 == __arg1_0,
                (PointerKind::OfParam(__self_0),
                    PointerKind::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)]
74enum PointerKind<'tcx> {
75    /// No metadata attached, ie pointer to sized type or foreign type
76    Thin,
77    /// A trait object
78    VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
79    /// Slice
80    Length,
81    /// The unsize info of this projection or opaque type
82    OfAlias(ty::AliasTy<'tcx>),
83    /// The unsize info of this parameter
84    OfParam(ty::ParamTy),
85}
86
87impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
88    /// Returns the kind of unsize information of t, or None
89    /// if t is unknown.
90    fn pointer_kind(
91        &self,
92        t: Ty<'tcx>,
93        span: Span,
94    ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
95        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:95",
                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                        ::tracing_core::__macro_support::Option::Some(95u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
                                                    t, span) as &dyn Value))])
            });
    } else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
96
97        let t = self.resolve_vars_if_possible(t);
98        t.error_reported()?;
99
100        if self.type_is_sized_modulo_regions(self.param_env, t) {
101            return Ok(Some(PointerKind::Thin));
102        }
103
104        let t = self.resolve_vars_with_obligations(t);
105
106        Ok(match *t.kind() {
107            ty::Slice(_) | ty::Str => Some(PointerKind::Length),
108            ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
109            ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
110                None => Some(PointerKind::Thin),
111                Some(f) => {
112                    let field_ty = self.field_ty(span, f, args);
113                    self.pointer_kind(field_ty, span)?
114                }
115            },
116            ty::Tuple(fields) => match fields.last() {
117                None => Some(PointerKind::Thin),
118                Some(&f) => self.pointer_kind(f, span)?,
119            },
120
121            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
122
123            // Pointers to foreign types are thin, despite being unsized
124            ty::Foreign(..) => Some(PointerKind::Thin),
125            // We should really try to normalize here.
126            ty::Alias(pi) => Some(PointerKind::OfAlias(pi)),
127            ty::Param(p) => Some(PointerKind::OfParam(p)),
128            // Insufficient type information.
129            ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
130
131            ty::Bool
132            | ty::Char
133            | ty::Int(..)
134            | ty::Uint(..)
135            | ty::Float(_)
136            | ty::Array(..)
137            | ty::CoroutineWitness(..)
138            | ty::RawPtr(_, _)
139            | ty::Ref(..)
140            | ty::Pat(..)
141            | ty::FnDef(..)
142            | ty::FnPtr(..)
143            | ty::Closure(..)
144            | ty::CoroutineClosure(..)
145            | ty::Coroutine(..)
146            | ty::Adt(..)
147            | ty::Never
148            | ty::Error(_) => {
149                let guar = self
150                    .dcx()
151                    .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?"));
152                return Err(guar);
153            }
154        })
155    }
156}
157
158#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CastError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            CastError::ErrorGuaranteed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ErrorGuaranteed", &__self_0),
            CastError::CastToBool =>
                ::core::fmt::Formatter::write_str(f, "CastToBool"),
            CastError::CastToChar =>
                ::core::fmt::Formatter::write_str(f, "CastToChar"),
            CastError::DifferingKinds { src_kind: __self_0, dst_kind: __self_1
                } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "DifferingKinds", "src_kind", __self_0, "dst_kind",
                    &__self_1),
            CastError::SizedUnsizedCast =>
                ::core::fmt::Formatter::write_str(f, "SizedUnsizedCast"),
            CastError::IllegalCast =>
                ::core::fmt::Formatter::write_str(f, "IllegalCast"),
            CastError::NeedDeref =>
                ::core::fmt::Formatter::write_str(f, "NeedDeref"),
            CastError::NeedViaPtr =>
                ::core::fmt::Formatter::write_str(f, "NeedViaPtr"),
            CastError::NeedViaThinPtr =>
                ::core::fmt::Formatter::write_str(f, "NeedViaThinPtr"),
            CastError::NeedViaInt =>
                ::core::fmt::Formatter::write_str(f, "NeedViaInt"),
            CastError::NonScalar =>
                ::core::fmt::Formatter::write_str(f, "NonScalar"),
            CastError::UnknownExprPtrKind =>
                ::core::fmt::Formatter::write_str(f, "UnknownExprPtrKind"),
            CastError::UnknownCastPtrKind =>
                ::core::fmt::Formatter::write_str(f, "UnknownCastPtrKind"),
            CastError::IntToWideCast(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IntToWideCast", &__self_0),
            CastError::ForeignNonExhaustiveAdt =>
                ::core::fmt::Formatter::write_str(f,
                    "ForeignNonExhaustiveAdt"),
            CastError::PtrPtrAddingAutoTrait(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PtrPtrAddingAutoTrait", &__self_0),
        }
    }
}Debug)]
159enum CastError<'tcx> {
160    ErrorGuaranteed(ErrorGuaranteed),
161
162    CastToBool,
163    CastToChar,
164    DifferingKinds {
165        src_kind: PointerKind<'tcx>,
166        dst_kind: PointerKind<'tcx>,
167    },
168    /// Cast of thin to wide raw ptr (e.g., `*const () as *const [u8]`).
169    SizedUnsizedCast,
170    IllegalCast,
171    NeedDeref,
172    NeedViaPtr,
173    NeedViaThinPtr,
174    NeedViaInt,
175    NonScalar,
176    UnknownExprPtrKind,
177    UnknownCastPtrKind,
178    /// Cast of int to (possibly) wide raw pointer.
179    ///
180    /// Argument is the specific name of the metadata in plain words, such as "a vtable"
181    /// or "a length". If this argument is None, then the metadata is unknown, for example,
182    /// when we're typechecking a type parameter with a ?Sized bound.
183    IntToWideCast(Option<&'static str>),
184    ForeignNonExhaustiveAdt,
185    PtrPtrAddingAutoTrait(Vec<DefId>),
186}
187
188impl From<ErrorGuaranteed> for CastError<'_> {
189    fn from(err: ErrorGuaranteed) -> Self {
190        CastError::ErrorGuaranteed(err)
191    }
192}
193
194fn make_invalid_casting_error<'a, 'tcx>(
195    span: Span,
196    expr_ty: Ty<'tcx>,
197    cast_ty: Ty<'tcx>,
198    fcx: &FnCtxt<'a, 'tcx>,
199) -> Diag<'a> {
200    {
    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!(
201        fcx.dcx(),
202        span,
203        expr_ty,
204        E0606,
205        "casting `{}` as `{}` is invalid",
206        fcx.ty_to_string(expr_ty),
207        fcx.ty_to_string(cast_ty)
208    )
209}
210
211/// If a cast from `from_ty` to `to_ty` is valid, returns a `Some` containing the kind
212/// of the cast.
213///
214/// This is a helper used from clippy.
215pub fn check_cast<'tcx>(
216    tcx: TyCtxt<'tcx>,
217    param_env: ty::ParamEnv<'tcx>,
218    e: &'tcx hir::Expr<'tcx>,
219    from_ty: Ty<'tcx>,
220    to_ty: Ty<'tcx>,
221) -> Option<CastKind> {
222    let hir_id = e.hir_id;
223    let local_def_id = hir_id.owner.def_id;
224
225    let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
226    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
227
228    if let Ok(check) = CastCheck::new(
229        &fn_ctxt, e, from_ty, to_ty,
230        // We won't show any errors to the user, so the span is irrelevant here.
231        DUMMY_SP, DUMMY_SP,
232    ) {
233        check.do_check(&fn_ctxt).ok()
234    } else {
235        None
236    }
237}
238
239impl<'a, 'tcx> CastCheck<'tcx> {
240    pub(crate) fn new(
241        fcx: &FnCtxt<'a, 'tcx>,
242        expr: &'tcx hir::Expr<'tcx>,
243        expr_ty: Ty<'tcx>,
244        cast_ty: Ty<'tcx>,
245        cast_span: Span,
246        span: Span,
247    ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
248        let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
249        let check =
250            CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span, body_id: fcx.body_id };
251
252        // For better error messages, check for some obviously unsized
253        // cases now. We do a more thorough check at the end, once
254        // inference is more completely known.
255        match cast_ty.kind() {
256            ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
257            _ => Ok(check),
258        }
259    }
260
261    fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
262        match e {
263            CastError::ErrorGuaranteed(_) => {
264                // an error has already been reported
265            }
266            CastError::NeedDeref => {
267                let mut err =
268                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
269
270                if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
271                    // get just the borrow part of the expression
272                    let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
273                    err.span_suggestion_verbose(
274                        span,
275                        "remove the unneeded borrow",
276                        "",
277                        Applicability::MachineApplicable,
278                    );
279                } else {
280                    err.span_suggestion_verbose(
281                        self.expr_span.shrink_to_lo(),
282                        "dereference the expression",
283                        "*",
284                        Applicability::MachineApplicable,
285                    );
286                }
287
288                err.emit();
289            }
290            CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
291                let mut err =
292                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
293
294                if self.cast_ty.is_integral() {
295                    if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
296                        && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
297                        && let ty::Adt(adt_def, _) = *inner_ty.kind()
298                        && adt_def.is_enum()
299                        && adt_def.is_payloadfree()
300                    {
301                        err.span_suggestion_verbose(
302                            self.expr_span.shrink_to_lo(),
303                            "try dereferencing before the cast",
304                            "*",
305                            Applicability::MaybeIncorrect,
306                        );
307                        if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
308                            err.span_suggestion_verbose(
309                                fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
310                                "add `#[derive(Copy, Clone)]` to the enum definition",
311                                "#[derive(Copy, Clone)]\n",
312                                Applicability::MaybeIncorrect,
313                            );
314                        }
315                    } else {
316                        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!(
317                            "cast through {} first",
318                            match e {
319                                CastError::NeedViaPtr => "a raw pointer",
320                                CastError::NeedViaThinPtr => "a thin pointer",
321                                e => unreachable!(
322                                    "control flow means we should never encounter a {e:?}"
323                                ),
324                            }
325                        ));
326                    }
327                }
328
329                self.try_suggest_collection_to_bool(fcx, &mut err);
330
331                err.emit();
332            }
333            CastError::NeedViaInt => {
334                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
335                    .with_help("cast through an integer first")
336                    .emit();
337            }
338            CastError::IllegalCast => {
339                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
340            }
341            CastError::DifferingKinds { src_kind, dst_kind } => {
342                let mut err =
343                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
344
345                match (src_kind, dst_kind) {
346                    (PointerKind::VTable(_), PointerKind::VTable(_)) => {
347                        err.note("the trait objects may have different vtables");
348                    }
349                    (
350                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
351                        PointerKind::OfParam(_)
352                        | PointerKind::OfAlias(_)
353                        | PointerKind::VTable(_)
354                        | PointerKind::Length,
355                    )
356                    | (
357                        PointerKind::VTable(_) | PointerKind::Length,
358                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
359                    ) => {
360                        err.note("the pointers may have different metadata");
361                    }
362                    (PointerKind::VTable(_), PointerKind::Length)
363                    | (PointerKind::Length, PointerKind::VTable(_)) => {
364                        err.note("the pointers have different metadata");
365                    }
366                    (
367                        PointerKind::Thin,
368                        PointerKind::Thin
369                        | PointerKind::VTable(_)
370                        | PointerKind::Length
371                        | PointerKind::OfParam(_)
372                        | PointerKind::OfAlias(_),
373                    )
374                    | (
375                        PointerKind::VTable(_)
376                        | PointerKind::Length
377                        | PointerKind::OfParam(_)
378                        | PointerKind::OfAlias(_),
379                        PointerKind::Thin,
380                    )
381                    | (PointerKind::Length, PointerKind::Length) => {
382                        ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("unexpected cast error: {0:?}", e))span_bug!(self.span, "unexpected cast error: {e:?}")
383                    }
384                }
385
386                err.emit();
387            }
388            CastError::CastToBool => {
389                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
390                let help = if self.expr_ty.is_numeric() {
391                    errors::CannotCastToBoolHelp::Numeric(
392                        self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
393                    )
394                } else {
395                    errors::CannotCastToBoolHelp::Unsupported(self.span)
396                };
397                fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help });
398            }
399            CastError::CastToChar => {
400                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!(
401                    fcx.dcx(),
402                    self.span,
403                    self.expr_ty,
404                    E0604,
405                    "only `u8` can be cast as `char`, not `{}`",
406                    self.expr_ty
407                );
408                err.span_label(self.span, "invalid cast");
409                if self.expr_ty.is_numeric() {
410                    if self.expr_ty == fcx.tcx.types.u32 {
411                        err.multipart_suggestion(
412                            "consider using `char::from_u32` instead",
413                            ::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![
414                                (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
415                                (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
416                            ],
417                            Applicability::MachineApplicable,
418                        );
419                    } else if self.expr_ty == fcx.tcx.types.i8 {
420                        err.span_help(self.span, "consider casting from `u8` instead");
421                    } else {
422                        err.span_help(
423                            self.span,
424                            "consider using `char::from_u32` instead (via a `u32`)",
425                        );
426                    };
427                }
428                err.emit();
429            }
430            CastError::NonScalar => {
431                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!(
432                    fcx.dcx(),
433                    self.span,
434                    self.expr_ty,
435                    E0605,
436                    "non-primitive cast: `{}` as `{}`",
437                    self.expr_ty,
438                    fcx.ty_to_string(self.cast_ty)
439                );
440
441                if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
442                    && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
443                {
444                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
                snippet))
    })format!(
445                        "casting reference expression `{}` because `&` binds tighter than `as`",
446                        snippet
447                    ));
448                }
449
450                let mut sugg = None;
451                let mut sugg_mutref = false;
452                if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
453                    if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
454                        && fcx.may_coerce(
455                            Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
456                            self.cast_ty,
457                        )
458                    {
459                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
    })format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
460                    } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
461                        && expr_mutbl == Mutability::Not
462                        && mutbl == Mutability::Mut
463                        && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
464                    {
465                        sugg_mutref = true;
466                    }
467
468                    if !sugg_mutref
469                        && sugg == None
470                        && fcx.may_coerce(
471                            Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
472                            self.cast_ty,
473                        )
474                    {
475                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
476                    }
477                } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
478                    && fcx.may_coerce(
479                        Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
480                        self.cast_ty,
481                    )
482                {
483                    sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
484                }
485                if sugg_mutref {
486                    err.span_label(self.span, "invalid cast");
487                    err.span_note(self.expr_span, "this reference is immutable");
488                    err.span_note(self.cast_span, "trying to cast to a mutable reference type");
489                } else if let Some((sugg, remove_cast)) = sugg {
490                    err.span_label(self.span, "invalid cast");
491
492                    let has_parens = fcx
493                        .tcx
494                        .sess
495                        .source_map()
496                        .span_to_snippet(self.expr_span)
497                        .is_ok_and(|snip| snip.starts_with('('));
498
499                    // Very crude check to see whether the expression must be wrapped
500                    // in parentheses for the suggestion to work (issue #89497).
501                    // Can/should be extended in the future.
502                    let needs_parens =
503                        !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    hir::ExprKind::Cast(..) => true,
    _ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
504
505                    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)];
506                    if needs_parens {
507                        suggestion[0].1 += "(";
508                        suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
509                    }
510                    if remove_cast {
511                        suggestion.push((
512                            self.expr_span.shrink_to_hi().to(self.cast_span),
513                            String::new(),
514                        ));
515                    }
516
517                    err.multipart_suggestion(
518                        "consider borrowing the value",
519                        suggestion,
520                        Applicability::MachineApplicable,
521                    );
522                } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
    _ => false,
}matches!(
523                    self.cast_ty.kind(),
524                    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
525                ) {
526                    // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
527                    if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
528                        let ty = fcx.resolve_vars_if_possible(self.cast_ty);
529                        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
530                        if fcx
531                            .infcx
532                            .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
533                            .must_apply_modulo_regions()
534                        {
535                            let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
536                                fcx.tcx.value_path_str_with_args(def.did(), args)
537                            } else {
538                                self.cast_ty.to_string()
539                            };
540                            err.multipart_suggestion(
541                                "consider using the `From` trait instead",
542                                ::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![
543                                    (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
544                                    (
545                                        self.expr_span.shrink_to_hi().to(self.cast_span),
546                                        ")".to_string(),
547                                    ),
548                                ],
549                                Applicability::MaybeIncorrect,
550                            );
551                        }
552                    }
553
554                    let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
555                        && adt.is_enum()
556                        && self.cast_ty.is_numeric()
557                    {
558                        (
559                            "an `as` expression can be used to convert enum types to numeric \
560                             types only if the enum type is unit-only or field-less",
561                            Some(
562                                "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
563                            ),
564                        )
565                    } else {
566                        (
567                            "an `as` expression can only be used to convert between primitive \
568                             types or to coerce to a specific trait object",
569                            None,
570                        )
571                    };
572
573                    err.span_label(self.span, msg);
574
575                    if let Some(note) = note {
576                        err.note(note);
577                    }
578                } else {
579                    err.span_label(self.span, "invalid cast");
580                }
581
582                fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
583                self.try_suggest_collection_to_bool(fcx, &mut err);
584
585                err.emit();
586            }
587            CastError::SizedUnsizedCast => {
588                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
589                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
590                fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
591                    span: self.span,
592                    expr_ty,
593                    cast_ty,
594                    teach: fcx.tcx.sess.teach(E0607),
595                });
596            }
597            CastError::IntToWideCast(known_metadata) => {
598                let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
599                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
600                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
601                let metadata = known_metadata.unwrap_or("type-specific metadata");
602                let known_wide = known_metadata.is_some();
603                let span = self.cast_span;
604                let param_note = (!known_wide)
605                    .then(|| match cast_ty.kind() {
606                        ty::RawPtr(pointee, _) => match pointee.kind() {
607                            ty::Param(param) => {
608                                Some(errors::IntToWideParamNote { param: param.name })
609                            }
610                            _ => None,
611                        },
612                        _ => None,
613                    })
614                    .flatten();
615                fcx.dcx().emit_err(errors::IntToWide {
616                    span,
617                    metadata,
618                    expr_ty,
619                    cast_ty,
620                    expr_if_nightly,
621                    known_wide,
622                    param_note,
623                });
624            }
625            CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
626                let unknown_cast_to = match e {
627                    CastError::UnknownCastPtrKind => true,
628                    CastError::UnknownExprPtrKind => false,
629                    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:?}"),
630                };
631                let (span, sub) = if unknown_cast_to {
632                    (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
633                } else {
634                    (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
635                };
636                fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
637            }
638            CastError::ForeignNonExhaustiveAdt => {
639                make_invalid_casting_error(
640                    self.span,
641                    self.expr_ty,
642                    self.cast_ty,
643                    fcx,
644                )
645                .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
646                .emit();
647            }
648            CastError::PtrPtrAddingAutoTrait(added) => {
649                fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
650                    span: self.span,
651                    traits_len: added.len(),
652                    traits: {
653                        let mut traits: Vec<_> = added
654                            .into_iter()
655                            .map(|trait_did| fcx.tcx.def_path_str(trait_did))
656                            .collect();
657
658                        traits.sort();
659                        traits.into()
660                    },
661                });
662            }
663        }
664    }
665
666    fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
667        if let Err(err) = self.cast_ty.error_reported() {
668            return err;
669        }
670        if let Err(err) = self.expr_ty.error_reported() {
671            return err;
672        }
673
674        let tstr = fcx.ty_to_string(self.cast_ty);
675        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.resolve_vars_if_possible(self.expr_ty), tstr))
                        })).with_code(E0620)
        };
    if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
676            fcx.dcx(),
677            self.span,
678            self.expr_ty,
679            E0620,
680            "cast to unsized type: `{}` as `{}`",
681            fcx.resolve_vars_if_possible(self.expr_ty),
682            tstr
683        );
684        match self.expr_ty.kind() {
685            ty::Ref(_, _, mt) => {
686                let mtstr = mt.prefix_str();
687                err.span_suggestion_verbose(
688                    self.cast_span.shrink_to_lo(),
689                    "consider casting to a reference instead",
690                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mtstr))
    })format!("&{mtstr}"),
691                    Applicability::MachineApplicable,
692                );
693            }
694            ty::Adt(def, ..) if def.is_box() => {
695                err.multipart_suggestion(
696                    "you can cast to a `Box` instead",
697                    ::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![
698                        (self.cast_span.shrink_to_lo(), "Box<".to_string()),
699                        (self.cast_span.shrink_to_hi(), ">".to_string()),
700                    ],
701                    Applicability::MachineApplicable,
702                );
703            }
704            _ => {
705                err.span_help(self.expr_span, "consider using a box or reference as appropriate");
706            }
707        }
708        err.emit()
709    }
710
711    fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
712        let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
713            (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
714        } else {
715            (false, lint::builtin::TRIVIAL_CASTS)
716        };
717        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
718        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
719        fcx.tcx.emit_node_span_lint(
720            lint,
721            self.expr.hir_id,
722            self.span,
723            errors::TrivialCast { numeric, expr_ty, cast_ty },
724        );
725    }
726
727    #[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("compiler/rustc_hir_typeck/src/cast.rs"),
                                    ::tracing_core::__macro_support::Option::Some(727u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                    ::tracing_core::field::FieldSet::new(&["self"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn 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;
        }
        {
            self.expr_ty =
                fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
            self.cast_ty =
                fcx.structurally_resolve_type(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 compiler/rustc_hir_typeck/src/cast.rs:732",
                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                                    ::tracing_core::__macro_support::Option::Some(732u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::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 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 compiler/rustc_hir_typeck/src/cast.rs:750",
                                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(750u32),
                                                    ::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};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&format_args!(" -> PointerCast")
                                                                        as &dyn 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 compiler/rustc_hir_typeck/src/cast.rs:753",
                                                    "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(753u32),
                                                    ::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};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&format_args!(" -> CoercionCast")
                                                                        as &dyn 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 compiler/rustc_hir_typeck/src/cast.rs:762",
                                                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(762u32),
                                                        ::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};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!(" -> {0:?}",
                                                                                    k) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                            }
                            Err(e) => self.report_cast_error(fcx, e),
                        };
                    }
                };
            }
        }
    }
}#[instrument(skip(fcx), level = "debug")]
728    pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
729        self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
730        self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
731
732        debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
733
734        if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
735            && !self.cast_ty.has_infer_types()
736        {
737            self.report_cast_to_unsized_type(fcx);
738        } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
739            // No sense in giving duplicate error messages
740        } else {
741            match self.try_coercion_cast(fcx) {
742                Ok(()) => {
743                    if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
744                        // When casting a raw pointer to another raw pointer, we cannot convert the cast into
745                        // a coercion because the pointee types might only differ in regions, which HIR typeck
746                        // cannot distinguish. This would cause us to erroneously discard a cast which will
747                        // lead to a borrowck error like #113257.
748                        // We still did a coercion above to unify inference variables for `ptr as _` casts.
749                        // This does cause us to miss some trivial casts in the trivial cast lint.
750                        debug!(" -> PointerCast");
751                    } else {
752                        self.trivial_cast_lint(fcx);
753                        debug!(" -> CoercionCast");
754                        fcx.typeck_results
755                            .borrow_mut()
756                            .set_coercion_cast(self.expr.hir_id.local_id);
757                    }
758                }
759                Err(_) => {
760                    match self.do_check(fcx) {
761                        Ok(k) => {
762                            debug!(" -> {:?}", k);
763                        }
764                        Err(e) => self.report_cast_error(fcx, e),
765                    };
766                }
767            };
768        }
769    }
770    /// Checks a cast, and report an error if one exists. In some cases, this
771    /// can return Ok and create type errors in the fcx rather than returning
772    /// directly. coercion-cast is handled in check instead of here.
773    fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
774        use rustc_middle::ty::cast::CastTy::*;
775        use rustc_middle::ty::cast::IntTy::*;
776
777        let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
778        {
779            (Some(t_from), Some(t_cast)) => (t_from, t_cast),
780            // Function item types may need to be reified before casts.
781            (None, Some(t_cast)) => {
782                match *self.expr_ty.kind() {
783                    ty::FnDef(..) => {
784                        // Attempt a coercion to a fn pointer type.
785                        let f = fcx.normalize(
786                            self.expr_span,
787                            Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
788                        );
789                        let res = fcx.coerce(
790                            self.expr,
791                            self.expr_ty,
792                            Ty::new_fn_ptr(fcx.tcx, f),
793                            AllowTwoPhase::No,
794                            None,
795                        );
796                        if let Err(TypeError::IntrinsicCast) = res {
797                            return Err(CastError::IllegalCast);
798                        }
799                        if res.is_err() {
800                            return Err(CastError::NonScalar);
801                        }
802                        (FnPtr, t_cast)
803                    }
804                    // Special case some errors for references, and check for
805                    // array-ptr-casts. `Ref` is not a CastTy because the cast
806                    // is split into a coercion to a pointer type, followed by
807                    // a cast.
808                    ty::Ref(_, inner_ty, mutbl) => {
809                        return match t_cast {
810                            Int(_) | Float => match *inner_ty.kind() {
811                                ty::Int(_)
812                                | ty::Uint(_)
813                                | ty::Float(_)
814                                | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
815                                    Err(CastError::NeedDeref)
816                                }
817                                _ => Err(CastError::NeedViaPtr),
818                            },
819                            // array-ptr-cast
820                            Ptr(mt) => {
821                                if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
822                                    return Err(CastError::IllegalCast);
823                                }
824                                self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
825                            }
826                            _ => Err(CastError::NonScalar),
827                        };
828                    }
829                    _ => return Err(CastError::NonScalar),
830                }
831            }
832            _ => return Err(CastError::NonScalar),
833        };
834        if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
835            && !adt_def.did().is_local()
836            && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
837        {
838            return Err(CastError::ForeignNonExhaustiveAdt);
839        }
840        match (t_from, t_cast) {
841            // These types have invariants! can't cast into them.
842            (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
843
844            // * -> Bool
845            (_, Int(Bool)) => Err(CastError::CastToBool),
846
847            // * -> Char
848            (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
849            (_, Int(Char)) => Err(CastError::CastToChar),
850
851            // prim -> float,ptr
852            (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
853
854            (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
855                Err(CastError::IllegalCast)
856            }
857
858            // ptr -> ptr
859            (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
860
861            // ptr-addr-cast
862            (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr),
863
864            (FnPtr, Int(_)) => {
865                // FIXME(#95489): there should eventually be a lint for these casts
866                Ok(CastKind::FnPtrAddrCast)
867            }
868            // addr-ptr-cast
869            (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
870            // fn-ptr-cast
871            (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
872
873            // prim -> prim
874            (Int(CEnum), Int(_)) => {
875                self.err_if_cenum_impl_drop(fcx);
876                Ok(CastKind::EnumCast)
877            }
878            (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
879
880            (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
881        }
882    }
883
884    fn check_ptr_ptr_cast(
885        &self,
886        fcx: &FnCtxt<'a, 'tcx>,
887        m_src: ty::TypeAndMut<'tcx>,
888        m_dst: ty::TypeAndMut<'tcx>,
889    ) -> Result<CastKind, CastError<'tcx>> {
890        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:890",
                        "rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
                        ::tracing_core::__macro_support::Option::Some(890u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_ptr_ptr_cast m_src={0:?} m_dst={1:?}",
                                                    m_src, m_dst) as &dyn Value))])
            });
    } else { ; }
};debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
891        // ptr-ptr cast. metadata must match.
892
893        let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
894        let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
895
896        // We can't cast if target pointer kind is unknown
897        let Some(dst_kind) = dst_kind else {
898            return Err(CastError::UnknownCastPtrKind);
899        };
900
901        // Cast to thin pointer is OK
902        if dst_kind == PointerKind::Thin {
903            return Ok(CastKind::PtrPtrCast);
904        }
905
906        // We can't cast to wide pointer if source pointer kind is unknown
907        let Some(src_kind) = src_kind else {
908            return Err(CastError::UnknownCastPtrKind);
909        };
910
911        match (src_kind, dst_kind) {
912            // thin -> fat? report invalid cast (don't complain about vtable kinds)
913            (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
914
915            // trait object -> trait object? need to do additional checks
916            (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
917                match (src_tty.principal(), dst_tty.principal()) {
918                    // A<dyn Src<...> + SrcAuto> -> B<dyn Dst<...> + DstAuto>. need to make sure
919                    // - `Src` and `Dst` traits are the same
920                    // - traits have the same generic arguments
921                    // - projections are the same
922                    // - `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`
923                    //
924                    // Note that trait upcasting goes through a different mechanism (`coerce_unsized`)
925                    // and is unaffected by this check.
926                    (Some(src_principal), Some(_)) => {
927                        let tcx = fcx.tcx;
928
929                        // We need to reconstruct trait object types.
930                        // `m_src` and `m_dst` won't work for us here because they will potentially
931                        // contain wrappers, which we do not care about.
932                        //
933                        // e.g. we want to allow `dyn T -> (dyn T,)`, etc.
934                        //
935                        // We also need to skip auto traits to emit an FCW and not an error.
936                        let src_obj = Ty::new_dynamic(
937                            tcx,
938                            tcx.mk_poly_existential_predicates(
939                                &src_tty.without_auto_traits().collect::<Vec<_>>(),
940                            ),
941                            tcx.lifetimes.re_erased,
942                        );
943                        let dst_obj = Ty::new_dynamic(
944                            tcx,
945                            tcx.mk_poly_existential_predicates(
946                                &dst_tty.without_auto_traits().collect::<Vec<_>>(),
947                            ),
948                            tcx.lifetimes.re_erased,
949                        );
950
951                        // `dyn Src = dyn Dst`, this checks for matching traits/generics/projections
952                        // This is `fcx.demand_eqtype`, but inlined to give a better error.
953                        let cause = fcx.misc(self.span);
954                        if fcx
955                            .at(&cause, fcx.param_env)
956                            .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
957                            .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
958                            .is_err()
959                        {
960                            return Err(CastError::DifferingKinds { src_kind, dst_kind });
961                        }
962
963                        // Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`.
964                        // Emit an FCW otherwise.
965                        let src_auto: FxHashSet<_> = src_tty
966                            .auto_traits()
967                            .chain(
968                                elaborate::supertrait_def_ids(tcx, src_principal.def_id())
969                                    .filter(|def_id| tcx.trait_is_auto(*def_id)),
970                            )
971                            .collect();
972
973                        let added = dst_tty
974                            .auto_traits()
975                            .filter(|trait_did| !src_auto.contains(trait_did))
976                            .collect::<Vec<_>>();
977
978                        if !added.is_empty() {
979                            return Err(CastError::PtrPtrAddingAutoTrait(added));
980                        }
981
982                        Ok(CastKind::PtrPtrCast)
983                    }
984
985                    // dyn Auto -> dyn Auto'? ok.
986                    (None, None) => Ok(CastKind::PtrPtrCast),
987
988                    // dyn Trait -> dyn Auto? not ok (for now).
989                    //
990                    // Although dropping the principal is already allowed for unsizing coercions
991                    // (e.g. `*const (dyn Trait + Auto)` to `*const dyn Auto`), dropping it is
992                    // currently **NOT** allowed for (non-coercion) ptr-to-ptr casts (e.g
993                    // `*const Foo` to `*const Bar` where `Foo` has a `dyn Trait + Auto` tail
994                    // and `Bar` has a `dyn Auto` tail), because the underlying MIR operations
995                    // currently work very differently:
996                    //
997                    // * A MIR unsizing coercion on raw pointers to trait objects (`*const dyn Src`
998                    //   to `*const dyn Dst`) is currently equivalent to downcasting the source to
999                    //   the concrete sized type that it was originally unsized from first (via a
1000                    //   ptr-to-ptr cast from `*const Src` to `*const T` with `T: Sized`) and then
1001                    //   unsizing this thin pointer to the target type (unsizing `*const T` to
1002                    //   `*const Dst`). In particular, this means that the pointer's metadata
1003                    //   (vtable) will semantically change, e.g. for const eval and miri, even
1004                    //   though the vtables will always be merged for codegen.
1005                    //
1006                    // * A MIR ptr-to-ptr cast is currently equivalent to a transmute and does not
1007                    //   change the pointer metadata (vtable) at all.
1008                    //
1009                    // In addition to this potentially surprising difference between coercion and
1010                    // non-coercion casts, casting away the principal with a MIR ptr-to-ptr cast
1011                    // is currently considered undefined behavior:
1012                    //
1013                    // As a validity invariant of pointers to trait objects, we currently require
1014                    // that the principal of the vtable in the pointer metadata exactly matches
1015                    // the principal of the pointee type, where "no principal" is also considered
1016                    // a kind of principal.
1017                    (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1018
1019                    // dyn Auto -> dyn Trait? not ok.
1020                    (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1021                }
1022            }
1023
1024            // fat -> fat? metadata kinds must match
1025            (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1026
1027            (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1028        }
1029    }
1030
1031    fn check_fptr_ptr_cast(
1032        &self,
1033        fcx: &FnCtxt<'a, 'tcx>,
1034        m_cast: ty::TypeAndMut<'tcx>,
1035    ) -> Result<CastKind, CastError<'tcx>> {
1036        // fptr-ptr cast. must be to thin ptr
1037
1038        match fcx.pointer_kind(m_cast.ty, self.span)? {
1039            None => Err(CastError::UnknownCastPtrKind),
1040            Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1041            _ => Err(CastError::IllegalCast),
1042        }
1043    }
1044
1045    fn check_ptr_addr_cast(
1046        &self,
1047        fcx: &FnCtxt<'a, 'tcx>,
1048        m_expr: ty::TypeAndMut<'tcx>,
1049    ) -> Result<CastKind, CastError<'tcx>> {
1050        // ptr-addr cast. must be from thin ptr
1051
1052        match fcx.pointer_kind(m_expr.ty, self.span)? {
1053            None => Err(CastError::UnknownExprPtrKind),
1054            Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1055            _ => Err(CastError::NeedViaThinPtr),
1056        }
1057    }
1058
1059    fn check_ref_cast(
1060        &self,
1061        fcx: &FnCtxt<'a, 'tcx>,
1062        mut m_expr: ty::TypeAndMut<'tcx>,
1063        mut m_cast: ty::TypeAndMut<'tcx>,
1064    ) -> Result<CastKind, CastError<'tcx>> {
1065        // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1066        m_expr.ty = fcx.resolve_vars_with_obligations(m_expr.ty);
1067        m_cast.ty = fcx.resolve_vars_with_obligations(m_cast.ty);
1068
1069        if m_expr.mutbl >= m_cast.mutbl
1070            && let ty::Array(ety, _) = m_expr.ty.kind()
1071            && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1072        {
1073            // Due to historical reasons we allow directly casting references of
1074            // arrays into raw pointers of their element type.
1075
1076            // Coerce to a raw pointer so that we generate RawPtr in MIR.
1077            let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1078            fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1079                .unwrap_or_else(|_| {
1080                    ::rustc_middle::util::bug::bug_fmt(format_args!("could not cast from reference to array to pointer to array ({0:?} to {1:?})",
        self.expr_ty, array_ptr_type))bug!(
1081                        "could not cast from reference to array to pointer to array ({:?} to {:?})",
1082                        self.expr_ty,
1083                        array_ptr_type,
1084                    )
1085                });
1086
1087            // this will report a type mismatch if needed
1088            fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1089            return Ok(CastKind::ArrayPtrCast);
1090        }
1091
1092        Err(CastError::IllegalCast)
1093    }
1094
1095    fn check_addr_ptr_cast(
1096        &self,
1097        fcx: &FnCtxt<'a, 'tcx>,
1098        m_cast: TypeAndMut<'tcx>,
1099    ) -> Result<CastKind, CastError<'tcx>> {
1100        // ptr-addr cast. pointer must be thin.
1101        match fcx.pointer_kind(m_cast.ty, self.span)? {
1102            None => Err(CastError::UnknownCastPtrKind),
1103            Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1104            Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1105            Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1106            Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1107                Err(CastError::IntToWideCast(None))
1108            }
1109        }
1110    }
1111
1112    fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1113        match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1114            Ok(_) => Ok(()),
1115            Err(err) => Err(err),
1116        }
1117    }
1118
1119    fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1120        if let ty::Adt(d, _) = self.expr_ty.kind()
1121            && d.has_dtor(fcx.tcx)
1122        {
1123            let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1124            let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1125
1126            fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1127        }
1128    }
1129
1130    /// Attempt to suggest using `.is_empty` when trying to cast from a
1131    /// collection type to a boolean.
1132    fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1133        if self.cast_ty.is_bool() {
1134            let derefed = fcx
1135                .autoderef(self.expr_span, self.expr_ty)
1136                .silence_errors()
1137                .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(..)));
1138
1139            if let Some((deref_ty, _)) = derefed {
1140                // Give a note about what the expr derefs to.
1141                if deref_ty != self.expr_ty.peel_refs() {
1142                    err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1143                }
1144
1145                // Create a multipart suggestion: add `!` and `.is_empty()` in
1146                // place of the cast.
1147                err.subdiagnostic(errors::UseIsEmpty {
1148                    lo: self.expr_span.shrink_to_lo(),
1149                    hi: self.span.with_lo(self.expr_span.hi()),
1150                    expr_ty: self.expr_ty,
1151                });
1152            }
1153        }
1154    }
1155}