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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
t, span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
96
97 let t = self.resolve_vars_if_possible(t);
98 t.error_reported()?;
99
100 if self.type_is_sized_modulo_regions(self.param_env, t) {
101 return Ok(Some(PointerKind::Thin));
102 }
103
104 let t = self.resolve_vars_with_obligations(t);
105
106 Ok(match *t.kind() {
107 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
108 ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
109 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
110 None => Some(PointerKind::Thin),
111 Some(f) => {
112 let field_ty = self.field_ty(span, f, args);
113 self.pointer_kind(field_ty, span)?
114 }
115 },
116 ty::Tuple(fields) => match fields.last() {
117 None => Some(PointerKind::Thin),
118 Some(&f) => self.pointer_kind(f, span)?,
119 },
120
121 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
122
123 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 if self.is_non_trivial_ref_trait_object_upcast(fcx) {
735 return;
736 }
737
738 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
739 (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
740 } else {
741 (false, lint::builtin::TRIVIAL_CASTS)
742 };
743 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
744 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
745 fcx.tcx.emit_node_span_lint(
746 lint,
747 self.expr.hir_id,
748 self.span,
749 diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
750 );
751 }
752
753 fn is_non_trivial_ref_trait_object_upcast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
758 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!(
759 (self.expr_ty.kind(), self.cast_ty.kind()),
760 (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _))
761 if matches!(
762 (from_ty.kind(), to_ty.kind()),
763 (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if from_data != to_data
764 )
765 ) {
766 return false;
767 }
768
769 let hir::Node::Expr(cast_expr) = fcx.tcx.parent_hir_node(self.expr.hir_id) else {
770 return false;
771 };
772 let hir::Node::Expr(parent) = fcx.tcx.parent_hir_node(cast_expr.hir_id) else {
773 return false;
774 };
775
776 #[allow(non_exhaustive_omitted_patterns)] match parent.kind {
hir::ExprKind::MethodCall(_, receiver, ..) if
receiver.hir_id == cast_expr.hir_id => true,
_ => false,
}matches!(
777 parent.kind,
778 hir::ExprKind::MethodCall(_, receiver, ..) if receiver.hir_id == cast_expr.hir_id
779 )
780 }
781
782 fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
783 if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
784 && fcx.resolve_vars_if_possible(self.expr_ty).is_ty_var()
785 && fcx.resolve_vars_if_possible(fcx.node_ty(idx.hir_id)).is_ty_var()
786 {
787 index_operand_ambiguity_span(idx)
788 } else {
789 self.expr_span
790 }
791 }
792
793 #[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(793u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let expr_span = self.expr_span_for_type_resolution(fcx);
self.expr_ty =
fcx.structurally_resolve_type(expr_span, self.expr_ty);
self.cast_ty =
fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:799",
"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(799u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_cast({0}, {1:?} as {2:?})",
self.expr.hir_id, self.expr_ty, self.cast_ty) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
&& !self.cast_ty.has_infer_types() {
self.report_cast_to_unsized_type(fcx);
} else if self.expr_ty.references_error() ||
self.cast_ty.references_error()
{} else {
match self.try_coercion_cast(fcx) {
Ok(()) => {
if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:817",
"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(817u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" -> PointerCast")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
} else {
self.trivial_cast_lint(fcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:820",
"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(820u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!(" -> CoercionCast")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
}
}
Err(_) => {
match self.do_check(fcx) {
Ok(k) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:829",
"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(829u32),
::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")]
794 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
795 let expr_span = self.expr_span_for_type_resolution(fcx);
796 self.expr_ty = fcx.structurally_resolve_type(expr_span, self.expr_ty);
797 self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
798
799 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
800
801 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
802 && !self.cast_ty.has_infer_types()
803 {
804 self.report_cast_to_unsized_type(fcx);
805 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
806 } else {
808 match self.try_coercion_cast(fcx) {
809 Ok(()) => {
810 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
811 debug!(" -> PointerCast");
818 } else {
819 self.trivial_cast_lint(fcx);
820 debug!(" -> CoercionCast");
821 fcx.typeck_results
822 .borrow_mut()
823 .set_coercion_cast(self.expr.hir_id.local_id);
824 }
825 }
826 Err(_) => {
827 match self.do_check(fcx) {
828 Ok(k) => {
829 debug!(" -> {:?}", k);
830 }
831 Err(e) => self.report_cast_error(fcx, e),
832 };
833 }
834 };
835 }
836 }
837 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
841 use rustc_middle::ty::cast::CastTy::*;
842 use rustc_middle::ty::cast::IntTy::*;
843
844 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
845 {
846 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
847 (None, Some(t_cast)) => {
849 match *self.expr_ty.kind() {
850 ty::FnDef(..) => {
851 let f = fcx.normalize(
853 self.expr_span,
854 Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
855 );
856 let res = fcx.coerce(
857 self.expr,
858 self.expr_ty,
859 Ty::new_fn_ptr(fcx.tcx, f),
860 AllowTwoPhase::No,
861 None,
862 );
863 if let Err(TypeError::IntrinsicCast) = res {
864 return Err(CastError::IllegalCast);
865 }
866 if res.is_err() {
867 return Err(CastError::NonScalar);
868 }
869 (FnPtr, t_cast)
870 }
871 ty::Ref(_, inner_ty, mutbl) => {
876 return match t_cast {
877 Int(_) | Float => match *inner_ty.kind() {
878 ty::Int(_)
879 | ty::Uint(_)
880 | ty::Float(_)
881 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
882 Err(CastError::NeedDeref)
883 }
884 _ => Err(CastError::NeedViaPtr),
885 },
886 Ptr(mt) => {
888 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
889 return Err(CastError::IllegalCast);
890 }
891 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
892 }
893 _ => Err(CastError::NonScalar),
894 };
895 }
896 _ => return Err(CastError::NonScalar),
897 }
898 }
899 _ => return Err(CastError::NonScalar),
900 };
901 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
902 && !adt_def.did().is_local()
903 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
904 {
905 return Err(CastError::ForeignNonExhaustiveAdt);
906 }
907 match (t_from, t_cast) {
908 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
910
911 (_, Int(Bool)) => Err(CastError::CastToBool),
913
914 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
917
918 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
920
921 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
922 Err(CastError::IllegalCast)
923 }
924
925 (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),
930
931 (FnPtr, Int(_)) => {
932 Ok(CastKind::FnPtrAddrCast)
934 }
935 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
937 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
939
940 (Int(CEnum), Int(_)) => self.check_enum_cast(fcx),
942
943 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
945
946 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
947 }
948 }
949
950 fn check_ptr_ptr_cast(
951 &self,
952 fcx: &FnCtxt<'a, 'tcx>,
953 m_src: ty::TypeAndMut<'tcx>,
954 m_dst: ty::TypeAndMut<'tcx>,
955 ) -> Result<CastKind, CastError<'tcx>> {
956 {
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:956",
"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(956u32),
::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:?}");
957 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
960 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
961
962 let Some(dst_kind) = dst_kind else {
964 return Err(CastError::UnknownCastPtrKind);
965 };
966
967 if dst_kind == PointerKind::Thin {
969 return Ok(CastKind::PtrPtrCast);
970 }
971
972 let Some(src_kind) = src_kind else {
974 return Err(CastError::UnknownCastPtrKind);
975 };
976
977 match (src_kind, dst_kind) {
978 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
980
981 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
983 match (src_tty.principal(), dst_tty.principal()) {
984 (Some(src_principal), Some(_)) => {
993 let tcx = fcx.tcx;
994
995 let src_obj = Ty::new_dynamic(
1003 tcx,
1004 tcx.mk_poly_existential_predicates(
1005 &src_tty.without_auto_traits().collect::<Vec<_>>(),
1006 ),
1007 tcx.lifetimes.re_erased,
1008 );
1009 let dst_obj = Ty::new_dynamic(
1010 tcx,
1011 tcx.mk_poly_existential_predicates(
1012 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1013 ),
1014 tcx.lifetimes.re_erased,
1015 );
1016
1017 let cause = fcx.misc(self.span);
1020 if fcx
1021 .at(&cause, fcx.param_env)
1022 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
1023 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
1024 .is_err()
1025 {
1026 return Err(CastError::DifferingKinds { src_kind, dst_kind });
1027 }
1028
1029 let src_auto: FxHashSet<_> = src_tty
1032 .auto_traits()
1033 .chain(
1034 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
1035 .filter(|def_id| tcx.trait_is_auto(*def_id)),
1036 )
1037 .collect();
1038
1039 let added = dst_tty
1040 .auto_traits()
1041 .filter(|trait_did| !src_auto.contains(trait_did))
1042 .collect::<Vec<_>>();
1043
1044 if !added.is_empty() {
1045 return Err(CastError::PtrPtrAddingAutoTrait(added));
1046 }
1047
1048 Ok(CastKind::PtrPtrCast)
1049 }
1050
1051 (None, None) => Ok(CastKind::PtrPtrCast),
1053
1054 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1084
1085 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1087 }
1088 }
1089
1090 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1092
1093 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1094 }
1095 }
1096
1097 fn check_fptr_ptr_cast(
1098 &self,
1099 fcx: &FnCtxt<'a, 'tcx>,
1100 m_cast: ty::TypeAndMut<'tcx>,
1101 ) -> Result<CastKind, CastError<'tcx>> {
1102 match fcx.pointer_kind(m_cast.ty, self.span)? {
1105 None => Err(CastError::UnknownCastPtrKind),
1106 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1107 _ => Err(CastError::IllegalCast),
1108 }
1109 }
1110
1111 fn check_ptr_addr_cast(
1112 &self,
1113 fcx: &FnCtxt<'a, 'tcx>,
1114 m_expr: ty::TypeAndMut<'tcx>,
1115 ) -> Result<CastKind, CastError<'tcx>> {
1116 match fcx.pointer_kind(m_expr.ty, self.span)? {
1119 None => Err(CastError::UnknownExprPtrKind),
1120 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1121 _ => Err(CastError::NeedViaThinPtr),
1122 }
1123 }
1124
1125 fn check_ref_cast(
1126 &self,
1127 fcx: &FnCtxt<'a, 'tcx>,
1128 mut m_expr: ty::TypeAndMut<'tcx>,
1129 mut m_cast: ty::TypeAndMut<'tcx>,
1130 ) -> Result<CastKind, CastError<'tcx>> {
1131 m_expr.ty = fcx.resolve_vars_with_obligations(m_expr.ty);
1133 m_cast.ty = fcx.resolve_vars_with_obligations(m_cast.ty);
1134
1135 if m_expr.mutbl >= m_cast.mutbl
1136 && let ty::Array(ety, _) = m_expr.ty.kind()
1137 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1138 {
1139 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1144 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1145 .unwrap_or_else(|_| {
1146 ::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!(
1147 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1148 self.expr_ty,
1149 array_ptr_type,
1150 )
1151 });
1152
1153 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1155 return Ok(CastKind::ArrayPtrCast);
1156 }
1157
1158 Err(CastError::IllegalCast)
1159 }
1160
1161 fn check_addr_ptr_cast(
1162 &self,
1163 fcx: &FnCtxt<'a, 'tcx>,
1164 m_cast: TypeAndMut<'tcx>,
1165 ) -> Result<CastKind, CastError<'tcx>> {
1166 match fcx.pointer_kind(m_cast.ty, self.span)? {
1168 None => Err(CastError::UnknownCastPtrKind),
1169 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1170 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1171 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1172 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1173 Err(CastError::IntToWideCast(None))
1174 }
1175 }
1176 }
1177
1178 fn check_enum_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
1179 if let ty::Adt(d, _) = self.expr_ty.kind()
1180 && d.has_dtor(fcx.tcx)
1181 {
1182 Err(CastError::CastEnumDrop)
1183 } else {
1184 Ok(CastKind::EnumCast)
1185 }
1186 }
1187
1188 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1189 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1190 Ok(_) => Ok(()),
1191 Err(err) => Err(err),
1192 }
1193 }
1194
1195 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1198 if self.cast_ty.is_bool() {
1199 let derefed = fcx
1200 .autoderef(self.expr_span, self.expr_ty)
1201 .silence_errors()
1202 .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(..)));
1203
1204 if let Some((deref_ty, _)) = derefed {
1205 if deref_ty != self.expr_ty.peel_refs() {
1207 err.subdiagnostic(diagnostics::DerefImplsIsEmpty {
1208 span: self.expr_span,
1209 deref_ty,
1210 });
1211 }
1212
1213 err.subdiagnostic(diagnostics::UseIsEmpty {
1216 lo: self.expr_span.shrink_to_lo(),
1217 hi: self.span.with_lo(self.expr_span.hi()),
1218 expr_ty: self.expr_ty,
1219 });
1220 }
1221 }
1222 }
1223}
1224
1225fn index_operand_ambiguity_span(expr: &hir::Expr<'_>) -> Span {
1226 match expr.kind {
1227 hir::ExprKind::MethodCall(segment, ..) => segment.ident.span,
1228 _ => expr.span,
1229 }
1230}