1use 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#[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::write_str(f,
match self {
CastKind::PtrPtrCast => "PtrPtrCast",
CastKind::PtrAddrCast => "PtrAddrCast",
CastKind::AddrPtrCast => "AddrPtrCast",
CastKind::NumericCast => "NumericCast",
CastKind::EnumCast => "EnumCast",
CastKind::PrimIntCast => "PrimIntCast",
CastKind::U8CharCast => "U8CharCast",
CastKind::ArrayPtrCast => "ArrayPtrCast",
CastKind::FnPtrPtrCast => "FnPtrPtrCast",
CastKind::FnPtrAddrCast => "FnPtrAddrCast",
})
}
}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#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CastCheck<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["expr", "expr_ty", "expr_span", "cast_ty", "cast_span", "span",
"body_def_id"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.expr, &self.expr_ty, &self.expr_span, &self.cast_ty,
&self.cast_span, &self.span, &&self.body_def_id];
::core::fmt::Formatter::debug_struct_fields_finish(f, "CastCheck",
names, values)
}
}Debug)]
74pub(crate) struct CastCheck<'tcx> {
75 expr: &'tcx hir::Expr<'tcx>,
77 expr_ty: Ty<'tcx>,
79 expr_span: Span,
80 cast_ty: Ty<'tcx>,
82 cast_span: Span,
83 span: Span,
84 pub body_def_id: LocalDefId,
85}
86
87#[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_tuple_field1_finish(f, "VTable",
&__self_0),
Self::Length => ::core::fmt::Formatter::write_str(f, "Length"),
Self::OfAlias(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfAlias", &__self_0),
Self::OfParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfParam", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PointerKind<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for PointerKind<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PointerKind<'tcx> {
#[inline]
fn clone(&self) -> 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 Thin,
94 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
96 Length,
98 OfAlias(ty::AliasTy<'tcx>),
100 OfParam(ty::ParamTy),
102}
103
104impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
105 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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:112",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/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 ty::Foreign(..) => Some(PointerKind::Thin),
142 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
144 ty::Param(p) => Some(PointerKind::OfParam(p)),
145 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_tuple_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", __self_0, "dst_kind",
&__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_tuple_field1_finish(f,
"IntToWideCast", &__self_0),
Self::ForeignNonExhaustiveAdt =>
::core::fmt::Formatter::write_str(f,
"ForeignNonExhaustiveAdt"),
Self::PtrPtrAddingAutoTrait(__self_0) =>
::core::fmt::Formatter::debug_tuple_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 SizedUnsizedCast,
187 IllegalCast,
188 NeedDeref,
189 NeedViaPtr,
190 NeedViaThinPtr,
191 NeedViaInt,
192 NonScalar,
193 UnknownExprPtrKind,
194 UnknownCastPtrKind,
195 CastEnumDrop,
196 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
229pub 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
246 if let Ok(check) = CastCheck::new(
247 &fn_ctxt, e, from_ty, to_ty,
248 DUMMY_SP, DUMMY_SP,
250 ) {
251 check.do_check(&fn_ctxt).ok()
252 } else {
253 None
254 }
255}
256
257impl<'a, 'tcx> CastCheck<'tcx> {
258 pub(crate) fn new(
259 fcx: &FnCtxt<'a, 'tcx>,
260 expr: &'tcx hir::Expr<'tcx>,
261 expr_ty: Ty<'tcx>,
262 cast_ty: Ty<'tcx>,
263 cast_span: Span,
264 span: Span,
265 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
266 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
267 let check = CastCheck {
268 expr,
269 expr_ty,
270 expr_span,
271 cast_ty,
272 cast_span,
273 span,
274 body_def_id: fcx.body_def_id,
275 };
276
277 match cast_ty.kind() {
281 ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
282 _ => Ok(check),
283 }
284 }
285
286 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
287 match e {
288 CastError::ErrorGuaranteed(_) => {
289 }
291 CastError::NeedDeref => {
292 let mut err =
293 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
294
295 if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
296 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
298 err.span_suggestion_verbose(
299 span,
300 "remove the unneeded borrow",
301 "",
302 Applicability::MachineApplicable,
303 );
304 } else {
305 err.span_suggestion_verbose(
306 self.expr_span.shrink_to_lo(),
307 "dereference the expression",
308 "*",
309 Applicability::MachineApplicable,
310 );
311 }
312
313 err.emit();
314 }
315 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
316 let mut err =
317 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
318
319 if self.cast_ty.is_integral() {
320 if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
321 && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
322 && let ty::Adt(adt_def, _) = *inner_ty.kind()
323 && adt_def.is_enum()
324 && adt_def.is_payloadfree()
325 {
326 err.span_suggestion_verbose(
327 self.expr_span.shrink_to_lo(),
328 "try dereferencing before the cast",
329 "*",
330 Applicability::MaybeIncorrect,
331 );
332 if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
333 err.span_suggestion_verbose(
334 fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
335 "add `#[derive(Copy, Clone)]` to the enum definition",
336 "#[derive(Copy, Clone)]\n",
337 Applicability::MaybeIncorrect,
338 );
339 }
340 } else {
341 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!(
342 "cast through {} first",
343 match e {
344 CastError::NeedViaPtr => "a raw pointer",
345 CastError::NeedViaThinPtr => "a thin pointer",
346 e => unreachable!(
347 "control flow means we should never encounter a {e:?}"
348 ),
349 }
350 ));
351 }
352 }
353
354 self.try_suggest_collection_to_bool(fcx, &mut err);
355
356 err.emit();
357 }
358 CastError::NeedViaInt => {
359 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
360 .with_help("cast through an integer first")
361 .emit();
362 }
363 CastError::IllegalCast => {
364 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
365 }
366 CastError::DifferingKinds { src_kind, dst_kind } => {
367 let mut err =
368 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
369
370 match (src_kind, dst_kind) {
371 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
372 err.note("the trait objects may have different vtables");
373 }
374 (
375 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
376 PointerKind::OfParam(_)
377 | PointerKind::OfAlias(_)
378 | PointerKind::VTable(_)
379 | PointerKind::Length,
380 )
381 | (
382 PointerKind::VTable(_) | PointerKind::Length,
383 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
384 ) => {
385 err.note("the pointers may have different metadata");
386 }
387 (PointerKind::VTable(_), PointerKind::Length)
388 | (PointerKind::Length, PointerKind::VTable(_)) => {
389 err.note("the pointers have different metadata");
390 }
391 (
392 PointerKind::Thin,
393 PointerKind::Thin
394 | PointerKind::VTable(_)
395 | PointerKind::Length
396 | PointerKind::OfParam(_)
397 | PointerKind::OfAlias(_),
398 )
399 | (
400 PointerKind::VTable(_)
401 | PointerKind::Length
402 | PointerKind::OfParam(_)
403 | PointerKind::OfAlias(_),
404 PointerKind::Thin,
405 )
406 | (PointerKind::Length, PointerKind::Length) => {
407 ::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:?}")
408 }
409 }
410
411 err.emit();
412 }
413 CastError::CastToBool => {
414 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
415 let help = if self.expr_ty.is_numeric() {
416 diagnostics::CannotCastToBoolHelp::Numeric(
417 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
418 )
419 } else {
420 diagnostics::CannotCastToBoolHelp::Unsupported(self.span)
421 };
422 fcx.dcx().emit_err(diagnostics::CannotCastToBool {
423 span: self.span,
424 expr_ty,
425 help,
426 });
427 }
428 CastError::CastToChar => {
429 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!(
430 fcx.dcx(),
431 self.span,
432 self.expr_ty,
433 E0604,
434 "only `u8` can be cast as `char`, not `{}`",
435 self.expr_ty
436 );
437 err.span_label(self.span, "invalid cast");
438 if self.expr_ty.is_numeric() {
439 if self.expr_ty == fcx.tcx.types.u32 {
440 err.multipart_suggestion(
441 "consider using `char::from_u32` instead",
442 ::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![
443 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
444 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
445 ],
446 Applicability::MachineApplicable,
447 );
448 } else if self.expr_ty == fcx.tcx.types.i8 {
449 err.span_help(self.span, "consider casting from `u8` instead");
450 } else {
451 err.span_help(
452 self.span,
453 "consider using `char::from_u32` instead (via a `u32`)",
454 );
455 };
456 }
457 err.emit();
458 }
459 CastError::NonScalar => {
460 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!(
461 fcx.dcx(),
462 self.span,
463 self.expr_ty,
464 E0605,
465 "non-primitive cast: `{}` as `{}`",
466 self.expr_ty,
467 fcx.ty_to_string(self.cast_ty)
468 );
469
470 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
471 && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
472 {
473 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
snippet))
})format!(
474 "casting reference expression `{}` because `&` binds tighter than `as`",
475 snippet
476 ));
477 }
478
479 let mut sugg = None;
480 let mut sugg_mutref = false;
481 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
482 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
483 && fcx.may_coerce(
484 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
485 self.cast_ty,
486 )
487 {
488 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
})format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
489 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
490 && expr_mutbl == Mutability::Not
491 && mutbl == Mutability::Mut
492 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
493 {
494 sugg_mutref = true;
495 }
496
497 if !sugg_mutref
498 && sugg == None
499 && fcx.may_coerce(
500 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
501 self.cast_ty,
502 )
503 {
504 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
505 }
506 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
507 && fcx.may_coerce(
508 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
509 self.cast_ty,
510 )
511 {
512 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
513 }
514 if sugg_mutref {
515 err.span_label(self.span, "invalid cast");
516 err.span_note(self.expr_span, "this reference is immutable");
517 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
518 } else if let Some((sugg, remove_cast)) = sugg {
519 err.span_label(self.span, "invalid cast");
520
521 let has_parens = fcx
522 .tcx
523 .sess
524 .source_map()
525 .span_to_snippet(self.expr_span)
526 .is_ok_and(|snip| snip.starts_with('('));
527
528 let needs_parens =
532 !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
hir::ExprKind::Cast(..) => true,
_ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
533
534 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)];
535 if needs_parens {
536 suggestion[0].1 += "(";
537 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
538 }
539 if remove_cast {
540 suggestion.push((
541 self.expr_span.shrink_to_hi().to(self.cast_span),
542 String::new(),
543 ));
544 }
545
546 err.multipart_suggestion(
547 "consider borrowing the value",
548 suggestion,
549 Applicability::MachineApplicable,
550 );
551 } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
_ => false,
}matches!(
552 self.cast_ty.kind(),
553 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
554 ) {
555 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
557 let ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
558 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
559 if fcx
560 .infcx
561 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
562 .must_apply_modulo_regions()
563 {
564 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
565 fcx.tcx.value_path_str_with_args(def.did(), args)
566 } else {
567 self.cast_ty.to_string()
568 };
569 err.multipart_suggestion(
570 "consider using the `From` trait instead",
571 ::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![
572 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
573 (
574 self.expr_span.shrink_to_hi().to(self.cast_span),
575 ")".to_string(),
576 ),
577 ],
578 Applicability::MaybeIncorrect,
579 );
580 }
581 }
582
583 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
584 && adt.is_enum()
585 && self.cast_ty.is_numeric()
586 {
587 (
588 "an `as` expression can be used to convert enum types to numeric \
589 types only if the enum type is unit-only or field-less",
590 Some(
591 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
592 ),
593 )
594 } else {
595 (
596 "an `as` expression can only be used to convert between primitive \
597 types or to coerce to a specific trait object",
598 None,
599 )
600 };
601
602 err.span_label(self.span, msg);
603
604 if let Some(note) = note {
605 err.note(note);
606 }
607 } else {
608 err.span_label(self.span, "invalid cast");
609 }
610
611 fcx.suggest_closure_to_fn_ptr_coercion(
612 &mut err,
613 self.expr,
614 self.cast_ty,
615 self.expr_ty,
616 );
617 self.try_suggest_collection_to_bool(fcx, &mut err);
618
619 err.emit();
620 }
621 CastError::SizedUnsizedCast => {
622 let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
623 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
624 fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer {
625 span: self.span,
626 expr_ty,
627 cast_ty,
628 teach: fcx.tcx.sess.teach(E0607),
629 });
630 }
631 CastError::IntToWideCast(known_metadata) => {
632 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
633 let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
634 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
635 let metadata = known_metadata.unwrap_or("type-specific metadata");
636 let known_wide = known_metadata.is_some();
637 let span = self.cast_span;
638 let param_note = (!known_wide)
639 .then(|| match cast_ty.kind() {
640 ty::RawPtr(pointee, _) => match pointee.kind() {
641 ty::Param(param) => {
642 Some(diagnostics::IntToWideParamNote { param: param.name })
643 }
644 _ => None,
645 },
646 _ => None,
647 })
648 .flatten();
649 fcx.dcx().emit_err(diagnostics::IntToWide {
650 span,
651 metadata,
652 expr_ty,
653 cast_ty,
654 expr_if_nightly,
655 known_wide,
656 param_note,
657 });
658 }
659 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
660 let unknown_cast_to = match e {
661 CastError::UnknownCastPtrKind => true,
662 CastError::UnknownExprPtrKind => false,
663 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:?}"),
664 };
665 let (span, sub) = if unknown_cast_to {
666 (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span))
667 } else {
668 (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span))
669 };
670 fcx.dcx().emit_err(diagnostics::CastUnknownPointer {
671 span,
672 to: unknown_cast_to,
673 sub,
674 });
675 }
676 CastError::CastEnumDrop => {
677 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
678 let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
679
680 fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty });
681 }
682 CastError::ForeignNonExhaustiveAdt => {
683 make_invalid_casting_error(
684 self.span,
685 self.expr_ty,
686 self.cast_ty,
687 fcx,
688 )
689 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
690 .emit();
691 }
692 CastError::PtrPtrAddingAutoTrait(added) => {
693 fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject {
694 span: self.span,
695 traits_len: added.len(),
696 traits: {
697 let mut traits: Vec<_> = added
698 .into_iter()
699 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
700 .collect();
701
702 traits.sort();
703 traits.into()
704 },
705 });
706 }
707 }
708 }
709
710 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
711 if let Err(err) = self.cast_ty.error_reported() {
712 return err;
713 }
714 if let Err(err) = self.expr_ty.error_reported() {
715 return err;
716 }
717
718 let tstr = fcx.ty_to_string(self.cast_ty);
719 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!(
720 fcx.dcx(),
721 self.span,
722 self.expr_ty,
723 E0620,
724 "cast to unsized type: `{}` as `{}`",
725 fcx.deeply_resolve_ignoring_regions(self.expr_ty),
726 tstr
727 );
728 match self.expr_ty.kind() {
729 ty::Ref(_, _, mt) => {
730 let mtstr = mt.prefix_str();
731 err.span_suggestion_verbose(
732 self.cast_span.shrink_to_lo(),
733 "consider casting to a reference instead",
734 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mtstr))
})format!("&{mtstr}"),
735 Applicability::MachineApplicable,
736 );
737 }
738 ty::Adt(def, ..) if def.is_box() => {
739 err.multipart_suggestion(
740 "you can cast to a `Box` instead",
741 ::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![
742 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
743 (self.cast_span.shrink_to_hi(), ">".to_string()),
744 ],
745 Applicability::MachineApplicable,
746 );
747 }
748 _ => {
749 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
750 }
751 }
752 err.emit_err()
753 }
754
755 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
756 if self.is_non_trivial_ref_trait_object_upcast(fcx) {
757 return;
758 }
759
760 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
761 (true, TRIVIAL_NUMERIC_CASTS)
762 } else {
763 (false, TRIVIAL_CASTS)
764 };
765 let expr_ty = fcx.deeply_resolve_ignoring_regions(self.expr_ty);
766 let cast_ty = fcx.deeply_resolve_ignoring_regions(self.cast_ty);
767 fcx.tcx.emit_node_span_lint(
768 lint,
769 self.expr.hir_id,
770 self.span,
771 diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
772 );
773 }
774
775 fn is_non_trivial_ref_trait_object_upcast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
780 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!(
781 (self.expr_ty.kind(), self.cast_ty.kind()),
782 (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _))
783 if matches!(
784 (from_ty.kind(), to_ty.kind()),
785 (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if from_data != to_data
786 )
787 ) {
788 return false;
789 }
790
791 let hir::Node::Expr(cast_expr) = fcx.tcx.parent_hir_node(self.expr.hir_id) else {
792 return false;
793 };
794 let hir::Node::Expr(parent) = fcx.tcx.parent_hir_node(cast_expr.hir_id) else {
795 return false;
796 };
797
798 #[allow(non_exhaustive_omitted_patterns)] match parent.kind {
hir::ExprKind::MethodCall(_, receiver, ..) if
receiver.hir_id == cast_expr.hir_id => true,
_ => false,
}matches!(
799 parent.kind,
800 hir::ExprKind::MethodCall(_, receiver, ..) if receiver.hir_id == cast_expr.hir_id
801 )
802 }
803
804 fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
805 if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
806 && fcx.deeply_resolve_ignoring_regions(self.expr_ty).is_ty_var()
807 && fcx.deeply_resolve_ignoring_regions(fcx.node_ty(idx.hir_id)).is_ty_var()
808 {
809 index_operand_ambiguity_span(idx)
810 } else {
811 self.expr_span
812 }
813 }
814
815 {}
#[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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(815u32),
::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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:830",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(830u32),
::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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:848",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(848u32),
::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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:851",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(851u32),
::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/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:860",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(860u32),
::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")]
816 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
817 let expr_span = self.expr_span_for_type_resolution(fcx);
818 self.expr_ty = fcx.structurally_resolve_type(expr_span, self.expr_ty);
819 self.cast_ty = fcx.deeply_resolve_ignoring_regions_with_obligations(self.cast_ty);
820 if self.cast_ty.is_ty_var() {
821 self.cast_ty = if let Some(guar) = self.try_report_ambiguous_binop_for_infer_cast(fcx) {
822 let err = Ty::new_error(fcx.tcx, guar);
823 fcx.demand_suptype(self.cast_span, err, self.cast_ty);
824 err
825 } else {
826 fcx.type_must_be_known_at_this_point(self.cast_span, self.cast_ty)
827 };
828 }
829
830 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
831
832 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
833 && !self.cast_ty.has_infer_types()
834 {
835 self.report_cast_to_unsized_type(fcx);
836 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
837 } else {
839 match self.try_coercion_cast(fcx) {
840 Ok(()) => {
841 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
842 debug!(" -> PointerCast");
849 } else {
850 self.trivial_cast_lint(fcx);
851 debug!(" -> CoercionCast");
852 fcx.typeck_results
853 .borrow_mut()
854 .set_coercion_cast(self.expr.hir_id.local_id);
855 }
856 }
857 Err(_) => {
858 match self.do_check(fcx) {
859 Ok(k) => {
860 debug!(" -> {:?}", k);
861 }
862 Err(e) => self.report_cast_error(fcx, e),
863 };
864 }
865 };
866 }
867 }
868
869 #[cold]
871 fn try_report_ambiguous_binop_for_infer_cast(
872 &self,
873 fcx: &FnCtxt<'a, 'tcx>,
874 ) -> Option<ErrorGuaranteed> {
875 let errors: Vec<_> = fcx
876 .fulfillment_cx
877 .borrow()
878 .pending_obligations()
879 .into_iter()
880 .filter_map(|mut obligation| {
881 let predicate = fcx.deeply_resolve_ignoring_regions(obligation.predicate);
882 if !#[allow(non_exhaustive_omitted_patterns)] match predicate.kind().skip_binder()
{
ty::PredicateKind::Clause(ty::ClauseKind::Trait(_)) => true,
_ => false,
}matches!(
883 predicate.kind().skip_binder(),
884 ty::PredicateKind::Clause(ty::ClauseKind::Trait(_))
885 ) {
886 return None;
887 }
888 let cast_span = self.cast_span;
889
890 let ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. } =
891 obligation.cause.code()
892 else {
893 return None;
894 };
895 let lhs_ty = fcx.deeply_resolve_ignoring_regions(fcx.node_ty(*lhs_hir_id));
896 let rhs_ty = fcx.deeply_resolve_ignoring_regions(fcx.node_ty(*rhs_hir_id));
897
898 if (fcx.tcx.hir_span(*lhs_hir_id).contains(cast_span)
899 && lhs_ty.contains(self.cast_ty))
900 || (rhs_span.contains(cast_span) && rhs_ty.contains(self.cast_ty))
901 {
902 obligation.cause.span = cast_span;
903 obligation.predicate = predicate;
904
905 let ocx = ObligationCtxt::new_with_diagnostics(&fcx.infcx);
906 ocx.register_obligation(obligation);
907 ocx.evaluate_obligations_error_on_ambiguity().into_iter().find(|error| {
908 #[allow(non_exhaustive_omitted_patterns)] match error.code {
traits::FulfillmentErrorCode::Ambiguity { overflow: None } => true,
_ => false,
}matches!(
909 error.code,
910 traits::FulfillmentErrorCode::Ambiguity { overflow: None }
911 )
912 })
913 } else {
914 None
915 }
916 })
917 .collect();
918
919 if errors.is_empty() {
920 None
921 } else {
922 Some(fcx.err_ctxt().report_fulfillment_errors(errors.into()))
923 }
924 }
925
926 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
930 use rustc_middle::ty::cast::CastTy::*;
931
932 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
933 {
934 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
935 (None, Some(t_cast)) => {
937 match *self.expr_ty.kind() {
938 ty::FnDef(..) => {
939 let f = fcx.normalize(
941 self.expr_span,
942 Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
943 );
944 let res = fcx.coerce(
945 self.expr,
946 self.expr_ty,
947 Ty::new_fn_ptr(fcx.tcx, f),
948 AllowTwoPhase::No,
949 None,
950 );
951 if let Err(TypeError::IntrinsicCast) = res {
952 return Err(CastError::IllegalCast);
953 }
954 if res.is_err() {
955 return Err(CastError::NonScalar);
956 }
957 (FnPtr, t_cast)
958 }
959 ty::Ref(_, inner_ty, mutbl) => {
964 return match t_cast {
965 Int | CEnum | Bool | Char | Float => match *inner_ty.kind() {
966 ty::Int(_)
967 | ty::Uint(_)
968 | ty::Float(_)
969 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
970 Err(CastError::NeedDeref)
971 }
972 _ => Err(CastError::NeedViaPtr),
973 },
974 Ptr(mt) => {
976 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
977 return Err(CastError::IllegalCast);
978 }
979 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
980 }
981 _ => Err(CastError::NonScalar),
982 };
983 }
984 _ => return Err(CastError::NonScalar),
985 }
986 }
987 _ => return Err(CastError::NonScalar),
988 };
989 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
990 && !adt_def.did().is_local()
991 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
992 {
993 return Err(CastError::ForeignNonExhaustiveAdt);
994 }
995 match (t_from, t_cast) {
996 (_, CEnum | FnPtr) => Err(CastError::NonScalar),
998
999 (_, Bool) => Err(CastError::CastToBool),
1001
1002 (Int, Char) if self.expr_ty == fcx.tcx.types.u8 => {
1004 Ok(CastKind::U8CharCast) }
1006 (_, Char) => Err(CastError::CastToChar),
1007
1008 (Bool | CEnum | Char, Float) => Err(CastError::NeedViaInt),
1010
1011 (Bool | CEnum | Char | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
1012 Err(CastError::IllegalCast)
1013 }
1014
1015 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), (Ptr(m_expr), Int) => self.check_ptr_addr_cast(fcx, m_expr),
1020
1021 (FnPtr, Int) => {
1022 Ok(CastKind::FnPtrAddrCast)
1024 }
1025 (Int, Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
1027 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
1029
1030 (CEnum, Int) => self.check_enum_cast(fcx),
1032
1033 (Char | Bool, Int) => Ok(CastKind::PrimIntCast),
1035
1036 (Int | Float, Int | Float) => Ok(CastKind::NumericCast),
1037 }
1038 }
1039
1040 fn check_ptr_ptr_cast(
1041 &self,
1042 fcx: &FnCtxt<'a, 'tcx>,
1043 m_src: ty::TypeAndMut<'tcx>,
1044 m_dst: ty::TypeAndMut<'tcx>,
1045 ) -> Result<CastKind, CastError<'tcx>> {
1046 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs:1046",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(1046u32),
::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:?}");
1047 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
1050 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
1051
1052 let Some(dst_kind) = dst_kind else {
1054 return Err(CastError::UnknownCastPtrKind);
1055 };
1056
1057 if dst_kind == PointerKind::Thin {
1059 return Ok(CastKind::PtrPtrCast);
1060 }
1061
1062 let Some(src_kind) = src_kind else {
1064 return Err(CastError::UnknownCastPtrKind);
1065 };
1066
1067 match (src_kind, dst_kind) {
1068 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
1070
1071 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
1073 match (src_tty.principal(), dst_tty.principal()) {
1074 (Some(src_principal), Some(_)) => {
1083 let tcx = fcx.tcx;
1084
1085 let src_obj = Ty::new_dynamic(
1093 tcx,
1094 tcx.mk_poly_existential_predicates(
1095 &src_tty.without_auto_traits().collect::<Vec<_>>(),
1096 ),
1097 tcx.lifetimes.re_erased,
1098 );
1099 let dst_obj = Ty::new_dynamic(
1100 tcx,
1101 tcx.mk_poly_existential_predicates(
1102 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1103 ),
1104 tcx.lifetimes.re_erased,
1105 );
1106
1107 let cause = fcx.misc(self.span);
1110 if fcx
1111 .at(&cause, fcx.param_env)
1112 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
1113 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
1114 .is_err()
1115 {
1116 return Err(CastError::DifferingKinds { src_kind, dst_kind });
1117 }
1118
1119 let src_auto: FxHashSet<_> = src_tty
1122 .auto_traits()
1123 .chain(
1124 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
1125 .filter(|def_id| tcx.trait_is_auto(*def_id)),
1126 )
1127 .collect();
1128
1129 let added = dst_tty
1130 .auto_traits()
1131 .filter(|trait_did| !src_auto.contains(trait_did))
1132 .collect::<Vec<_>>();
1133
1134 if !added.is_empty() {
1135 return Err(CastError::PtrPtrAddingAutoTrait(added));
1136 }
1137
1138 Ok(CastKind::PtrPtrCast)
1139 }
1140
1141 (None, None) => Ok(CastKind::PtrPtrCast),
1143
1144 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1174
1175 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1177 }
1178 }
1179
1180 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1182
1183 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1184 }
1185 }
1186
1187 fn check_fptr_ptr_cast(
1188 &self,
1189 fcx: &FnCtxt<'a, 'tcx>,
1190 m_cast: ty::TypeAndMut<'tcx>,
1191 ) -> Result<CastKind, CastError<'tcx>> {
1192 match fcx.pointer_kind(m_cast.ty, self.span)? {
1195 None => Err(CastError::UnknownCastPtrKind),
1196 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1197 _ => Err(CastError::IllegalCast),
1198 }
1199 }
1200
1201 fn check_ptr_addr_cast(
1202 &self,
1203 fcx: &FnCtxt<'a, 'tcx>,
1204 m_expr: ty::TypeAndMut<'tcx>,
1205 ) -> Result<CastKind, CastError<'tcx>> {
1206 match fcx.pointer_kind(m_expr.ty, self.span)? {
1209 None => Err(CastError::UnknownExprPtrKind),
1210 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1211 _ => Err(CastError::NeedViaThinPtr),
1212 }
1213 }
1214
1215 fn check_ref_cast(
1216 &self,
1217 fcx: &FnCtxt<'a, 'tcx>,
1218 mut m_expr: ty::TypeAndMut<'tcx>,
1219 mut m_cast: ty::TypeAndMut<'tcx>,
1220 ) -> Result<CastKind, CastError<'tcx>> {
1221 m_expr.ty = fcx.deeply_resolve_ignoring_regions_with_obligations(m_expr.ty);
1223 m_cast.ty = fcx.deeply_resolve_ignoring_regions_with_obligations(m_cast.ty);
1224
1225 if m_expr.mutbl >= m_cast.mutbl
1226 && let ty::Array(ety, _) = m_expr.ty.kind()
1227 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1228 {
1229 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1234 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1235 .unwrap_or_else(|_| {
1236 ::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!(
1237 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1238 self.expr_ty,
1239 array_ptr_type,
1240 )
1241 });
1242
1243 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1245 return Ok(CastKind::ArrayPtrCast);
1246 }
1247
1248 Err(CastError::IllegalCast)
1249 }
1250
1251 fn check_addr_ptr_cast(
1252 &self,
1253 fcx: &FnCtxt<'a, 'tcx>,
1254 m_cast: TypeAndMut<'tcx>,
1255 ) -> Result<CastKind, CastError<'tcx>> {
1256 match fcx.pointer_kind(m_cast.ty, self.span)? {
1258 None => Err(CastError::UnknownCastPtrKind),
1259 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1260 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1261 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1262 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1263 Err(CastError::IntToWideCast(None))
1264 }
1265 }
1266 }
1267
1268 fn check_enum_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
1269 if let ty::Adt(d, _) = self.expr_ty.kind()
1270 && d.has_dtor(fcx.tcx)
1271 {
1272 Err(CastError::CastEnumDrop)
1273 } else {
1274 Ok(CastKind::EnumCast)
1275 }
1276 }
1277
1278 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1279 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1280 Ok(_) => Ok(()),
1281 Err(err) => Err(err),
1282 }
1283 }
1284
1285 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1288 if self.cast_ty.is_bool() {
1289 let derefed = fcx
1290 .autoderef(self.expr_span, self.expr_ty)
1291 .silence_errors()
1292 .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(..)));
1293
1294 if let Some((deref_ty, _)) = derefed {
1295 if deref_ty != self.expr_ty.peel_refs() {
1297 err.subdiagnostic(diagnostics::DerefImplsIsEmpty {
1298 span: self.expr_span,
1299 deref_ty,
1300 });
1301 }
1302
1303 err.subdiagnostic(diagnostics::UseIsEmpty {
1306 lo: self.expr_span.shrink_to_lo(),
1307 hi: self.span.with_lo(self.expr_span.hi()),
1308 expr_ty: self.expr_ty,
1309 });
1310 }
1311 }
1312 }
1313}
1314
1315fn index_operand_ambiguity_span(expr: &hir::Expr<'_>) -> Span {
1316 match expr.kind {
1317 hir::ExprKind::MethodCall(segment, ..) => segment.ident.span,
1318 _ => expr.span,
1319 }
1320}