1use rustc_data_structures::fx::FxHashSet;
32use rustc_errors::codes::*;
33use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
34use rustc_hir::def_id::{DefId, LocalDefId};
35use rustc_hir::{self as hir, ExprKind};
36use rustc_infer::infer::DefineOpaqueTypes;
37use rustc_infer::traits::ObligationCauseCode;
38use rustc_lint_defs::builtin::{TRIVIAL_CASTS, TRIVIAL_NUMERIC_CASTS};
39use rustc_macros::{TypeFoldable, TypeVisitable};
40use rustc_middle::mir::Mutability;
41use rustc_middle::ty::adjustment::AllowTwoPhase;
42use rustc_middle::ty::cast::{CastKind, CastTy};
43use rustc_middle::ty::error::TypeError;
44use rustc_middle::ty::{
45 self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, Unnormalized, VariantDef, elaborate,
46};
47use rustc_middle::{bug, span_bug};
48use rustc_span::{DUMMY_SP, Span, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::{self, ObligationCtxt, TraitEngine};
51use tracing::{debug, instrument};
52
53use super::FnCtxt;
54use crate::{diagnostics, type_error_struct};
55
56#[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)]
59pub(crate) struct CastCheck<'tcx> {
60 expr: &'tcx hir::Expr<'tcx>,
62 expr_ty: Ty<'tcx>,
64 expr_span: Span,
65 cast_ty: Ty<'tcx>,
67 cast_span: Span,
68 span: Span,
69 pub body_def_id: LocalDefId,
70}
71
72#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PointerKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PointerKind::Thin => ::core::fmt::Formatter::write_str(f, "Thin"),
PointerKind::VTable(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "VTable",
&__self_0),
PointerKind::Length =>
::core::fmt::Formatter::write_str(f, "Length"),
PointerKind::OfAlias(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfAlias", &__self_0),
PointerKind::OfParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OfParam", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PointerKind<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for PointerKind<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PointerKind<'tcx> {
#[inline]
fn clone(&self) -> PointerKind<'tcx> {
let _:
::core::clone::AssertParamIsClone<&'tcx ty::List<ty::Binder<'tcx,
ty::ExistentialPredicate<'tcx>>>>;
let _: ::core::clone::AssertParamIsClone<ty::AliasTy<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::ParamTy>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for PointerKind<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PointerKind<'tcx> {
#[inline]
fn eq(&self, other: &PointerKind<'tcx>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PointerKind::VTable(__self_0), PointerKind::VTable(__arg1_0))
=> __self_0 == __arg1_0,
(PointerKind::OfAlias(__self_0),
PointerKind::OfAlias(__arg1_0)) => __self_0 == __arg1_0,
(PointerKind::OfParam(__self_0),
PointerKind::OfParam(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for PointerKind<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<&'tcx ty::List<ty::Binder<'tcx,
ty::ExistentialPredicate<'tcx>>>>;
let _: ::core::cmp::AssertParamIsEq<ty::AliasTy<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<ty::ParamTy>;
}
}Eq, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for PointerKind<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
PointerKind::Thin => {}
PointerKind::VTable(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
PointerKind::Length => {}
PointerKind::OfAlias(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
PointerKind::OfParam(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for PointerKind<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
PointerKind::Thin => { PointerKind::Thin }
PointerKind::VTable(__binding_0) => {
PointerKind::VTable(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
PointerKind::Length => { PointerKind::Length }
PointerKind::OfAlias(__binding_0) => {
PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
PointerKind::OfParam(__binding_0) => {
PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
PointerKind::Thin => { PointerKind::Thin }
PointerKind::VTable(__binding_0) => {
PointerKind::VTable(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
PointerKind::Length => { PointerKind::Length }
PointerKind::OfAlias(__binding_0) => {
PointerKind::OfAlias(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
PointerKind::OfParam(__binding_0) => {
PointerKind::OfParam(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable)]
76enum PointerKind<'tcx> {
77 Thin,
79 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
81 Length,
83 OfAlias(ty::AliasTy<'tcx>),
85 OfParam(ty::ParamTy),
87}
88
89impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
90 fn pointer_kind(
93 &self,
94 t: Ty<'tcx>,
95 span: Span,
96 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
97 {
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:97",
"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(97u32),
::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);
98
99 let t = self.resolve_vars_if_possible(t);
100 t.error_reported()?;
101
102 if self.type_is_sized_modulo_regions(self.param_env, t) {
103 return Ok(Some(PointerKind::Thin));
104 }
105
106 let t = self.resolve_vars_with_obligations(t);
107
108 Ok(match *t.kind() {
109 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
110 ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
111 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
112 None => Some(PointerKind::Thin),
113 Some(f) => {
114 let field_ty = self.field_ty(span, f, args);
115 self.pointer_kind(field_ty, span)?
116 }
117 },
118 ty::Tuple(fields) => match fields.last() {
119 None => Some(PointerKind::Thin),
120 Some(&f) => self.pointer_kind(f, span)?,
121 },
122
123 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
124
125 ty::Foreign(..) => Some(PointerKind::Thin),
127 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
129 ty::Param(p) => Some(PointerKind::OfParam(p)),
130 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
132
133 ty::Bool
134 | ty::Char
135 | ty::Int(..)
136 | ty::Uint(..)
137 | ty::Float(_)
138 | ty::Array(..)
139 | ty::CoroutineWitness(..)
140 | ty::RawPtr(_, _)
141 | ty::Ref(..)
142 | ty::Pat(..)
143 | ty::FnDef(..)
144 | ty::FnPtr(..)
145 | ty::Closure(..)
146 | ty::CoroutineClosure(..)
147 | ty::Coroutine(..)
148 | ty::Adt(..)
149 | ty::Never
150 | ty::Error(_) => {
151 let guar = self
152 .dcx()
153 .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?"));
154 return Err(guar);
155 }
156 })
157 }
158}
159
160#[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)]
161enum CastError<'tcx> {
162 ErrorGuaranteed(ErrorGuaranteed),
163
164 CastToBool,
165 CastToChar,
166 DifferingKinds {
167 src_kind: PointerKind<'tcx>,
168 dst_kind: PointerKind<'tcx>,
169 },
170 SizedUnsizedCast,
172 IllegalCast,
173 NeedDeref,
174 NeedViaPtr,
175 NeedViaThinPtr,
176 NeedViaInt,
177 NonScalar,
178 UnknownExprPtrKind,
179 UnknownCastPtrKind,
180 CastEnumDrop,
181 IntToWideCast(Option<&'static str>),
187 ForeignNonExhaustiveAdt,
188 PtrPtrAddingAutoTrait(Vec<DefId>),
189}
190
191impl From<ErrorGuaranteed> for CastError<'_> {
192 fn from(err: ErrorGuaranteed) -> Self {
193 CastError::ErrorGuaranteed(err)
194 }
195}
196
197fn make_invalid_casting_error<'a, 'tcx>(
198 span: Span,
199 expr_ty: Ty<'tcx>,
200 cast_ty: Ty<'tcx>,
201 fcx: &FnCtxt<'a, 'tcx>,
202) -> Diag<'a> {
203 {
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!(
204 fcx.dcx(),
205 span,
206 expr_ty,
207 E0606,
208 "casting `{}` as `{}` is invalid",
209 fcx.ty_to_string(expr_ty),
210 fcx.ty_to_string(cast_ty)
211 )
212}
213
214pub fn check_cast<'tcx>(
219 tcx: TyCtxt<'tcx>,
220 param_env: ty::ParamEnv<'tcx>,
221 e: &'tcx hir::Expr<'tcx>,
222 from_ty: Ty<'tcx>,
223 to_ty: Ty<'tcx>,
224) -> Option<CastKind> {
225 let hir_id = e.hir_id;
226 let local_def_id = hir_id.owner.def_id;
227
228 let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
229 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
230
231 if let Ok(check) = CastCheck::new(
232 &fn_ctxt, e, from_ty, to_ty,
233 DUMMY_SP, DUMMY_SP,
235 ) {
236 check.do_check(&fn_ctxt).ok()
237 } else {
238 None
239 }
240}
241
242impl<'a, 'tcx> CastCheck<'tcx> {
243 pub(crate) fn new(
244 fcx: &FnCtxt<'a, 'tcx>,
245 expr: &'tcx hir::Expr<'tcx>,
246 expr_ty: Ty<'tcx>,
247 cast_ty: Ty<'tcx>,
248 cast_span: Span,
249 span: Span,
250 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
251 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
252 let check = CastCheck {
253 expr,
254 expr_ty,
255 expr_span,
256 cast_ty,
257 cast_span,
258 span,
259 body_def_id: fcx.body_def_id,
260 };
261
262 match cast_ty.kind() {
266 ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
267 _ => Ok(check),
268 }
269 }
270
271 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
272 match e {
273 CastError::ErrorGuaranteed(_) => {
274 }
276 CastError::NeedDeref => {
277 let mut err =
278 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
279
280 if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
281 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
283 err.span_suggestion_verbose(
284 span,
285 "remove the unneeded borrow",
286 "",
287 Applicability::MachineApplicable,
288 );
289 } else {
290 err.span_suggestion_verbose(
291 self.expr_span.shrink_to_lo(),
292 "dereference the expression",
293 "*",
294 Applicability::MachineApplicable,
295 );
296 }
297
298 err.emit();
299 }
300 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
301 let mut err =
302 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
303
304 if self.cast_ty.is_integral() {
305 if !#[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
306 && let ty::Ref(_, inner_ty, _) = *self.expr_ty.kind()
307 && let ty::Adt(adt_def, _) = *inner_ty.kind()
308 && adt_def.is_enum()
309 && adt_def.is_payloadfree()
310 {
311 err.span_suggestion_verbose(
312 self.expr_span.shrink_to_lo(),
313 "try dereferencing before the cast",
314 "*",
315 Applicability::MaybeIncorrect,
316 );
317 if !fcx.type_is_copy_modulo_regions(fcx.param_env, inner_ty) {
318 err.span_suggestion_verbose(
319 fcx.tcx.def_span(adt_def.did()).shrink_to_lo(),
320 "add `#[derive(Copy, Clone)]` to the enum definition",
321 "#[derive(Copy, Clone)]\n",
322 Applicability::MaybeIncorrect,
323 );
324 }
325 } else {
326 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!(
327 "cast through {} first",
328 match e {
329 CastError::NeedViaPtr => "a raw pointer",
330 CastError::NeedViaThinPtr => "a thin pointer",
331 e => unreachable!(
332 "control flow means we should never encounter a {e:?}"
333 ),
334 }
335 ));
336 }
337 }
338
339 self.try_suggest_collection_to_bool(fcx, &mut err);
340
341 err.emit();
342 }
343 CastError::NeedViaInt => {
344 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
345 .with_help("cast through an integer first")
346 .emit();
347 }
348 CastError::IllegalCast => {
349 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
350 }
351 CastError::DifferingKinds { src_kind, dst_kind } => {
352 let mut err =
353 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
354
355 match (src_kind, dst_kind) {
356 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
357 err.note("the trait objects may have different vtables");
358 }
359 (
360 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
361 PointerKind::OfParam(_)
362 | PointerKind::OfAlias(_)
363 | PointerKind::VTable(_)
364 | PointerKind::Length,
365 )
366 | (
367 PointerKind::VTable(_) | PointerKind::Length,
368 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
369 ) => {
370 err.note("the pointers may have different metadata");
371 }
372 (PointerKind::VTable(_), PointerKind::Length)
373 | (PointerKind::Length, PointerKind::VTable(_)) => {
374 err.note("the pointers have different metadata");
375 }
376 (
377 PointerKind::Thin,
378 PointerKind::Thin
379 | PointerKind::VTable(_)
380 | PointerKind::Length
381 | PointerKind::OfParam(_)
382 | PointerKind::OfAlias(_),
383 )
384 | (
385 PointerKind::VTable(_)
386 | PointerKind::Length
387 | PointerKind::OfParam(_)
388 | PointerKind::OfAlias(_),
389 PointerKind::Thin,
390 )
391 | (PointerKind::Length, PointerKind::Length) => {
392 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected cast error: {0:?}", e))span_bug!(self.span, "unexpected cast error: {e:?}")
393 }
394 }
395
396 err.emit();
397 }
398 CastError::CastToBool => {
399 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
400 let help = if self.expr_ty.is_numeric() {
401 diagnostics::CannotCastToBoolHelp::Numeric(
402 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
403 )
404 } else {
405 diagnostics::CannotCastToBoolHelp::Unsupported(self.span)
406 };
407 fcx.dcx().emit_err(diagnostics::CannotCastToBool {
408 span: self.span,
409 expr_ty,
410 help,
411 });
412 }
413 CastError::CastToChar => {
414 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!(
415 fcx.dcx(),
416 self.span,
417 self.expr_ty,
418 E0604,
419 "only `u8` can be cast as `char`, not `{}`",
420 self.expr_ty
421 );
422 err.span_label(self.span, "invalid cast");
423 if self.expr_ty.is_numeric() {
424 if self.expr_ty == fcx.tcx.types.u32 {
425 err.multipart_suggestion(
426 "consider using `char::from_u32` instead",
427 ::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![
428 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
429 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
430 ],
431 Applicability::MachineApplicable,
432 );
433 } else if self.expr_ty == fcx.tcx.types.i8 {
434 err.span_help(self.span, "consider casting from `u8` instead");
435 } else {
436 err.span_help(
437 self.span,
438 "consider using `char::from_u32` instead (via a `u32`)",
439 );
440 };
441 }
442 err.emit();
443 }
444 CastError::NonScalar => {
445 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!(
446 fcx.dcx(),
447 self.span,
448 self.expr_ty,
449 E0605,
450 "non-primitive cast: `{}` as `{}`",
451 self.expr_ty,
452 fcx.ty_to_string(self.cast_ty)
453 );
454
455 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
456 && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
457 {
458 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
snippet))
})format!(
459 "casting reference expression `{}` because `&` binds tighter than `as`",
460 snippet
461 ));
462 }
463
464 let mut sugg = None;
465 let mut sugg_mutref = false;
466 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
467 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
468 && fcx.may_coerce(
469 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
470 self.cast_ty,
471 )
472 {
473 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
})format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
474 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
475 && expr_mutbl == Mutability::Not
476 && mutbl == Mutability::Mut
477 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
478 {
479 sugg_mutref = true;
480 }
481
482 if !sugg_mutref
483 && sugg == None
484 && fcx.may_coerce(
485 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
486 self.cast_ty,
487 )
488 {
489 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
490 }
491 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
492 && fcx.may_coerce(
493 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
494 self.cast_ty,
495 )
496 {
497 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
498 }
499 if sugg_mutref {
500 err.span_label(self.span, "invalid cast");
501 err.span_note(self.expr_span, "this reference is immutable");
502 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
503 } else if let Some((sugg, remove_cast)) = sugg {
504 err.span_label(self.span, "invalid cast");
505
506 let has_parens = fcx
507 .tcx
508 .sess
509 .source_map()
510 .span_to_snippet(self.expr_span)
511 .is_ok_and(|snip| snip.starts_with('('));
512
513 let needs_parens =
517 !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
hir::ExprKind::Cast(..) => true,
_ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
518
519 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)];
520 if needs_parens {
521 suggestion[0].1 += "(";
522 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
523 }
524 if remove_cast {
525 suggestion.push((
526 self.expr_span.shrink_to_hi().to(self.cast_span),
527 String::new(),
528 ));
529 }
530
531 err.multipart_suggestion(
532 "consider borrowing the value",
533 suggestion,
534 Applicability::MachineApplicable,
535 );
536 } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
_ => false,
}matches!(
537 self.cast_ty.kind(),
538 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
539 ) {
540 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
542 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
543 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
544 if fcx
545 .infcx
546 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
547 .must_apply_modulo_regions()
548 {
549 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
550 fcx.tcx.value_path_str_with_args(def.did(), args)
551 } else {
552 self.cast_ty.to_string()
553 };
554 err.multipart_suggestion(
555 "consider using the `From` trait instead",
556 ::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![
557 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
558 (
559 self.expr_span.shrink_to_hi().to(self.cast_span),
560 ")".to_string(),
561 ),
562 ],
563 Applicability::MaybeIncorrect,
564 );
565 }
566 }
567
568 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
569 && adt.is_enum()
570 && self.cast_ty.is_numeric()
571 {
572 (
573 "an `as` expression can be used to convert enum types to numeric \
574 types only if the enum type is unit-only or field-less",
575 Some(
576 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
577 ),
578 )
579 } else {
580 (
581 "an `as` expression can only be used to convert between primitive \
582 types or to coerce to a specific trait object",
583 None,
584 )
585 };
586
587 err.span_label(self.span, msg);
588
589 if let Some(note) = note {
590 err.note(note);
591 }
592 } else {
593 err.span_label(self.span, "invalid cast");
594 }
595
596 fcx.suggest_closure_to_fn_ptr_coercion(
597 &mut err,
598 self.expr,
599 self.cast_ty,
600 self.expr_ty,
601 );
602 self.try_suggest_collection_to_bool(fcx, &mut err);
603
604 err.emit();
605 }
606 CastError::SizedUnsizedCast => {
607 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
608 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
609 fcx.dcx().emit_err(diagnostics::CastThinPointerToWidePointer {
610 span: self.span,
611 expr_ty,
612 cast_ty,
613 teach: fcx.tcx.sess.teach(E0607),
614 });
615 }
616 CastError::IntToWideCast(known_metadata) => {
617 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
618 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
619 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
620 let metadata = known_metadata.unwrap_or("type-specific metadata");
621 let known_wide = known_metadata.is_some();
622 let span = self.cast_span;
623 let param_note = (!known_wide)
624 .then(|| match cast_ty.kind() {
625 ty::RawPtr(pointee, _) => match pointee.kind() {
626 ty::Param(param) => {
627 Some(diagnostics::IntToWideParamNote { param: param.name })
628 }
629 _ => None,
630 },
631 _ => None,
632 })
633 .flatten();
634 fcx.dcx().emit_err(diagnostics::IntToWide {
635 span,
636 metadata,
637 expr_ty,
638 cast_ty,
639 expr_if_nightly,
640 known_wide,
641 param_note,
642 });
643 }
644 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
645 let unknown_cast_to = match e {
646 CastError::UnknownCastPtrKind => true,
647 CastError::UnknownExprPtrKind => false,
648 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:?}"),
649 };
650 let (span, sub) = if unknown_cast_to {
651 (self.cast_span, diagnostics::CastUnknownPointerSub::To(self.cast_span))
652 } else {
653 (self.cast_span, diagnostics::CastUnknownPointerSub::From(self.span))
654 };
655 fcx.dcx().emit_err(diagnostics::CastUnknownPointer {
656 span,
657 to: unknown_cast_to,
658 sub,
659 });
660 }
661 CastError::CastEnumDrop => {
662 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
663 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
664
665 fcx.dcx().emit_err(diagnostics::CastEnumDrop { span: self.span, expr_ty, cast_ty });
666 }
667 CastError::ForeignNonExhaustiveAdt => {
668 make_invalid_casting_error(
669 self.span,
670 self.expr_ty,
671 self.cast_ty,
672 fcx,
673 )
674 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
675 .emit();
676 }
677 CastError::PtrPtrAddingAutoTrait(added) => {
678 fcx.dcx().emit_err(diagnostics::PtrCastAddAutoToObject {
679 span: self.span,
680 traits_len: added.len(),
681 traits: {
682 let mut traits: Vec<_> = added
683 .into_iter()
684 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
685 .collect();
686
687 traits.sort();
688 traits.into()
689 },
690 });
691 }
692 }
693 }
694
695 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
696 if let Err(err) = self.cast_ty.error_reported() {
697 return err;
698 }
699 if let Err(err) = self.expr_ty.error_reported() {
700 return err;
701 }
702
703 let tstr = fcx.ty_to_string(self.cast_ty);
704 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!(
705 fcx.dcx(),
706 self.span,
707 self.expr_ty,
708 E0620,
709 "cast to unsized type: `{}` as `{}`",
710 fcx.resolve_vars_if_possible(self.expr_ty),
711 tstr
712 );
713 match self.expr_ty.kind() {
714 ty::Ref(_, _, mt) => {
715 let mtstr = mt.prefix_str();
716 err.span_suggestion_verbose(
717 self.cast_span.shrink_to_lo(),
718 "consider casting to a reference instead",
719 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mtstr))
})format!("&{mtstr}"),
720 Applicability::MachineApplicable,
721 );
722 }
723 ty::Adt(def, ..) if def.is_box() => {
724 err.multipart_suggestion(
725 "you can cast to a `Box` instead",
726 ::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![
727 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
728 (self.cast_span.shrink_to_hi(), ">".to_string()),
729 ],
730 Applicability::MachineApplicable,
731 );
732 }
733 _ => {
734 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
735 }
736 }
737 err.emit()
738 }
739
740 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
741 if self.is_non_trivial_ref_trait_object_upcast(fcx) {
742 return;
743 }
744
745 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
746 (true, TRIVIAL_NUMERIC_CASTS)
747 } else {
748 (false, TRIVIAL_CASTS)
749 };
750 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
751 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
752 fcx.tcx.emit_node_span_lint(
753 lint,
754 self.expr.hir_id,
755 self.span,
756 diagnostics::TrivialCast { numeric, expr_ty, cast_ty },
757 );
758 }
759
760 fn is_non_trivial_ref_trait_object_upcast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
765 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!(
766 (self.expr_ty.kind(), self.cast_ty.kind()),
767 (ty::Ref(_, from_ty, _), ty::Ref(_, to_ty, _))
768 if matches!(
769 (from_ty.kind(), to_ty.kind()),
770 (ty::Dynamic(from_data, _), ty::Dynamic(to_data, _)) if from_data != to_data
771 )
772 ) {
773 return false;
774 }
775
776 let hir::Node::Expr(cast_expr) = fcx.tcx.parent_hir_node(self.expr.hir_id) else {
777 return false;
778 };
779 let hir::Node::Expr(parent) = fcx.tcx.parent_hir_node(cast_expr.hir_id) else {
780 return false;
781 };
782
783 #[allow(non_exhaustive_omitted_patterns)] match parent.kind {
hir::ExprKind::MethodCall(_, receiver, ..) if
receiver.hir_id == cast_expr.hir_id => true,
_ => false,
}matches!(
784 parent.kind,
785 hir::ExprKind::MethodCall(_, receiver, ..) if receiver.hir_id == cast_expr.hir_id
786 )
787 }
788
789 fn expr_span_for_type_resolution(&self, fcx: &FnCtxt<'a, 'tcx>) -> Span {
790 if let hir::ExprKind::Index(_, idx, _) = self.expr.kind
791 && fcx.resolve_vars_if_possible(self.expr_ty).is_ty_var()
792 && fcx.resolve_vars_if_possible(fcx.node_ty(idx.hir_id)).is_ty_var()
793 {
794 index_operand_ambiguity_span(idx)
795 } else {
796 self.expr_span
797 }
798 }
799
800 {}
#[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(800u32),
::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.resolve_vars_with_obligations(self.cast_ty);
if self.cast_ty.is_ty_var() {
self.cast_ty =
if let Some(guar) =
self.try_report_ambiguous_binop_for_infer_cast(fcx) {
let err = Ty::new_error(fcx.tcx, guar);
fcx.demand_suptype(self.cast_span, err, self.cast_ty);
err
} else {
fcx.type_must_be_known_at_this_point(self.cast_span,
self.cast_ty)
};
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:815",
"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(815u32),
::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:833",
"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(833u32),
::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:836",
"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(836u32),
::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:845",
"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(845u32),
::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")]
801 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
802 let expr_span = self.expr_span_for_type_resolution(fcx);
803 self.expr_ty = fcx.structurally_resolve_type(expr_span, self.expr_ty);
804 self.cast_ty = fcx.resolve_vars_with_obligations(self.cast_ty);
805 if self.cast_ty.is_ty_var() {
806 self.cast_ty = if let Some(guar) = self.try_report_ambiguous_binop_for_infer_cast(fcx) {
807 let err = Ty::new_error(fcx.tcx, guar);
808 fcx.demand_suptype(self.cast_span, err, self.cast_ty);
809 err
810 } else {
811 fcx.type_must_be_known_at_this_point(self.cast_span, self.cast_ty)
812 };
813 }
814
815 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
816
817 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
818 && !self.cast_ty.has_infer_types()
819 {
820 self.report_cast_to_unsized_type(fcx);
821 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
822 } else {
824 match self.try_coercion_cast(fcx) {
825 Ok(()) => {
826 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
827 debug!(" -> PointerCast");
834 } else {
835 self.trivial_cast_lint(fcx);
836 debug!(" -> CoercionCast");
837 fcx.typeck_results
838 .borrow_mut()
839 .set_coercion_cast(self.expr.hir_id.local_id);
840 }
841 }
842 Err(_) => {
843 match self.do_check(fcx) {
844 Ok(k) => {
845 debug!(" -> {:?}", k);
846 }
847 Err(e) => self.report_cast_error(fcx, e),
848 };
849 }
850 };
851 }
852 }
853
854 #[cold]
856 fn try_report_ambiguous_binop_for_infer_cast(
857 &self,
858 fcx: &FnCtxt<'a, 'tcx>,
859 ) -> Option<ErrorGuaranteed> {
860 let errors: Vec<_> = fcx
861 .fulfillment_cx
862 .borrow()
863 .pending_obligations()
864 .into_iter()
865 .filter_map(|mut obligation| {
866 let predicate = fcx.resolve_vars_if_possible(obligation.predicate);
867 if !#[allow(non_exhaustive_omitted_patterns)] match predicate.kind().skip_binder()
{
ty::PredicateKind::Clause(ty::ClauseKind::Trait(_)) => true,
_ => false,
}matches!(
868 predicate.kind().skip_binder(),
869 ty::PredicateKind::Clause(ty::ClauseKind::Trait(_))
870 ) {
871 return None;
872 }
873 let cast_span = self.cast_span;
874
875 let ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. } =
876 obligation.cause.code()
877 else {
878 return None;
879 };
880 let lhs_ty = fcx.resolve_vars_if_possible(fcx.node_ty(*lhs_hir_id));
881 let rhs_ty = fcx.resolve_vars_if_possible(fcx.node_ty(*rhs_hir_id));
882
883 if (fcx.tcx.hir_span(*lhs_hir_id).contains(cast_span)
884 && lhs_ty.contains(self.cast_ty))
885 || (rhs_span.contains(cast_span) && rhs_ty.contains(self.cast_ty))
886 {
887 obligation.cause.span = cast_span;
888 obligation.predicate = predicate;
889
890 let ocx = ObligationCtxt::new_with_diagnostics(&fcx.infcx);
891 ocx.register_obligation(obligation);
892 ocx.evaluate_obligations_error_on_ambiguity().into_iter().find(|error| {
893 #[allow(non_exhaustive_omitted_patterns)] match error.code {
traits::FulfillmentErrorCode::Ambiguity { overflow: None } => true,
_ => false,
}matches!(
894 error.code,
895 traits::FulfillmentErrorCode::Ambiguity { overflow: None }
896 )
897 })
898 } else {
899 None
900 }
901 })
902 .collect();
903
904 if errors.is_empty() {
905 None
906 } else {
907 Some(fcx.err_ctxt().report_fulfillment_errors(errors.into()))
908 }
909 }
910
911 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
915 use rustc_middle::ty::cast::CastTy::*;
916 use rustc_middle::ty::cast::IntTy::*;
917
918 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
919 {
920 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
921 (None, Some(t_cast)) => {
923 match *self.expr_ty.kind() {
924 ty::FnDef(..) => {
925 let f = fcx.normalize(
927 self.expr_span,
928 Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
929 );
930 let res = fcx.coerce(
931 self.expr,
932 self.expr_ty,
933 Ty::new_fn_ptr(fcx.tcx, f),
934 AllowTwoPhase::No,
935 None,
936 );
937 if let Err(TypeError::IntrinsicCast) = res {
938 return Err(CastError::IllegalCast);
939 }
940 if res.is_err() {
941 return Err(CastError::NonScalar);
942 }
943 (FnPtr, t_cast)
944 }
945 ty::Ref(_, inner_ty, mutbl) => {
950 return match t_cast {
951 Int(_) | Float => match *inner_ty.kind() {
952 ty::Int(_)
953 | ty::Uint(_)
954 | ty::Float(_)
955 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
956 Err(CastError::NeedDeref)
957 }
958 _ => Err(CastError::NeedViaPtr),
959 },
960 Ptr(mt) => {
962 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
963 return Err(CastError::IllegalCast);
964 }
965 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
966 }
967 _ => Err(CastError::NonScalar),
968 };
969 }
970 _ => return Err(CastError::NonScalar),
971 }
972 }
973 _ => return Err(CastError::NonScalar),
974 };
975 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
976 && !adt_def.did().is_local()
977 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
978 {
979 return Err(CastError::ForeignNonExhaustiveAdt);
980 }
981 match (t_from, t_cast) {
982 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
984
985 (_, Int(Bool)) => Err(CastError::CastToBool),
987
988 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
991
992 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
994
995 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
996 Err(CastError::IllegalCast)
997 }
998
999 (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),
1004
1005 (FnPtr, Int(_)) => {
1006 Ok(CastKind::FnPtrAddrCast)
1008 }
1009 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt),
1011 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
1013
1014 (Int(CEnum), Int(_)) => self.check_enum_cast(fcx),
1016
1017 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
1019
1020 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
1021 }
1022 }
1023
1024 fn check_ptr_ptr_cast(
1025 &self,
1026 fcx: &FnCtxt<'a, 'tcx>,
1027 m_src: ty::TypeAndMut<'tcx>,
1028 m_dst: ty::TypeAndMut<'tcx>,
1029 ) -> Result<CastKind, CastError<'tcx>> {
1030 {
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:1030",
"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(1030u32),
::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:?}");
1031 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
1034 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
1035
1036 let Some(dst_kind) = dst_kind else {
1038 return Err(CastError::UnknownCastPtrKind);
1039 };
1040
1041 if dst_kind == PointerKind::Thin {
1043 return Ok(CastKind::PtrPtrCast);
1044 }
1045
1046 let Some(src_kind) = src_kind else {
1048 return Err(CastError::UnknownCastPtrKind);
1049 };
1050
1051 match (src_kind, dst_kind) {
1052 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
1054
1055 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
1057 match (src_tty.principal(), dst_tty.principal()) {
1058 (Some(src_principal), Some(_)) => {
1067 let tcx = fcx.tcx;
1068
1069 let src_obj = Ty::new_dynamic(
1077 tcx,
1078 tcx.mk_poly_existential_predicates(
1079 &src_tty.without_auto_traits().collect::<Vec<_>>(),
1080 ),
1081 tcx.lifetimes.re_erased,
1082 );
1083 let dst_obj = Ty::new_dynamic(
1084 tcx,
1085 tcx.mk_poly_existential_predicates(
1086 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1087 ),
1088 tcx.lifetimes.re_erased,
1089 );
1090
1091 let cause = fcx.misc(self.span);
1094 if fcx
1095 .at(&cause, fcx.param_env)
1096 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
1097 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
1098 .is_err()
1099 {
1100 return Err(CastError::DifferingKinds { src_kind, dst_kind });
1101 }
1102
1103 let src_auto: FxHashSet<_> = src_tty
1106 .auto_traits()
1107 .chain(
1108 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
1109 .filter(|def_id| tcx.trait_is_auto(*def_id)),
1110 )
1111 .collect();
1112
1113 let added = dst_tty
1114 .auto_traits()
1115 .filter(|trait_did| !src_auto.contains(trait_did))
1116 .collect::<Vec<_>>();
1117
1118 if !added.is_empty() {
1119 return Err(CastError::PtrPtrAddingAutoTrait(added));
1120 }
1121
1122 Ok(CastKind::PtrPtrCast)
1123 }
1124
1125 (None, None) => Ok(CastKind::PtrPtrCast),
1127
1128 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1158
1159 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1161 }
1162 }
1163
1164 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1166
1167 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1168 }
1169 }
1170
1171 fn check_fptr_ptr_cast(
1172 &self,
1173 fcx: &FnCtxt<'a, 'tcx>,
1174 m_cast: ty::TypeAndMut<'tcx>,
1175 ) -> Result<CastKind, CastError<'tcx>> {
1176 match fcx.pointer_kind(m_cast.ty, self.span)? {
1179 None => Err(CastError::UnknownCastPtrKind),
1180 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1181 _ => Err(CastError::IllegalCast),
1182 }
1183 }
1184
1185 fn check_ptr_addr_cast(
1186 &self,
1187 fcx: &FnCtxt<'a, 'tcx>,
1188 m_expr: ty::TypeAndMut<'tcx>,
1189 ) -> Result<CastKind, CastError<'tcx>> {
1190 match fcx.pointer_kind(m_expr.ty, self.span)? {
1193 None => Err(CastError::UnknownExprPtrKind),
1194 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1195 _ => Err(CastError::NeedViaThinPtr),
1196 }
1197 }
1198
1199 fn check_ref_cast(
1200 &self,
1201 fcx: &FnCtxt<'a, 'tcx>,
1202 mut m_expr: ty::TypeAndMut<'tcx>,
1203 mut m_cast: ty::TypeAndMut<'tcx>,
1204 ) -> Result<CastKind, CastError<'tcx>> {
1205 m_expr.ty = fcx.resolve_vars_with_obligations(m_expr.ty);
1207 m_cast.ty = fcx.resolve_vars_with_obligations(m_cast.ty);
1208
1209 if m_expr.mutbl >= m_cast.mutbl
1210 && let ty::Array(ety, _) = m_expr.ty.kind()
1211 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1212 {
1213 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1218 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1219 .unwrap_or_else(|_| {
1220 ::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!(
1221 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1222 self.expr_ty,
1223 array_ptr_type,
1224 )
1225 });
1226
1227 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1229 return Ok(CastKind::ArrayPtrCast);
1230 }
1231
1232 Err(CastError::IllegalCast)
1233 }
1234
1235 fn check_addr_ptr_cast(
1236 &self,
1237 fcx: &FnCtxt<'a, 'tcx>,
1238 m_cast: TypeAndMut<'tcx>,
1239 ) -> Result<CastKind, CastError<'tcx>> {
1240 match fcx.pointer_kind(m_cast.ty, self.span)? {
1242 None => Err(CastError::UnknownCastPtrKind),
1243 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1244 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1245 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1246 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1247 Err(CastError::IntToWideCast(None))
1248 }
1249 }
1250 }
1251
1252 fn check_enum_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
1253 if let ty::Adt(d, _) = self.expr_ty.kind()
1254 && d.has_dtor(fcx.tcx)
1255 {
1256 Err(CastError::CastEnumDrop)
1257 } else {
1258 Ok(CastKind::EnumCast)
1259 }
1260 }
1261
1262 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1263 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1264 Ok(_) => Ok(()),
1265 Err(err) => Err(err),
1266 }
1267 }
1268
1269 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1272 if self.cast_ty.is_bool() {
1273 let derefed = fcx
1274 .autoderef(self.expr_span, self.expr_ty)
1275 .silence_errors()
1276 .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(..)));
1277
1278 if let Some((deref_ty, _)) = derefed {
1279 if deref_ty != self.expr_ty.peel_refs() {
1281 err.subdiagnostic(diagnostics::DerefImplsIsEmpty {
1282 span: self.expr_span,
1283 deref_ty,
1284 });
1285 }
1286
1287 err.subdiagnostic(diagnostics::UseIsEmpty {
1290 lo: self.expr_span.shrink_to_lo(),
1291 hi: self.span.with_lo(self.expr_span.hi()),
1292 expr_ty: self.expr_ty,
1293 });
1294 }
1295 }
1296 }
1297}
1298
1299fn index_operand_ambiguity_span(expr: &hir::Expr<'_>) -> Span {
1300 match expr.kind {
1301 hir::ExprKind::MethodCall(segment, ..) => segment.ident.span,
1302 _ => expr.span,
1303 }
1304}