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::{diagnostics, 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_def_id"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.expr, &self.expr_ty, &self.expr_span, &self.cast_ty,
                        &self.cast_span, &self.span, &&self.body_def_id];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "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_def_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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
                                                    t, span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
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 implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}unimplemented!("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::CastEnumDrop =>
                ::core::fmt::Formatter::write_str(f, "CastEnumDrop"),
            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    CastEnumDrop,
179    /// Cast of int to (possibly) wide raw pointer.
180    ///
181    /// Argument is the specific name of the metadata in plain words, such as "a vtable"
182    /// or "a length". If this argument is None, then the metadata is unknown, for example,
183    /// when we're typechecking a type parameter with a ?Sized bound.
184    IntToWideCast(Option<&'static str>),
185    ForeignNonExhaustiveAdt,
186    PtrPtrAddingAutoTrait(Vec<DefId>),
187}
188
189impl From<ErrorGuaranteed> for CastError<'_> {
190    fn from(err: ErrorGuaranteed) -> Self {
191        CastError::ErrorGuaranteed(err)
192    }
193}
194
195fn make_invalid_casting_error<'a, 'tcx>(
196    span: Span,
197    expr_ty: Ty<'tcx>,
198    cast_ty: Ty<'tcx>,
199    fcx: &FnCtxt<'a, 'tcx>,
200) -> Diag<'a> {
201    {
    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!(
202        fcx.dcx(),
203        span,
204        expr_ty,
205        E0606,
206        "casting `{}` as `{}` is invalid",
207        fcx.ty_to_string(expr_ty),
208        fcx.ty_to_string(cast_ty)
209    )
210}
211
212/// If a cast from `from_ty` to `to_ty` is valid, returns a `Some` containing the kind
213/// of the cast.
214///
215/// This is a helper used from clippy.
216pub fn check_cast<'tcx>(
217    tcx: TyCtxt<'tcx>,
218    param_env: ty::ParamEnv<'tcx>,
219    e: &'tcx hir::Expr<'tcx>,
220    from_ty: Ty<'tcx>,
221    to_ty: Ty<'tcx>,
222) -> Option<CastKind> {
223    let hir_id = e.hir_id;
224    let local_def_id = hir_id.owner.def_id;
225
226    let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
227    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
228
229    if let Ok(check) = CastCheck::new(
230        &fn_ctxt, e, from_ty, to_ty,
231        // We won't show any errors to the user, so the span is irrelevant here.
232        DUMMY_SP, DUMMY_SP,
233    ) {
234        check.do_check(&fn_ctxt).ok()
235    } else {
236        None
237    }
238}
239
240impl<'a, 'tcx> CastCheck<'tcx> {
241    pub(crate) fn new(
242        fcx: &FnCtxt<'a, 'tcx>,
243        expr: &'tcx hir::Expr<'tcx>,
244        expr_ty: Ty<'tcx>,
245        cast_ty: Ty<'tcx>,
246        cast_span: Span,
247        span: Span,
248    ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
249        let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
250        let check = CastCheck {
251            expr,
252            expr_ty,
253            expr_span,
254            cast_ty,
255            cast_span,
256            span,
257            body_def_id: fcx.body_def_id,
258        };
259
260        // For better error messages, check for some obviously unsized
261        // cases now. We do a more thorough check at the end, once
262        // inference is more completely known.
263        match cast_ty.kind() {
264            ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
265            _ => Ok(check),
266        }
267    }
268
269    fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
270        match e {
271            CastError::ErrorGuaranteed(_) => {
272                // an error has already been reported
273            }
274            CastError::NeedDeref => {
275                let mut err =
276                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
277
278                if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
279                    // get just the borrow part of the expression
280                    let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
281                    err.span_suggestion_verbose(
282                        span,
283                        "remove the unneeded borrow",
284                        "",
285                        Applicability::MachineApplicable,
286                    );
287                } else {
288                    err.span_suggestion_verbose(
289                        self.expr_span.shrink_to_lo(),
290                        "dereference the expression",
291                        "*",
292                        Applicability::MachineApplicable,
293                    );
294                }
295
296                err.emit();
297            }
298            CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
299                let mut err =
300                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
301
302                if self.cast_ty.is_integral() {
303                    if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
304                        && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
305                        && let ty::Adt(adt_def, _) = *inner_ty.kind()
306                        && adt_def.is_enum()
307                        && adt_def.is_payloadfree()
308                    {
309                        err.span_suggestion_verbose(
310                            self.expr_span.shrink_to_lo(),
311                            "try dereferencing before the cast",
312                            "*",
313                            Applicability::MaybeIncorrect,
314                        );
315                        if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
316                            err.span_suggestion_verbose(
317                                fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
318                                "add `#[derive(Copy, Clone)]` to the enum definition",
319                                "#[derive(Copy, Clone)]\n",
320                                Applicability::MaybeIncorrect,
321                            );
322                        }
323                    } else {
324                        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!(
325                            "cast through {} first",
326                            match e {
327                                CastError::NeedViaPtr => "a raw pointer",
328                                CastError::NeedViaThinPtr => "a thin pointer",
329                                e => unreachable!(
330                                    "control flow means we should never encounter a {e:?}"
331                                ),
332                            }
333                        ));
334                    }
335                }
336
337                self.try_suggest_collection_to_bool(fcx, &mut err);
338
339                err.emit();
340            }
341            CastError::NeedViaInt => {
342                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
343                    .with_help("cast through an integer first")
344                    .emit();
345            }
346            CastError::IllegalCast => {
347                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
348            }
349            CastError::DifferingKinds { src_kind, dst_kind } => {
350                let mut err =
351                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
352
353                match (src_kind, dst_kind) {
354                    (PointerKind::VTable(_), PointerKind::VTable(_)) => {
355                        err.note("the trait objects may have different vtables");
356                    }
357                    (
358                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
359                        PointerKind::OfParam(_)
360                        | PointerKind::OfAlias(_)
361                        | PointerKind::VTable(_)
362                        | PointerKind::Length,
363                    )
364                    | (
365                        PointerKind::VTable(_) | PointerKind::Length,
366                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
367                    ) => {
368                        err.note("the pointers may have different metadata");
369                    }
370                    (PointerKind::VTable(_), PointerKind::Length)
371                    | (PointerKind::Length, PointerKind::VTable(_)) => {
372                        err.note("the pointers have different metadata");
373                    }
374                    (
375                        PointerKind::Thin,
376                        PointerKind::Thin
377                        | PointerKind::VTable(_)
378                        | PointerKind::Length
379                        | PointerKind::OfParam(_)
380                        | PointerKind::OfAlias(_),
381                    )
382                    | (
383                        PointerKind::VTable(_)
384                        | PointerKind::Length
385                        | PointerKind::OfParam(_)
386                        | PointerKind::OfAlias(_),
387                        PointerKind::Thin,
388                    )
389                    | (PointerKind::Length, PointerKind::Length) => {
390                        ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("unexpected cast error: {0:?}", e))span_bug!(self.span, "unexpected cast error: {e:?}")
391                    }
392                }
393
394                err.emit();
395            }
396            CastError::CastToBool => {
397                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
398                let help = if self.expr_ty.is_numeric() {
399                    diagnostics::CannotCastToBoolHelp::Numeric(
400                        self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
401                    )
402                } else {
403                    diagnostics::CannotCastToBoolHelp::Unsupported(self.span)
404                };
405                fcx.dcx().emit_err(diagnostics::CannotCastToBool {
406                    span: self.span,
407                    expr_ty,
408                    help,
409                });
410            }
411            CastError::CastToChar => {
412                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!(
413                    fcx.dcx(),
414                    self.span,
415                    self.expr_ty,
416                    E0604,
417                    "only `u8` can be cast as `char`, not `{}`",
418                    self.expr_ty
419                );
420                err.span_label(self.span, "invalid cast");
421                if self.expr_ty.is_numeric() {
422                    if self.expr_ty == fcx.tcx.types.u32 {
423                        err.multipart_suggestion(
424                            "consider using `char::from_u32` instead",
425                            ::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![
426                                (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
427                                (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
428                            ],
429                            Applicability::MachineApplicable,
430                        );
431                    } else if self.expr_ty == fcx.tcx.types.i8 {
432                        err.span_help(self.span, "consider casting from `u8` instead");
433                    } else {
434                        err.span_help(
435                            self.span,
436                            "consider using `char::from_u32` instead (via a `u32`)",
437                        );
438                    };
439                }
440                err.emit();
441            }
442            CastError::NonScalar => {
443                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!(
444                    fcx.dcx(),
445                    self.span,
446                    self.expr_ty,
447                    E0605,
448                    "non-primitive cast: `{}` as `{}`",
449                    self.expr_ty,
450                    fcx.ty_to_string(self.cast_ty)
451                );
452
453                if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
454                    && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    ExprKind::AddrOf(..) => true,
    _ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
455                {
456                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
                snippet))
    })format!(
457                        "casting reference expression `{}` because `&` binds tighter than `as`",
458                        snippet
459                    ));
460                }
461
462                let mut sugg = None;
463                let mut sugg_mutref = false;
464                if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
465                    if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
466                        && fcx.may_coerce(
467                            Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
468                            self.cast_ty,
469                        )
470                    {
471                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
    })format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
472                    } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
473                        && expr_mutbl == Mutability::Not
474                        && mutbl == Mutability::Mut
475                        && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
476                    {
477                        sugg_mutref = true;
478                    }
479
480                    if !sugg_mutref
481                        && sugg == None
482                        && fcx.may_coerce(
483                            Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
484                            self.cast_ty,
485                        )
486                    {
487                        sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
488                    }
489                } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
490                    && fcx.may_coerce(
491                        Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
492                        self.cast_ty,
493                    )
494                {
495                    sugg = Some((::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
    })format!("&{}", mutbl.prefix_str()), false));
496                }
497                if sugg_mutref {
498                    err.span_label(self.span, "invalid cast");
499                    err.span_note(self.expr_span, "this reference is immutable");
500                    err.span_note(self.cast_span, "trying to cast to a mutable reference type");
501                } else if let Some((sugg, remove_cast)) = sugg {
502                    err.span_label(self.span, "invalid cast");
503
504                    let has_parens = fcx
505                        .tcx
506                        .sess
507                        .source_map()
508                        .span_to_snippet(self.expr_span)
509                        .is_ok_and(|snip| snip.starts_with('('));
510
511                    // Very crude check to see whether the expression must be wrapped
512                    // in parentheses for the suggestion to work (issue #89497).
513                    // Can/should be extended in the future.
514                    let needs_parens =
515                        !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
    hir::ExprKind::Cast(..) => true,
    _ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
516
517                    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)];
518                    if needs_parens {
519                        suggestion[0].1 += "(";
520                        suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
521                    }
522                    if remove_cast {
523                        suggestion.push((
524                            self.expr_span.shrink_to_hi().to(self.cast_span),
525                            String::new(),
526                        ));
527                    }
528
529                    err.multipart_suggestion(
530                        "consider borrowing the value",
531                        suggestion,
532                        Applicability::MachineApplicable,
533                    );
534                } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
    _ => false,
}matches!(
535                    self.cast_ty.kind(),
536                    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
537                ) {
538                    // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
539                    if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
540                        let ty = fcx.resolve_vars_if_possible(self.cast_ty);
541                        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
542                        if fcx
543                            .infcx
544                            .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
545                            .must_apply_modulo_regions()
546                        {
547                            let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
548                                fcx.tcx.value_path_str_with_args(def.did(), args)
549                            } else {
550                                self.cast_ty.to_string()
551                            };
552                            err.multipart_suggestion(
553                                "consider using the `From` trait instead",
554                                ::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![
555                                    (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
556                                    (
557                                        self.expr_span.shrink_to_hi().to(self.cast_span),
558                                        ")".to_string(),
559                                    ),
560                                ],
561                                Applicability::MaybeIncorrect,
562                            );
563                        }
564                    }
565
566                    let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
567                        && adt.is_enum()
568                        && self.cast_ty.is_numeric()
569                    {
570                        (
571                            "an `as` expression can be used to convert enum types to numeric \
572                             types only if the enum type is unit-only or field-less",
573                            Some(
574                                "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
575                            ),
576                        )
577                    } else {
578                        (
579                            "an `as` expression can only be used to convert between primitive \
580                             types or to coerce to a specific trait object",
581                            None,
582                        )
583                    };
584
585                    err.span_label(self.span, msg);
586
587                    if let Some(note) = note {
588                        err.note(note);
589                    }
590                } else {
591                    err.span_label(self.span, "invalid cast");
592                }
593
594                fcx.suggest_closure_to_fn_ptr_coercion(
595                    &mut err,
596                    self.expr,
597                    self.cast_ty,
598                    self.expr_ty,
599                );
600                self.try_suggest_collection_to_bool(fcx, &mut err);
601
602                err.emit();
603            }
604            CastError::SizedUnsizedCast => {
605                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
606                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
607                fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer {
608                    span: self.span,
609                    expr_ty,
610                    cast_ty,
611                    teach: fcx.tcx.sess.teach(E0607),
612                });
613            }
614            CastError::IntToWideCast(known_metadata) => {
615                let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
616                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
617                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
618                let metadata = known_metadata.unwrap_or("type-specific metadata");
619                let known_wide = known_metadata.is_some();
620                let span = self.cast_span;
621                let param_note = (!known_wide)
622                    .then(|| match cast_ty.kind() {
623                        ty::RawPtr(pointee, _) => match pointee.kind() {
624                            ty::Param(param) => {
625                                Some(diagnostics::IntToWideParamNote { param: param.name })
626                            }
627                            _ => None,
628                        },
629                        _ => None,
630                    })
631                    .flatten();
632                fcx.dcx().emit_err(diagnostics::IntToWide {
633                    span,
634                    metadata,
635                    expr_ty,
636                    cast_ty,
637                    expr_if_nightly,
638                    known_wide,
639                    param_note,
640                });
641            }
642            CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
643                let unknown_cast_to = match e {
644                    CastError::UnknownCastPtrKind => true,
645                    CastError::UnknownExprPtrKind => false,
646                    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:?}"),
647                };
648                let (span, sub) = if unknown_cast_to {
649                    (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span))
650                } else {
651                    (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span))
652                };
653                fcx.dcx().emit_err(diagnostics::CastUnknownPointer {
654                    span,
655                    to: unknown_cast_to,
656                    sub,
657                });
658            }
659            CastError::CastEnumDrop => {
660                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
661                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
662
663                fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty });
664            }
665            CastError::ForeignNonExhaustiveAdt => {
666                make_invalid_casting_error(
667                    self.span,
668                    self.expr_ty,
669                    self.cast_ty,
670                    fcx,
671                )
672                .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
673                .emit();
674            }
675            CastError::PtrPtrAddingAutoTrait(added) => {
676                fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject {
677                    span: self.span,
678                    traits_len: added.len(),
679                    traits: {
680                        let mut traits: Vec<_> = added
681                            .into_iter()
682                            .map(|trait_did| fcx.tcx.def_path_str(trait_did))
683                            .collect();
684
685                        traits.sort();
686                        traits.into()
687                    },
688                });
689            }
690        }
691    }
692
693    fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
694        if let Err(err) = self.cast_ty.error_reported() {
695            return err;
696        }
697        if let Err(err) = self.expr_ty.error_reported() {
698            return err;
699        }
700
701        let tstr = fcx.ty_to_string(self.cast_ty);
702        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!(
703            fcx.dcx(),
704            self.span,
705            self.expr_ty,
706            E0620,
707            "cast to unsized type: `{}` as `{}`",
708            fcx.resolve_vars_if_possible(self.expr_ty),
709            tstr
710        );
711        match self.expr_ty.kind() {
712            ty::Ref(_, _, mt) => {
713                let mtstr = mt.prefix_str();
714                err.span_suggestion_verbose(
715                    self.cast_span.shrink_to_lo(),
716                    "consider casting to a reference instead",
717                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&{0}", mtstr))
    })format!("&{mtstr}"),
718                    Applicability::MachineApplicable,
719                );
720            }
721            ty::Adt(def, ..) if def.is_box() => {
722                err.multipart_suggestion(
723                    "you can cast to a `Box` instead",
724                    ::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![
725                        (self.cast_span.shrink_to_lo(), "Box<".to_string()),
726                        (self.cast_span.shrink_to_hi(), ">".to_string()),
727                    ],
728                    Applicability::MachineApplicable,
729                );
730            }
731            _ => {
732                err.span_help(self.expr_span, "consider using a box or reference as appropriate");
733            }
734        }
735        err.emit()
736    }
737
738    fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
739        if self.is_non_trivial_ref_trait_object_upcast(fcx) {
740            return;
741        }
742
743        let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
744            (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
745        } else {
746            (false, lint::builtin::TRIVIAL_CASTS)
747        };
748        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
749        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
750        fcx.tcx.emit_node_span_lint(
751            lint,
752            self.expr.hir_id,
753            self.span,
754            diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
755        );
756    }
757
758    // A trait-object upcast from a method receiver, such as
759    // `(other as &dyn Any).downcast_ref::<u32>()`,
760    // is not trivial, because it may change the method resolution, we want to skip the lint in this case.
761    // see issue #148219
762    fn is_non_trivial_ref_trait_object_upcast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
763        if !#[allow(non_exhaustive_omitted_patterns)] match (self.expr_ty.kind(),
        self.cast_ty.kind()) {
    (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _)) if
        #[allow(non_exhaustive_omitted_patterns)] match (from_ty.kind(),
                to_ty.kind()) {
            (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if
                from_data != to_data => true,
            _ => false,
        } => true,
    _ => false,
}matches!(
764            (self.expr_ty.kind(), self.cast_ty.kind()),
765            (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _))
766                if matches!(
767                    (from_ty.kind(), to_ty.kind()),
768                    (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if from_data != to_data
769                )
770        ) {
771            return false;
772        }
773
774        let hir::Node::Expr(cast_expr) = fcx.tcx.parent_hir_node(self.expr.hir_id) else {
775            return false;
776        };
777        let hir::Node::Expr(parent) = fcx.tcx.parent_hir_node(cast_expr.hir_id) else {
778            return false;
779        };
780
781        #[allow(non_exhaustive_omitted_patterns)] match parent.kind {
    hir::ExprKind::MethodCall(_, receiver, ..) if
        receiver.hir_id == cast_expr.hir_id => true,
    _ => false,
}matches!(
782            parent.kind,
783            hir::ExprKind::MethodCall(_, receiver, ..) if receiver.hir_id == cast_expr.hir_id
784        )
785    }
786
787    fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
788        if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
789            && fcx.resolve_vars_if_possible(self.expr_ty).is_ty_var()
790            && fcx.resolve_vars_if_possible(fcx.node_ty(idx.hir_id)).is_ty_var()
791        {
792            index_operand_ambiguity_span(idx)
793        } else {
794            self.expr_span
795        }
796    }
797
798    #[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(798u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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