Skip to main content

rustc_hir_typeck/
cast.rs

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