Skip to main content

rustc_hir_typeck/
cast.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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