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_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::mir::Mutability;
39use rustc_middle::ty::adjustment::AllowTwoPhase;
40use rustc_middle::ty::cast::{CastKind, CastTy};
41use rustc_middle::ty::error::TypeError;
42use rustc_middle::ty::{
43 self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, Unnormalized, VariantDef, elaborate,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::lint;
47use rustc_span::{DUMMY_SP, Span, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use tracing::{debug, instrument};
50
51use super::FnCtxt;
52use crate::{diagnostics, type_error_struct};
53
54#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CastCheck<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["expr", "expr_ty", "expr_span", "cast_ty", "cast_span", "span",
"body_def_id"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.expr, &self.expr_ty, &self.expr_span, &self.cast_ty,
&self.cast_span, &self.span, &&self.body_def_id];
::core::fmt::Formatter::debug_struct_fields_finish(f, "CastCheck",
names, values)
}
}Debug)]
57pub(crate) struct CastCheck<'tcx> {
58 expr: &'tcx hir::Expr<'tcx>,
60 expr_ty: Ty<'tcx>,
62 expr_span: Span,
63 cast_ty: Ty<'tcx>,
65 cast_span: Span,
66 span: Span,
67 pub body_def_id: LocalDefId,
68}
69
70#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PointerKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PointerKind::Thin => ::core::fmt::Formatter::write_str(f, "Thin"),
PointerKind::VTable(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "VTable",
&__self_0),
PointerKind::Length =>
::core::fmt::Formatter::write_str(f, "Length"),
PointerKind::OfAlias(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfAlias", &__self_0),
PointerKind::OfParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfParam", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PointerKind<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for PointerKind<'tcx> {
#[inline]
fn clone(&self) -> PointerKind<'tcx> {
let _:
::core::clone::AssertParamIsClone<&'tcx ty::List<ty::Binder<'tcx,
ty::ExistentialPredicate<'tcx>>>>;
let _: ::core::clone::AssertParamIsClone<ty::AliasTy<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::ParamTy>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PointerKind<'tcx> {
#[inline]
fn eq(&self, other: &PointerKind<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PointerKind::VTable(__self_0), PointerKind::VTable(__arg1_0))
=> __self_0 == __arg1_0,
(PointerKind::OfAlias(__self_0),
PointerKind::OfAlias(__arg1_0)) => __self_0 == __arg1_0,
(PointerKind::OfParam(__self_0),
PointerKind::OfParam(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for PointerKind<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<&'tcx ty::List<ty::Binder<'tcx,
ty::ExistentialPredicate<'tcx>>>>;
let _: ::core::cmp::AssertParamIsEq<ty::AliasTy<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<ty::ParamTy>;
}
}Eq, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for PointerKind<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
PointerKind::Thin => {}
PointerKind::VTable(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
PointerKind::Length => {}
PointerKind::OfAlias(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
PointerKind::OfParam(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for PointerKind<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
PointerKind::Thin => { PointerKind::Thin }
PointerKind::VTable(__binding_0) => {
PointerKind::VTable(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
PointerKind::Length => { PointerKind::Length }
PointerKind::OfAlias(__binding_0) => {
PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
PointerKind::OfParam(__binding_0) => {
PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
PointerKind::Thin => { PointerKind::Thin }
PointerKind::VTable(__binding_0) => {
PointerKind::VTable(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
PointerKind::Length => { PointerKind::Length }
PointerKind::OfAlias(__binding_0) => {
PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
PointerKind::OfParam(__binding_0) => {
PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable)]
74enum PointerKind<'tcx> {
75 Thin,
77 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
79 Length,
81 OfAlias(ty::AliasTy<'tcx>),
83 OfParam(ty::ParamTy),
85}
86
87impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
88 fn pointer_kind(
91 &self,
92 t: Ty<'tcx>,
93 span: Span,
94 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
95 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:95",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(95u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
t, span) as &dyn Value))])
});
} else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
96
97 let t = self.resolve_vars_if_possible(t);
98 t.error_reported()?;
99
100 if self.type_is_sized_modulo_regions(self.param_env, t) {
101 return Ok(Some(PointerKind::Thin));
102 }
103
104 let t = self.resolve_vars_with_obligations(t);
105
106 Ok(match *t.kind() {
107 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
108 ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
109 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
110 None => Some(PointerKind::Thin),
111 Some(f) => {
112 let field_ty = self.field_ty(span, f, args);
113 self.pointer_kind(field_ty, span)?
114 }
115 },
116 ty::Tuple(fields) => match fields.last() {
117 None => Some(PointerKind::Thin),
118 Some(&f) => self.pointer_kind(f, span)?,
119 },
120
121 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
122
123 ty::Foreign(..) => Some(PointerKind::Thin),
125 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
127 ty::Param(p) => Some(PointerKind::OfParam(p)),
128 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
130
131 ty::Bool
132 | ty::Char
133 | ty::Int(..)
134 | ty::Uint(..)
135 | ty::Float(_)
136 | ty::Array(..)
137 | ty::CoroutineWitness(..)
138 | ty::RawPtr(_, _)
139 | ty::Ref(..)
140 | ty::Pat(..)
141 | ty::FnDef(..)
142 | ty::FnPtr(..)
143 | ty::Closure(..)
144 | ty::CoroutineClosure(..)
145 | ty::Coroutine(..)
146 | ty::Adt(..)
147 | ty::Never
148 | ty::Error(_) => {
149 let guar = self
150 .dcx()
151 .span_delayed_bug(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0:?}` should be sized but is not?",
t))
})format!("`{t:?}` should be sized but is not?"));
152 return Err(guar);
153 }
154 })
155 }
156}
157
158#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CastError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CastError::ErrorGuaranteed(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ErrorGuaranteed", &__self_0),
CastError::CastToBool =>
::core::fmt::Formatter::write_str(f, "CastToBool"),
CastError::CastToChar =>
::core::fmt::Formatter::write_str(f, "CastToChar"),
CastError::DifferingKinds { src_kind: __self_0, dst_kind: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"DifferingKinds", "src_kind", __self_0, "dst_kind",
&__self_1),
CastError::SizedUnsizedCast =>
::core::fmt::Formatter::write_str(f, "SizedUnsizedCast"),
CastError::IllegalCast =>
::core::fmt::Formatter::write_str(f, "IllegalCast"),
CastError::NeedDeref =>
::core::fmt::Formatter::write_str(f, "NeedDeref"),
CastError::NeedViaPtr =>
::core::fmt::Formatter::write_str(f, "NeedViaPtr"),
CastError::NeedViaThinPtr =>
::core::fmt::Formatter::write_str(f, "NeedViaThinPtr"),
CastError::NeedViaInt =>
::core::fmt::Formatter::write_str(f, "NeedViaInt"),
CastError::NonScalar =>
::core::fmt::Formatter::write_str(f, "NonScalar"),
CastError::UnknownExprPtrKind =>
::core::fmt::Formatter::write_str(f, "UnknownExprPtrKind"),
CastError::UnknownCastPtrKind =>
::core::fmt::Formatter::write_str(f, "UnknownCastPtrKind"),
CastError::CastEnumDrop =>
::core::fmt::Formatter::write_str(f, "CastEnumDrop"),
CastError::IntToWideCast(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IntToWideCast", &__self_0),
CastError::ForeignNonExhaustiveAdt =>
::core::fmt::Formatter::write_str(f,
"ForeignNonExhaustiveAdt"),
CastError::PtrPtrAddingAutoTrait(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PtrPtrAddingAutoTrait", &__self_0),
}
}
}Debug)]
159enum CastError<'tcx> {
160 ErrorGuaranteed(ErrorGuaranteed),
161
162 CastToBool,
163 CastToChar,
164 DifferingKinds {
165 src_kind: PointerKind<'tcx>,
166 dst_kind: PointerKind<'tcx>,
167 },
168 SizedUnsizedCast,
170 IllegalCast,
171 NeedDeref,
172 NeedViaPtr,
173 NeedViaThinPtr,
174 NeedViaInt,
175 NonScalar,
176 UnknownExprPtrKind,
177 UnknownCastPtrKind,
178 CastEnumDrop,
179 IntToWideCast(Option<&'static str>),
185 ForeignNonExhaustiveAdt,
186 PtrPtrAddingAutoTrait(Vec<DefId>),
187}
188
189impl From<ErrorGuaranteed> for CastError<'_> {
190 fn from(err: ErrorGuaranteed) -> Self {
191 CastError::ErrorGuaranteed(err)
192 }
193}
194
195fn make_invalid_casting_error<'a, 'tcx>(
196 span: Span,
197 expr_ty: Ty<'tcx>,
198 cast_ty: Ty<'tcx>,
199 fcx: &FnCtxt<'a, 'tcx>,
200) -> Diag<'a> {
201 {
let mut err =
{
fcx.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("casting `{0}` as `{1}` is invalid",
fcx.ty_to_string(expr_ty), fcx.ty_to_string(cast_ty)))
})).with_code(E0606)
};
if expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
202 fcx.dcx(),
203 span,
204 expr_ty,
205 E0606,
206 "casting `{}` as `{}` is invalid",
207 fcx.ty_to_string(expr_ty),
208 fcx.ty_to_string(cast_ty)
209 )
210}
211
212pub fn check_cast<'tcx>(
217 tcx: TyCtxt<'tcx>,
218 param_env: ty::ParamEnv<'tcx>,
219 e: &'tcx hir::Expr<'tcx>,
220 from_ty: Ty<'tcx>,
221 to_ty: Ty<'tcx>,
222) -> Option<CastKind> {
223 let hir_id = e.hir_id;
224 let local_def_id = hir_id.owner.def_id;
225
226 let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
227 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
228
229 if let Ok(check) = CastCheck::new(
230 &fn_ctxt, e, from_ty, to_ty,
231 DUMMY_SP, DUMMY_SP,
233 ) {
234 check.do_check(&fn_ctxt).ok()
235 } else {
236 None
237 }
238}
239
240impl<'a, 'tcx> CastCheck<'tcx> {
241 pub(crate) fn new(
242 fcx: &FnCtxt<'a, 'tcx>,
243 expr: &'tcx hir::Expr<'tcx>,
244 expr_ty: Ty<'tcx>,
245 cast_ty: Ty<'tcx>,
246 cast_span: Span,
247 span: Span,
248 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
249 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
250 let check = CastCheck {
251 expr,
252 expr_ty,
253 expr_span,
254 cast_ty,
255 cast_span,
256 span,
257 body_def_id: fcx.body_def_id,
258 };
259
260 match cast_ty.kind() {
264 ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
265 _ => Ok(check),
266 }
267 }
268
269 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
270 match e {
271 CastError::ErrorGuaranteed(_) => {
272 }
274 CastError::NeedDeref => {
275 let mut err =
276 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
277
278 if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
279 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
281 err.span_suggestion_verbose(
282 span,
283 "remove the unneeded borrow",
284 "",
285 Applicability::MachineApplicable,
286 );
287 } else {
288 err.span_suggestion_verbose(
289 self.expr_span.shrink_to_lo(),
290 "dereference the expression",
291 "*",
292 Applicability::MachineApplicable,
293 );
294 }
295
296 err.emit();
297 }
298 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
299 let mut err =
300 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
301
302 if self.cast_ty.is_integral() {
303 if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
304 && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
305 && let ty::Adt(adt_def, _) = *inner_ty.kind()
306 && adt_def.is_enum()
307 && adt_def.is_payloadfree()
308 {
309 err.span_suggestion_verbose(
310 self.expr_span.shrink_to_lo(),
311 "try dereferencing before the cast",
312 "*",
313 Applicability::MaybeIncorrect,
314 );
315 if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
316 err.span_suggestion_verbose(
317 fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
318 "add `#[derive(Copy, Clone)]` to the enum definition",
319 "#[derive(Copy, Clone)]\n",
320 Applicability::MaybeIncorrect,
321 );
322 }
323 } else {
324 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cast through {0} first",
match e {
CastError::NeedViaPtr => "a raw pointer",
CastError::NeedViaThinPtr => "a thin pointer",
e => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("control flow means we should never encounter a {0:?}",
e)));
}
}))
})format!(
325 "cast through {} first",
326 match e {
327 CastError::NeedViaPtr => "a raw pointer",
328 CastError::NeedViaThinPtr => "a thin pointer",
329 e => unreachable!(
330 "control flow means we should never encounter a {e:?}"
331 ),
332 }
333 ));
334 }
335 }
336
337 self.try_suggest_collection_to_bool(fcx, &mut err);
338
339 err.emit();
340 }
341 CastError::NeedViaInt => {
342 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
343 .with_help("cast through an integer first")
344 .emit();
345 }
346 CastError::IllegalCast => {
347 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
348 }
349 CastError::DifferingKinds { src_kind, dst_kind } => {
350 let mut err =
351 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
352
353 match (src_kind, dst_kind) {
354 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
355 err.note("the trait objects may have different vtables");
356 }
357 (
358 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
359 PointerKind::OfParam(_)
360 | PointerKind::OfAlias(_)
361 | PointerKind::VTable(_)
362 | PointerKind::Length,
363 )
364 | (
365 PointerKind::VTable(_) | PointerKind::Length,
366 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
367 ) => {
368 err.note("the pointers may have different metadata");
369 }
370 (PointerKind::VTable(_), PointerKind::Length)
371 | (PointerKind::Length, PointerKind::VTable(_)) => {
372 err.note("the pointers have different metadata");
373 }
374 (
375 PointerKind::Thin,
376 PointerKind::Thin
377 | PointerKind::VTable(_)
378 | PointerKind::Length
379 | PointerKind::OfParam(_)
380 | PointerKind::OfAlias(_),
381 )
382 | (
383 PointerKind::VTable(_)
384 | PointerKind::Length
385 | PointerKind::OfParam(_)
386 | PointerKind::OfAlias(_),
387 PointerKind::Thin,
388 )
389 | (PointerKind::Length, PointerKind::Length) => {
390 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected cast error: {0:?}", e))span_bug!(self.span, "unexpected cast error: {e:?}")
391 }
392 }
393
394 err.emit();
395 }
396 CastError::CastToBool => {
397 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
398 let help = if self.expr_ty.is_numeric() {
399 diagnostics::CannotCastToBoolHelp::Numeric(
400 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
401 )
402 } else {
403 diagnostics::CannotCastToBoolHelp::Unsupported(self.span)
404 };
405 fcx.dcx().emit_err(diagnostics::CannotCastToBool {
406 span: self.span,
407 expr_ty,
408 help,
409 });
410 }
411 CastError::CastToChar => {
412 let mut err = {
let mut err =
{
fcx.dcx().struct_span_err(self.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("only `u8` can be cast as `char`, not `{0}`",
self.expr_ty))
})).with_code(E0604)
};
if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
413 fcx.dcx(),
414 self.span,
415 self.expr_ty,
416 E0604,
417 "only `u8` can be cast as `char`, not `{}`",
418 self.expr_ty
419 );
420 err.span_label(self.span, "invalid cast");
421 if self.expr_ty.is_numeric() {
422 if self.expr_ty == fcx.tcx.types.u32 {
423 err.multipart_suggestion(
424 "consider using `char::from_u32` instead",
425 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
(self.expr_span.shrink_to_hi().to(self.cast_span),
")".to_string())]))vec![
426 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
427 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
428 ],
429 Applicability::MachineApplicable,
430 );
431 } else if self.expr_ty == fcx.tcx.types.i8 {
432 err.span_help(self.span, "consider casting from `u8` instead");
433 } else {
434 err.span_help(
435 self.span,
436 "consider using `char::from_u32` instead (via a `u32`)",
437 );
438 };
439 }
440 err.emit();
441 }
442 CastError::NonScalar => {
443 let mut err = {
let mut err =
{
fcx.dcx().struct_span_err(self.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("non-primitive cast: `{0}` as `{1}`",
self.expr_ty, fcx.ty_to_string(self.cast_ty)))
})).with_code(E0605)
};
if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
444 fcx.dcx(),
445 self.span,
446 self.expr_ty,
447 E0605,
448 "non-primitive cast: `{}` as `{}`",
449 self.expr_ty,
450 fcx.ty_to_string(self.cast_ty)
451 );
452
453 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
454 && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
455 {
456 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
snippet))
})format!(
457 "casting reference expression `{}` because `&` binds tighter than `as`",
458 snippet
459 ));
460 }
461
462 let mut sugg = None;
463 let mut sugg_mutref = false;
464 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
465 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
466 && fcx.may_coerce(
467 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
468 self.cast_ty,
469 )
470 {
471 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
})format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
472 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
473 && expr_mutbl == Mutability::Not
474 && mutbl == Mutability::Mut
475 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
476 {
477 sugg_mutref = true;
478 }
479
480 if !sugg_mutref
481 && sugg == None
482 && fcx.may_coerce(
483 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
484 self.cast_ty,
485 )
486 {
487 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
488 }
489 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
490 && fcx.may_coerce(
491 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
492 self.cast_ty,
493 )
494 {
495 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
496 }
497 if sugg_mutref {
498 err.span_label(self.span, "invalid cast");
499 err.span_note(self.expr_span, "this reference is immutable");
500 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
501 } else if let Some((sugg, remove_cast)) = sugg {
502 err.span_label(self.span, "invalid cast");
503
504 let has_parens = fcx
505 .tcx
506 .sess
507 .source_map()
508 .span_to_snippet(self.expr_span)
509 .is_ok_and(|snip| snip.starts_with('('));
510
511 let needs_parens =
515 !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
hir::ExprKind::Cast(..) => true,
_ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
516
517 let mut suggestion = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.expr_span.shrink_to_lo(), sugg)]))vec![(self.expr_span.shrink_to_lo(), sugg)];
518 if needs_parens {
519 suggestion[0].1 += "(";
520 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
521 }
522 if remove_cast {
523 suggestion.push((
524 self.expr_span.shrink_to_hi().to(self.cast_span),
525 String::new(),
526 ));
527 }
528
529 err.multipart_suggestion(
530 "consider borrowing the value",
531 suggestion,
532 Applicability::MachineApplicable,
533 );
534 } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
_ => false,
}matches!(
535 self.cast_ty.kind(),
536 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
537 ) {
538 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
540 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
541 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
542 if fcx
543 .infcx
544 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
545 .must_apply_modulo_regions()
546 {
547 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
548 fcx.tcx.value_path_str_with_args(def.did(), args)
549 } else {
550 self.cast_ty.to_string()
551 };
552 err.multipart_suggestion(
553 "consider using the `From` trait instead",
554 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.expr_span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::from(", to_ty))
})),
(self.expr_span.shrink_to_hi().to(self.cast_span),
")".to_string())]))vec![
555 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
556 (
557 self.expr_span.shrink_to_hi().to(self.cast_span),
558 ")".to_string(),
559 ),
560 ],
561 Applicability::MaybeIncorrect,
562 );
563 }
564 }
565
566 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
567 && adt.is_enum()
568 && self.cast_ty.is_numeric()
569 {
570 (
571 "an `as` expression can be used to convert enum types to numeric \
572 types only if the enum type is unit-only or field-less",
573 Some(
574 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
575 ),
576 )
577 } else {
578 (
579 "an `as` expression can only be used to convert between primitive \
580 types or to coerce to a specific trait object",
581 None,
582 )
583 };
584
585 err.span_label(self.span, msg);
586
587 if let Some(note) = note {
588 err.note(note);
589 }
590 } else {
591 err.span_label(self.span, "invalid cast");
592 }
593
594 fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
595 self.try_suggest_collection_to_bool(fcx, &mut err);
596
597 err.emit();
598 }
599 CastError::SizedUnsizedCast => {
600 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
601 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
602 fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer {
603 span: self.span,
604 expr_ty,
605 cast_ty,
606 teach: fcx.tcx.sess.teach(E0607),
607 });
608 }
609 CastError::IntToWideCast(known_metadata) => {
610 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
611 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
612 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
613 let metadata = known_metadata.unwrap_or("type-specific metadata");
614 let known_wide = known_metadata.is_some();
615 let span = self.cast_span;
616 let param_note = (!known_wide)
617 .then(|| match cast_ty.kind() {
618 ty::RawPtr(pointee, _) => match pointee.kind() {
619 ty::Param(param) => {
620 Some(diagnostics::IntToWideParamNote { param: param.name })
621 }
622 _ => None,
623 },
624 _ => None,
625 })
626 .flatten();
627 fcx.dcx().emit_err(diagnostics::IntToWide {
628 span,
629 metadata,
630 expr_ty,
631 cast_ty,
632 expr_if_nightly,
633 known_wide,
634 param_note,
635 });
636 }
637 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
638 let unknown_cast_to = match e {
639 CastError::UnknownCastPtrKind => true,
640 CastError::UnknownExprPtrKind => false,
641 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:?}"),
642 };
643 let (span, sub) = if unknown_cast_to {
644 (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span))
645 } else {
646 (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span))
647 };
648 fcx.dcx().emit_err(diagnostics::CastUnknownPointer {
649 span,
650 to: unknown_cast_to,
651 sub,
652 });
653 }
654 CastError::CastEnumDrop => {
655 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
656 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
657
658 fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty });
659 }
660 CastError::ForeignNonExhaustiveAdt => {
661 make_invalid_casting_error(
662 self.span,
663 self.expr_ty,
664 self.cast_ty,
665 fcx,
666 )
667 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
668 .emit();
669 }
670 CastError::PtrPtrAddingAutoTrait(added) => {
671 fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject {
672 span: self.span,
673 traits_len: added.len(),
674 traits: {
675 let mut traits: Vec<_> = added
676 .into_iter()
677 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
678 .collect();
679
680 traits.sort();
681 traits.into()
682 },
683 });
684 }
685 }
686 }
687
688 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
689 if let Err(err) = self.cast_ty.error_reported() {
690 return err;
691 }
692 if let Err(err) = self.expr_ty.error_reported() {
693 return err;
694 }
695
696 let tstr = fcx.ty_to_string(self.cast_ty);
697 let mut err = {
let mut err =
{
fcx.dcx().struct_span_err(self.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cast to unsized type: `{0}` as `{1}`",
fcx.resolve_vars_if_possible(self.expr_ty), tstr))
})).with_code(E0620)
};
if self.expr_ty.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
698 fcx.dcx(),
699 self.span,
700 self.expr_ty,
701 E0620,
702 "cast to unsized type: `{}` as `{}`",
703 fcx.resolve_vars_if_possible(self.expr_ty),
704 tstr
705 );
706 match self.expr_ty.kind() {
707 ty::Ref(_, _, mt) => {
708 let mtstr = mt.prefix_str();
709 err.span_suggestion_verbose(
710 self.cast_span.shrink_to_lo(),
711 "consider casting to a reference instead",
712 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mtstr))
})format!("&{mtstr}"),
713 Applicability::MachineApplicable,
714 );
715 }
716 ty::Adt(def, ..) if def.is_box() => {
717 err.multipart_suggestion(
718 "you can cast to a `Box` instead",
719 ::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![
720 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
721 (self.cast_span.shrink_to_hi(), ">".to_string()),
722 ],
723 Applicability::MachineApplicable,
724 );
725 }
726 _ => {
727 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
728 }
729 }
730 err.emit()
731 }
732
733 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
734 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
735 (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
736 } else {
737 (false, lint::builtin::TRIVIAL_CASTS)
738 };
739 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
740 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
741 fcx.tcx.emit_node_span_lint(
742 lint,
743 self.expr.hir_id,
744 self.span,
745 diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
746 );
747 }
748
749 fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
750 if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
751 && fcx.resolve_vars_if_possible(self.expr_ty).is_ty_var()
752 && fcx.resolve_vars_if_possible(fcx.node_ty(idx.hir_id)).is_ty_var()
753 {
754 index_operand_ambiguity_span(idx)
755 } else {
756 self.expr_span
757 }
758 }
759
760 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(760u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["self"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let expr_span = self.expr_span_for_type_resolution(fcx);
self.expr_ty =
fcx.structurally_resolve_type(expr_span, self.expr_ty);
self.cast_ty =
fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:766",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(766u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_cast({0}, {1:?} as {2:?})",
self.expr.hir_id, self.expr_ty, self.cast_ty) as
&dyn Value))])
});
} else { ; }
};
if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
&& !self.cast_ty.has_infer_types() {
self.report_cast_to_unsized_type(fcx);
} else if self.expr_ty.references_error() ||
self.cast_ty.references_error()
{} else {
match self.try_coercion_cast(fcx) {
Ok(()) => {
if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:784",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(784u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> PointerCast")
as &dyn Value))])
});
} else { ; }
};
} else {
self.trivial_cast_lint(fcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:787",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(787u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> CoercionCast")
as &dyn Value))])
});
} else { ; }
};
fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
}
}
Err(_) => {
match self.do_check(fcx) {
Ok(k) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:796",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(796u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> {0:?}",
k) as &dyn Value))])
});
} else { ; }
};
}
Err(e) => self.report_cast_error(fcx, e),
};
}
};
}
}
}
}#[instrument(skip(fcx), level = "debug")]
761 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
762 let expr_span = self.expr_span_for_type_resolution(fcx);
763 self.expr_ty = fcx.structurally_resolve_type(expr_span, self.expr_ty);
764 self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
765
766 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
767
768 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
769 && !self.cast_ty.has_infer_types()
770 {
771 self.report_cast_to_unsized_type(fcx);
772 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
773 } else {
775 match self.try_coercion_cast(fcx) {
776 Ok(()) => {
777 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
778 debug!(" -> PointerCast");
785 } else {
786 self.trivial_cast_lint(fcx);
787 debug!(" -> CoercionCast");
788 fcx.typeck_results
789 .borrow_mut()
790 .set_coercion_cast(self.expr.hir_id.local_id);
791 }
792 }
793 Err(_) => {
794 match self.do_check(fcx) {
795 Ok(k) => {
796 debug!(" -> {:?}", k);
797 }
798 Err(e) => self.report_cast_error(fcx, e),
799 };
800 }
801 };
802 }
803 }
804 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
808 use rustc_middle::ty::cast::CastTy::*;
809 use rustc_middle::ty::cast::IntTy::*;
810
811 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
812 {
813 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
814 (None, Some(t_cast)) => {
816 match *self.expr_ty.kind() {
817 ty::FnDef(..) => {
818 let f = fcx.normalize(
820 self.expr_span,
821 Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
822 );
823 let res = fcx.coerce(
824 self.expr,
825 self.expr_ty,
826 Ty::new_fn_ptr(fcx.tcx, f),
827 AllowTwoPhase::No,
828 None,
829 );
830 if let Err(TypeError::IntrinsicCast) = res {
831 return Err(CastError::IllegalCast);
832 }
833 if res.is_err() {
834 return Err(CastError::NonScalar);
835 }
836 (FnPtr, t_cast)
837 }
838 ty::Ref(_, inner_ty, mutbl) => {
843 return match t_cast {
844 Int(_) | Float => match *inner_ty.kind() {
845 ty::Int(_)
846 | ty::Uint(_)
847 | ty::Float(_)
848 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
849 Err(CastError::NeedDeref)
850 }
851 _ => Err(CastError::NeedViaPtr),
852 },
853 Ptr(mt) => {
855 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
856 return Err(CastError::IllegalCast);
857 }
858 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
859 }
860 _ => Err(CastError::NonScalar),
861 };
862 }
863 _ => return Err(CastError::NonScalar),
864 }
865 }
866 _ => return Err(CastError::NonScalar),
867 };
868 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
869 && !adt_def.did().is_local()
870 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
871 {
872 return Err(CastError::ForeignNonExhaustiveAdt);
873 }
874 match (t_from, t_cast) {
875 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
877
878 (_, Int(Bool)) => Err(CastError::CastToBool),
880
881 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
884
885 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
887
888 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
889 Err(CastError::IllegalCast)
890 }
891
892 (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),
897
898 (FnPtr, Int(_)) => {
899 Ok(CastKind::FnPtrAddrCast)
901 }
902 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
904 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
906
907 (Int(CEnum), Int(_)) => self.check_enum_cast(fcx),
909
910 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
912
913 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
914 }
915 }
916
917 fn check_ptr_ptr_cast(
918 &self,
919 fcx: &FnCtxt<'a, 'tcx>,
920 m_src: ty::TypeAndMut<'tcx>,
921 m_dst: ty::TypeAndMut<'tcx>,
922 ) -> Result<CastKind, CastError<'tcx>> {
923 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:923",
"rustc_hir_typeck::cast", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/cast.rs"),
::tracing_core::__macro_support::Option::Some(923u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_ptr_ptr_cast m_src={0:?} m_dst={1:?}",
m_src, m_dst) as &dyn Value))])
});
} else { ; }
};debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
924 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
927 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
928
929 let Some(dst_kind) = dst_kind else {
931 return Err(CastError::UnknownCastPtrKind);
932 };
933
934 if dst_kind == PointerKind::Thin {
936 return Ok(CastKind::PtrPtrCast);
937 }
938
939 let Some(src_kind) = src_kind else {
941 return Err(CastError::UnknownCastPtrKind);
942 };
943
944 match (src_kind, dst_kind) {
945 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
947
948 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
950 match (src_tty.principal(), dst_tty.principal()) {
951 (Some(src_principal), Some(_)) => {
960 let tcx = fcx.tcx;
961
962 let src_obj = Ty::new_dynamic(
970 tcx,
971 tcx.mk_poly_existential_predicates(
972 &src_tty.without_auto_traits().collect::<Vec<_>>(),
973 ),
974 tcx.lifetimes.re_erased,
975 );
976 let dst_obj = Ty::new_dynamic(
977 tcx,
978 tcx.mk_poly_existential_predicates(
979 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
980 ),
981 tcx.lifetimes.re_erased,
982 );
983
984 let cause = fcx.misc(self.span);
987 if fcx
988 .at(&cause, fcx.param_env)
989 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
990 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
991 .is_err()
992 {
993 return Err(CastError::DifferingKinds { src_kind, dst_kind });
994 }
995
996 let src_auto: FxHashSet<_> = src_tty
999 .auto_traits()
1000 .chain(
1001 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
1002 .filter(|def_id| tcx.trait_is_auto(*def_id)),
1003 )
1004 .collect();
1005
1006 let added = dst_tty
1007 .auto_traits()
1008 .filter(|trait_did| !src_auto.contains(trait_did))
1009 .collect::<Vec<_>>();
1010
1011 if !added.is_empty() {
1012 return Err(CastError::PtrPtrAddingAutoTrait(added));
1013 }
1014
1015 Ok(CastKind::PtrPtrCast)
1016 }
1017
1018 (None, None) => Ok(CastKind::PtrPtrCast),
1020
1021 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1051
1052 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1054 }
1055 }
1056
1057 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1059
1060 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1061 }
1062 }
1063
1064 fn check_fptr_ptr_cast(
1065 &self,
1066 fcx: &FnCtxt<'a, 'tcx>,
1067 m_cast: ty::TypeAndMut<'tcx>,
1068 ) -> Result<CastKind, CastError<'tcx>> {
1069 match fcx.pointer_kind(m_cast.ty, self.span)? {
1072 None => Err(CastError::UnknownCastPtrKind),
1073 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1074 _ => Err(CastError::IllegalCast),
1075 }
1076 }
1077
1078 fn check_ptr_addr_cast(
1079 &self,
1080 fcx: &FnCtxt<'a, 'tcx>,
1081 m_expr: ty::TypeAndMut<'tcx>,
1082 ) -> Result<CastKind, CastError<'tcx>> {
1083 match fcx.pointer_kind(m_expr.ty, self.span)? {
1086 None => Err(CastError::UnknownExprPtrKind),
1087 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1088 _ => Err(CastError::NeedViaThinPtr),
1089 }
1090 }
1091
1092 fn check_ref_cast(
1093 &self,
1094 fcx: &FnCtxt<'a, 'tcx>,
1095 mut m_expr: ty::TypeAndMut<'tcx>,
1096 mut m_cast: ty::TypeAndMut<'tcx>,
1097 ) -> Result<CastKind, CastError<'tcx>> {
1098 m_expr.ty = fcx.resolve_vars_with_obligations(m_expr.ty);
1100 m_cast.ty = fcx.resolve_vars_with_obligations(m_cast.ty);
1101
1102 if m_expr.mutbl >= m_cast.mutbl
1103 && let ty::Array(ety, _) = m_expr.ty.kind()
1104 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1105 {
1106 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1111 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1112 .unwrap_or_else(|_| {
1113 ::rustc_middle::util::bug::bug_fmt(format_args!("could not cast from reference to array to pointer to array ({0:?} to {1:?})",
self.expr_ty, array_ptr_type))bug!(
1114 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1115 self.expr_ty,
1116 array_ptr_type,
1117 )
1118 });
1119
1120 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1122 return Ok(CastKind::ArrayPtrCast);
1123 }
1124
1125 Err(CastError::IllegalCast)
1126 }
1127
1128 fn check_addr_ptr_cast(
1129 &self,
1130 fcx: &FnCtxt<'a, 'tcx>,
1131 m_cast: TypeAndMut<'tcx>,
1132 ) -> Result<CastKind, CastError<'tcx>> {
1133 match fcx.pointer_kind(m_cast.ty, self.span)? {
1135 None => Err(CastError::UnknownCastPtrKind),
1136 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1137 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1138 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1139 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1140 Err(CastError::IntToWideCast(None))
1141 }
1142 }
1143 }
1144
1145 fn check_enum_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
1146 if let ty::Adt(d, _) = self.expr_ty.kind()
1147 && d.has_dtor(fcx.tcx)
1148 {
1149 Err(CastError::CastEnumDrop)
1150 } else {
1151 Ok(CastKind::EnumCast)
1152 }
1153 }
1154
1155 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1156 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1157 Ok(_) => Ok(()),
1158 Err(err) => Err(err),
1159 }
1160 }
1161
1162 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1165 if self.cast_ty.is_bool() {
1166 let derefed = fcx
1167 .autoderef(self.expr_span, self.expr_ty)
1168 .silence_errors()
1169 .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(..)));
1170
1171 if let Some((deref_ty, _)) = derefed {
1172 if deref_ty != self.expr_ty.peel_refs() {
1174 err.subdiagnostic(diagnostics::DerefImplsIsEmpty {
1175 span: self.expr_span,
1176 deref_ty,
1177 });
1178 }
1179
1180 err.subdiagnostic(diagnostics::UseIsEmpty {
1183 lo: self.expr_span.shrink_to_lo(),
1184 hi: self.span.with_lo(self.expr_span.hi()),
1185 expr_ty: self.expr_ty,
1186 });
1187 }
1188 }
1189 }
1190}
1191
1192fn index_operand_ambiguity_span(expr: &hir::Expr<'_>) -> Span {
1193 match expr.kind {
1194 hir::ExprKind::MethodCall(segment, ..) => segment.ident.span,
1195 _ => expr.span,
1196 }
1197}