1use rustc_ast::util::parser::ExprPrecedence;
32use rustc_data_structures::fx::FxHashSet;
33use rustc_errors::codes::*;
34use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
35use rustc_hir::def_id::{DefId, LocalDefId};
36use rustc_hir::{self as hir, ExprKind};
37use rustc_infer::infer::DefineOpaqueTypes;
38use rustc_macros::{TypeFoldable, TypeVisitable};
39use rustc_middle::mir::Mutability;
40use rustc_middle::ty::adjustment::AllowTwoPhase;
41use rustc_middle::ty::cast::{CastKind, CastTy};
42use rustc_middle::ty::error::TypeError;
43use rustc_middle::ty::{
44 self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, Unnormalized, VariantDef, elaborate,
45};
46use rustc_middle::{bug, span_bug};
47use rustc_session::lint;
48use rustc_span::{DUMMY_SP, Span, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use tracing::{debug, instrument};
51
52use super::FnCtxt;
53use crate::{errors, type_error_struct};
54
55#[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_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_id];
::core::fmt::Formatter::debug_struct_fields_finish(f, "CastCheck",
names, values)
}
}Debug)]
58pub(crate) struct CastCheck<'tcx> {
59 expr: &'tcx hir::Expr<'tcx>,
61 expr_ty: Ty<'tcx>,
63 expr_span: Span,
64 cast_ty: Ty<'tcx>,
66 cast_span: Span,
67 span: Span,
68 pub body_id: LocalDefId,
69}
70
71#[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)]
75enum PointerKind<'tcx> {
76 Thin,
78 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
80 Length,
82 OfAlias(ty::AliasTy<'tcx>),
84 OfParam(ty::ParamTy),
86}
87
88impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
89 fn pointer_kind(
92 &self,
93 t: Ty<'tcx>,
94 span: Span,
95 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
96 {
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:96",
"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(96u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pointer_kind({0:?}, {1:?})",
t, span) as &dyn Value))])
});
} else { ; }
};debug!("pointer_kind({:?}, {:?})", t, span);
97
98 let t = self.resolve_vars_if_possible(t);
99 t.error_reported()?;
100
101 if self.type_is_sized_modulo_regions(self.param_env, t) {
102 return Ok(Some(PointerKind::Thin));
103 }
104
105 let t = self.try_structurally_resolve_type(span, t);
106
107 Ok(match *t.kind() {
108 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
109 ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
110 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
111 None => Some(PointerKind::Thin),
112 Some(f) => {
113 let field_ty = self.field_ty(span, f, args);
114 self.pointer_kind(field_ty, span)?
115 }
116 },
117 ty::Tuple(fields) => match fields.last() {
118 None => Some(PointerKind::Thin),
119 Some(&f) => self.pointer_kind(f, span)?,
120 },
121
122 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
123
124 ty::Foreign(..) => Some(PointerKind::Thin),
126 ty::Alias(pi) => Some(PointerKind::OfAlias(pi)),
128 ty::Param(p) => Some(PointerKind::OfParam(p)),
129 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
131
132 ty::Bool
133 | ty::Char
134 | ty::Int(..)
135 | ty::Uint(..)
136 | ty::Float(_)
137 | ty::Array(..)
138 | ty::CoroutineWitness(..)
139 | ty::RawPtr(_, _)
140 | ty::Ref(..)
141 | ty::Pat(..)
142 | ty::FnDef(..)
143 | ty::FnPtr(..)
144 | ty::Closure(..)
145 | ty::CoroutineClosure(..)
146 | ty::Coroutine(..)
147 | ty::Adt(..)
148 | ty::Never
149 | ty::Error(_) => {
150 let guar = self
151 .dcx()
152 .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?"));
153 return Err(guar);
154 }
155 })
156 }
157}
158
159#[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::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)]
160enum CastError<'tcx> {
161 ErrorGuaranteed(ErrorGuaranteed),
162
163 CastToBool,
164 CastToChar,
165 DifferingKinds {
166 src_kind: PointerKind<'tcx>,
167 dst_kind: PointerKind<'tcx>,
168 },
169 SizedUnsizedCast,
171 IllegalCast,
172 NeedDeref,
173 NeedViaPtr,
174 NeedViaThinPtr,
175 NeedViaInt,
176 NonScalar,
177 UnknownExprPtrKind,
178 UnknownCastPtrKind,
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 =
251 CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span, body_id: fcx.body_id };
252
253 match cast_ty.kind() {
257 ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
258 _ => Ok(check),
259 }
260 }
261
262 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
263 match e {
264 CastError::ErrorGuaranteed(_) => {
265 }
267 CastError::NeedDeref => {
268 let mut err =
269 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
270
271 if #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..)) {
272 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
274 err.span_suggestion_verbose(
275 span,
276 "remove the unneeded borrow",
277 "",
278 Applicability::MachineApplicable,
279 );
280 } else {
281 err.span_suggestion_verbose(
282 self.expr_span.shrink_to_lo(),
283 "dereference the expression",
284 "*",
285 Applicability::MachineApplicable,
286 );
287 }
288
289 err.emit();
290 }
291 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
292 let mut err =
293 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
294 if self.cast_ty.is_integral() {
295 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!("cast through {} first", match e {
296 CastError::NeedViaPtr => "a raw pointer",
297 CastError::NeedViaThinPtr => "a thin pointer",
298 e => unreachable!("control flow means we should never encounter a {e:?}"),
299 }));
300 }
301
302 self.try_suggest_collection_to_bool(fcx, &mut err);
303
304 err.emit();
305 }
306 CastError::NeedViaInt => {
307 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
308 .with_help("cast through an integer first")
309 .emit();
310 }
311 CastError::IllegalCast => {
312 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
313 }
314 CastError::DifferingKinds { src_kind, dst_kind } => {
315 let mut err =
316 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
317
318 match (src_kind, dst_kind) {
319 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
320 err.note("the trait objects may have different vtables");
321 }
322 (
323 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
324 PointerKind::OfParam(_)
325 | PointerKind::OfAlias(_)
326 | PointerKind::VTable(_)
327 | PointerKind::Length,
328 )
329 | (
330 PointerKind::VTable(_) | PointerKind::Length,
331 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
332 ) => {
333 err.note("the pointers may have different metadata");
334 }
335 (PointerKind::VTable(_), PointerKind::Length)
336 | (PointerKind::Length, PointerKind::VTable(_)) => {
337 err.note("the pointers have different metadata");
338 }
339 (
340 PointerKind::Thin,
341 PointerKind::Thin
342 | PointerKind::VTable(_)
343 | PointerKind::Length
344 | PointerKind::OfParam(_)
345 | PointerKind::OfAlias(_),
346 )
347 | (
348 PointerKind::VTable(_)
349 | PointerKind::Length
350 | PointerKind::OfParam(_)
351 | PointerKind::OfAlias(_),
352 PointerKind::Thin,
353 )
354 | (PointerKind::Length, PointerKind::Length) => {
355 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected cast error: {0:?}", e))span_bug!(self.span, "unexpected cast error: {e:?}")
356 }
357 }
358
359 err.emit();
360 }
361 CastError::CastToBool => {
362 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
363 let help = if self.expr_ty.is_numeric() {
364 errors::CannotCastToBoolHelp::Numeric(
365 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
366 )
367 } else {
368 errors::CannotCastToBoolHelp::Unsupported(self.span)
369 };
370 fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help });
371 }
372 CastError::CastToChar => {
373 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!(
374 fcx.dcx(),
375 self.span,
376 self.expr_ty,
377 E0604,
378 "only `u8` can be cast as `char`, not `{}`",
379 self.expr_ty
380 );
381 err.span_label(self.span, "invalid cast");
382 if self.expr_ty.is_numeric() {
383 if self.expr_ty == fcx.tcx.types.u32 {
384 err.multipart_suggestion(
385 "consider using `char::from_u32` instead",
386 ::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![
387 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
388 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
389 ],
390 Applicability::MachineApplicable,
391 );
392 } else if self.expr_ty == fcx.tcx.types.i8 {
393 err.span_help(self.span, "consider casting from `u8` instead");
394 } else {
395 err.span_help(
396 self.span,
397 "consider using `char::from_u32` instead (via a `u32`)",
398 );
399 };
400 }
401 err.emit();
402 }
403 CastError::NonScalar => {
404 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!(
405 fcx.dcx(),
406 self.span,
407 self.expr_ty,
408 E0605,
409 "non-primitive cast: `{}` as `{}`",
410 self.expr_ty,
411 fcx.ty_to_string(self.cast_ty)
412 );
413
414 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
415 && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
ExprKind::AddrOf(..) => true,
_ => false,
}matches!(self.expr.kind, ExprKind::AddrOf(..))
416 {
417 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("casting reference expression `{0}` because `&` binds tighter than `as`",
snippet))
})format!(
418 "casting reference expression `{}` because `&` binds tighter than `as`",
419 snippet
420 ));
421 }
422
423 let mut sugg = None;
424 let mut sugg_mutref = false;
425 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
426 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
427 && fcx.may_coerce(
428 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
429 self.cast_ty,
430 )
431 {
432 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}*", mutbl.prefix_str()))
})format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
433 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
434 && expr_mutbl == Mutability::Not
435 && mutbl == Mutability::Mut
436 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
437 {
438 sugg_mutref = true;
439 }
440
441 if !sugg_mutref
442 && sugg == None
443 && fcx.may_coerce(
444 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
445 self.cast_ty,
446 )
447 {
448 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
449 }
450 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
451 && fcx.may_coerce(
452 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
453 self.cast_ty,
454 )
455 {
456 sugg = Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()), false));
457 }
458 if sugg_mutref {
459 err.span_label(self.span, "invalid cast");
460 err.span_note(self.expr_span, "this reference is immutable");
461 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
462 } else if let Some((sugg, remove_cast)) = sugg {
463 err.span_label(self.span, "invalid cast");
464
465 let has_parens = fcx
466 .tcx
467 .sess
468 .source_map()
469 .span_to_snippet(self.expr_span)
470 .is_ok_and(|snip| snip.starts_with('('));
471
472 let needs_parens =
476 !has_parens && #[allow(non_exhaustive_omitted_patterns)] match self.expr.kind {
hir::ExprKind::Cast(..) => true,
_ => false,
}matches!(self.expr.kind, hir::ExprKind::Cast(..));
477
478 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)];
479 if needs_parens {
480 suggestion[0].1 += "(";
481 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
482 }
483 if remove_cast {
484 suggestion.push((
485 self.expr_span.shrink_to_hi().to(self.cast_span),
486 String::new(),
487 ));
488 }
489
490 err.multipart_suggestion(
491 "consider borrowing the value",
492 suggestion,
493 Applicability::MachineApplicable,
494 );
495 } else if !#[allow(non_exhaustive_omitted_patterns)] match self.cast_ty.kind() {
ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..) => true,
_ => false,
}matches!(
496 self.cast_ty.kind(),
497 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
498 ) {
499 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
501 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
502 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
503 if fcx
504 .infcx
505 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
506 .must_apply_modulo_regions()
507 {
508 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
509 fcx.tcx.value_path_str_with_args(def.did(), args)
510 } else {
511 self.cast_ty.to_string()
512 };
513 err.multipart_suggestion(
514 "consider using the `From` trait instead",
515 ::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![
516 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
517 (
518 self.expr_span.shrink_to_hi().to(self.cast_span),
519 ")".to_string(),
520 ),
521 ],
522 Applicability::MaybeIncorrect,
523 );
524 }
525 }
526
527 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
528 && adt.is_enum()
529 && self.cast_ty.is_numeric()
530 {
531 (
532 "an `as` expression can be used to convert enum types to numeric \
533 types only if the enum type is unit-only or field-less",
534 Some(
535 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
536 ),
537 )
538 } else {
539 (
540 "an `as` expression can only be used to convert between primitive \
541 types or to coerce to a specific trait object",
542 None,
543 )
544 };
545
546 err.span_label(self.span, msg);
547
548 if let Some(note) = note {
549 err.note(note);
550 }
551 } else {
552 err.span_label(self.span, "invalid cast");
553 }
554
555 fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
556 self.try_suggest_collection_to_bool(fcx, &mut err);
557
558 err.emit();
559 }
560 CastError::SizedUnsizedCast => {
561 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
562 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
563 fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
564 span: self.span,
565 expr_ty,
566 cast_ty,
567 teach: fcx.tcx.sess.teach(E0607),
568 });
569 }
570 CastError::IntToWideCast(known_metadata) => {
571 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
572 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
573 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
574 let metadata = known_metadata.unwrap_or("type-specific metadata");
575 let known_wide = known_metadata.is_some();
576 let span = self.cast_span;
577 let param_note = (!known_wide)
578 .then(|| match cast_ty.kind() {
579 ty::RawPtr(pointee, _) => match pointee.kind() {
580 ty::Param(param) => {
581 Some(errors::IntToWideParamNote { param: param.name })
582 }
583 _ => None,
584 },
585 _ => None,
586 })
587 .flatten();
588 fcx.dcx().emit_err(errors::IntToWide {
589 span,
590 metadata,
591 expr_ty,
592 cast_ty,
593 expr_if_nightly,
594 known_wide,
595 param_note,
596 });
597 }
598 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
599 let unknown_cast_to = match e {
600 CastError::UnknownCastPtrKind => true,
601 CastError::UnknownExprPtrKind => false,
602 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:?}"),
603 };
604 let (span, sub) = if unknown_cast_to {
605 (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
606 } else {
607 (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
608 };
609 fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
610 }
611 CastError::ForeignNonExhaustiveAdt => {
612 make_invalid_casting_error(
613 self.span,
614 self.expr_ty,
615 self.cast_ty,
616 fcx,
617 )
618 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
619 .emit();
620 }
621 CastError::PtrPtrAddingAutoTrait(added) => {
622 fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
623 span: self.span,
624 traits_len: added.len(),
625 traits: {
626 let mut traits: Vec<_> = added
627 .into_iter()
628 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
629 .collect();
630
631 traits.sort();
632 traits.into()
633 },
634 });
635 }
636 }
637 }
638
639 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
640 if let Err(err) = self.cast_ty.error_reported() {
641 return err;
642 }
643 if let Err(err) = self.expr_ty.error_reported() {
644 return err;
645 }
646
647 let tstr = fcx.ty_to_string(self.cast_ty);
648 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!(
649 fcx.dcx(),
650 self.span,
651 self.expr_ty,
652 E0620,
653 "cast to unsized type: `{}` as `{}`",
654 fcx.resolve_vars_if_possible(self.expr_ty),
655 tstr
656 );
657 match self.expr_ty.kind() {
658 ty::Ref(_, _, mt) => {
659 let mtstr = mt.prefix_str();
660 err.span_suggestion_verbose(
661 self.cast_span.shrink_to_lo(),
662 "consider casting to a reference instead",
663 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mtstr))
})format!("&{mtstr}"),
664 Applicability::MachineApplicable,
665 );
666 }
667 ty::Adt(def, ..) if def.is_box() => {
668 err.multipart_suggestion(
669 "you can cast to a `Box` instead",
670 ::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![
671 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
672 (self.cast_span.shrink_to_hi(), ">".to_string()),
673 ],
674 Applicability::MachineApplicable,
675 );
676 }
677 _ => {
678 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
679 }
680 }
681 err.emit()
682 }
683
684 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
685 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
686 (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
687 } else {
688 (false, lint::builtin::TRIVIAL_CASTS)
689 };
690 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
691 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
692 fcx.tcx.emit_node_span_lint(
693 lint,
694 self.expr.hir_id,
695 self.span,
696 errors::TrivialCast { numeric, expr_ty, cast_ty },
697 );
698 }
699
700 #[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(700u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["self"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.expr_ty =
fcx.structurally_resolve_type(self.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:705",
"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(705u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_cast({0}, {1:?} as {2:?})",
self.expr.hir_id, self.expr_ty, self.cast_ty) as
&dyn Value))])
});
} else { ; }
};
if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
&& !self.cast_ty.has_infer_types() {
self.report_cast_to_unsized_type(fcx);
} else if self.expr_ty.references_error() ||
self.cast_ty.references_error()
{} else {
match self.try_coercion_cast(fcx) {
Ok(()) => {
if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:723",
"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(723u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> PointerCast")
as &dyn Value))])
});
} else { ; }
};
} else {
self.trivial_cast_lint(fcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:726",
"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(726u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> CoercionCast")
as &dyn Value))])
});
} else { ; }
};
fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
}
}
Err(_) => {
match self.do_check(fcx) {
Ok(k) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/cast.rs:735",
"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(735u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" -> {0:?}",
k) as &dyn Value))])
});
} else { ; }
};
}
Err(e) => self.report_cast_error(fcx, e),
};
}
};
}
}
}
}#[instrument(skip(fcx), level = "debug")]
701 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
702 self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
703 self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
704
705 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
706
707 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
708 && !self.cast_ty.has_infer_types()
709 {
710 self.report_cast_to_unsized_type(fcx);
711 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
712 } else {
714 match self.try_coercion_cast(fcx) {
715 Ok(()) => {
716 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
717 debug!(" -> PointerCast");
724 } else {
725 self.trivial_cast_lint(fcx);
726 debug!(" -> CoercionCast");
727 fcx.typeck_results
728 .borrow_mut()
729 .set_coercion_cast(self.expr.hir_id.local_id);
730 }
731 }
732 Err(_) => {
733 match self.do_check(fcx) {
734 Ok(k) => {
735 debug!(" -> {:?}", k);
736 }
737 Err(e) => self.report_cast_error(fcx, e),
738 };
739 }
740 };
741 }
742 }
743 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
747 use rustc_middle::ty::cast::CastTy::*;
748 use rustc_middle::ty::cast::IntTy::*;
749
750 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
751 {
752 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
753 (None, Some(t_cast)) => {
755 match *self.expr_ty.kind() {
756 ty::FnDef(..) => {
757 let f = fcx.normalize(
759 self.expr_span,
760 Unnormalized::new_wip(self.expr_ty.fn_sig(fcx.tcx)),
761 );
762 let res = fcx.coerce(
763 self.expr,
764 self.expr_ty,
765 Ty::new_fn_ptr(fcx.tcx, f),
766 AllowTwoPhase::No,
767 None,
768 );
769 if let Err(TypeError::IntrinsicCast) = res {
770 return Err(CastError::IllegalCast);
771 }
772 if res.is_err() {
773 return Err(CastError::NonScalar);
774 }
775 (FnPtr, t_cast)
776 }
777 ty::Ref(_, inner_ty, mutbl) => {
782 return match t_cast {
783 Int(_) | Float => match *inner_ty.kind() {
784 ty::Int(_)
785 | ty::Uint(_)
786 | ty::Float(_)
787 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
788 Err(CastError::NeedDeref)
789 }
790 _ => Err(CastError::NeedViaPtr),
791 },
792 Ptr(mt) => {
794 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
795 return Err(CastError::IllegalCast);
796 }
797 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
798 }
799 _ => Err(CastError::NonScalar),
800 };
801 }
802 _ => return Err(CastError::NonScalar),
803 }
804 }
805 _ => return Err(CastError::NonScalar),
806 };
807 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
808 && !adt_def.did().is_local()
809 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
810 {
811 return Err(CastError::ForeignNonExhaustiveAdt);
812 }
813 match (t_from, t_cast) {
814 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
816
817 (_, Int(Bool)) => Err(CastError::CastToBool),
819
820 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
823
824 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
826
827 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
828 Err(CastError::IllegalCast)
829 }
830
831 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), (Ptr(m_expr), Int(t_c)) => {
836 self.lossy_provenance_ptr2int_lint(fcx, t_c);
837 self.check_ptr_addr_cast(fcx, m_expr)
838 }
839 (FnPtr, Int(_)) => {
840 Ok(CastKind::FnPtrAddrCast)
842 }
843 (Int(_), Ptr(mt)) => {
845 self.fuzzy_provenance_int2ptr_lint(fcx);
846 self.check_addr_ptr_cast(fcx, mt)
847 }
848 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
850
851 (Int(CEnum), Int(_)) => {
853 self.err_if_cenum_impl_drop(fcx);
854 Ok(CastKind::EnumCast)
855 }
856 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
857
858 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
859 }
860 }
861
862 fn check_ptr_ptr_cast(
863 &self,
864 fcx: &FnCtxt<'a, 'tcx>,
865 m_src: ty::TypeAndMut<'tcx>,
866 m_dst: ty::TypeAndMut<'tcx>,
867 ) -> Result<CastKind, CastError<'tcx>> {
868 {
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:868",
"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(868u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::cast"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_ptr_ptr_cast m_src={0:?} m_dst={1:?}",
m_src, m_dst) as &dyn Value))])
});
} else { ; }
};debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
869 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
872 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
873
874 let Some(dst_kind) = dst_kind else {
876 return Err(CastError::UnknownCastPtrKind);
877 };
878
879 if dst_kind == PointerKind::Thin {
881 return Ok(CastKind::PtrPtrCast);
882 }
883
884 let Some(src_kind) = src_kind else {
886 return Err(CastError::UnknownCastPtrKind);
887 };
888
889 match (src_kind, dst_kind) {
890 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
892
893 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
895 match (src_tty.principal(), dst_tty.principal()) {
896 (Some(src_principal), Some(_)) => {
905 let tcx = fcx.tcx;
906
907 let src_obj = Ty::new_dynamic(
915 tcx,
916 tcx.mk_poly_existential_predicates(
917 &src_tty.without_auto_traits().collect::<Vec<_>>(),
918 ),
919 tcx.lifetimes.re_erased,
920 );
921 let dst_obj = Ty::new_dynamic(
922 tcx,
923 tcx.mk_poly_existential_predicates(
924 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
925 ),
926 tcx.lifetimes.re_erased,
927 );
928
929 let cause = fcx.misc(self.span);
932 if fcx
933 .at(&cause, fcx.param_env)
934 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
935 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
936 .is_err()
937 {
938 return Err(CastError::DifferingKinds { src_kind, dst_kind });
939 }
940
941 let src_auto: FxHashSet<_> = src_tty
944 .auto_traits()
945 .chain(
946 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
947 .filter(|def_id| tcx.trait_is_auto(*def_id)),
948 )
949 .collect();
950
951 let added = dst_tty
952 .auto_traits()
953 .filter(|trait_did| !src_auto.contains(trait_did))
954 .collect::<Vec<_>>();
955
956 if !added.is_empty() {
957 return Err(CastError::PtrPtrAddingAutoTrait(added));
958 }
959
960 Ok(CastKind::PtrPtrCast)
961 }
962
963 (None, None) => Ok(CastKind::PtrPtrCast),
965
966 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
996
997 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
999 }
1000 }
1001
1002 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1004
1005 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1006 }
1007 }
1008
1009 fn check_fptr_ptr_cast(
1010 &self,
1011 fcx: &FnCtxt<'a, 'tcx>,
1012 m_cast: ty::TypeAndMut<'tcx>,
1013 ) -> Result<CastKind, CastError<'tcx>> {
1014 match fcx.pointer_kind(m_cast.ty, self.span)? {
1017 None => Err(CastError::UnknownCastPtrKind),
1018 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1019 _ => Err(CastError::IllegalCast),
1020 }
1021 }
1022
1023 fn check_ptr_addr_cast(
1024 &self,
1025 fcx: &FnCtxt<'a, 'tcx>,
1026 m_expr: ty::TypeAndMut<'tcx>,
1027 ) -> Result<CastKind, CastError<'tcx>> {
1028 match fcx.pointer_kind(m_expr.ty, self.span)? {
1031 None => Err(CastError::UnknownExprPtrKind),
1032 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1033 _ => Err(CastError::NeedViaThinPtr),
1034 }
1035 }
1036
1037 fn check_ref_cast(
1038 &self,
1039 fcx: &FnCtxt<'a, 'tcx>,
1040 mut m_expr: ty::TypeAndMut<'tcx>,
1041 mut m_cast: ty::TypeAndMut<'tcx>,
1042 ) -> Result<CastKind, CastError<'tcx>> {
1043 m_expr.ty = fcx.try_structurally_resolve_type(self.expr_span, m_expr.ty);
1045 m_cast.ty = fcx.try_structurally_resolve_type(self.cast_span, m_cast.ty);
1046
1047 if m_expr.mutbl >= m_cast.mutbl
1048 && let ty::Array(ety, _) = m_expr.ty.kind()
1049 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1050 {
1051 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1056 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1057 .unwrap_or_else(|_| {
1058 ::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!(
1059 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1060 self.expr_ty,
1061 array_ptr_type,
1062 )
1063 });
1064
1065 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1067 return Ok(CastKind::ArrayPtrCast);
1068 }
1069
1070 Err(CastError::IllegalCast)
1071 }
1072
1073 fn check_addr_ptr_cast(
1074 &self,
1075 fcx: &FnCtxt<'a, 'tcx>,
1076 m_cast: TypeAndMut<'tcx>,
1077 ) -> Result<CastKind, CastError<'tcx>> {
1078 match fcx.pointer_kind(m_cast.ty, self.span)? {
1080 None => Err(CastError::UnknownCastPtrKind),
1081 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1082 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1083 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1084 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1085 Err(CastError::IntToWideCast(None))
1086 }
1087 }
1088 }
1089
1090 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1091 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1092 Ok(_) => Ok(()),
1093 Err(err) => Err(err),
1094 }
1095 }
1096
1097 fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1098 if let ty::Adt(d, _) = self.expr_ty.kind()
1099 && d.has_dtor(fcx.tcx)
1100 {
1101 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1102 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1103
1104 fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1105 }
1106 }
1107
1108 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1109 let expr_prec = fcx.precedence(self.expr);
1110 let needs_parens = expr_prec < ExprPrecedence::Unambiguous;
1111
1112 let needs_cast = !#[allow(non_exhaustive_omitted_patterns)] match t_c {
ty::cast::IntTy::U(ty::UintTy::Usize) => true,
_ => false,
}matches!(t_c, ty::cast::IntTy::U(ty::UintTy::Usize));
1113 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1114 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1115 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1116 let expr_span = self.expr_span.shrink_to_lo();
1117 let sugg = match (needs_parens, needs_cast) {
1118 (true, true) => errors::LossyProvenancePtr2IntSuggestion::NeedsParensCast {
1119 expr_span,
1120 cast_span,
1121 cast_ty,
1122 },
1123 (true, false) => {
1124 errors::LossyProvenancePtr2IntSuggestion::NeedsParens { expr_span, cast_span }
1125 }
1126 (false, true) => {
1127 errors::LossyProvenancePtr2IntSuggestion::NeedsCast { cast_span, cast_ty }
1128 }
1129 (false, false) => errors::LossyProvenancePtr2IntSuggestion::Other { cast_span },
1130 };
1131
1132 let lint = errors::LossyProvenancePtr2Int { expr_ty, cast_ty, sugg };
1133 fcx.tcx.emit_node_span_lint(
1134 lint::builtin::LOSSY_PROVENANCE_CASTS,
1135 self.expr.hir_id,
1136 self.span,
1137 lint,
1138 );
1139 }
1140
1141 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1142 let sugg = errors::LossyProvenanceInt2PtrSuggestion {
1143 lo: self.expr_span.shrink_to_lo(),
1144 hi: self.expr_span.shrink_to_hi().to(self.cast_span),
1145 };
1146 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1147 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1148 let lint = errors::LossyProvenanceInt2Ptr { expr_ty, cast_ty, sugg };
1149 fcx.tcx.emit_node_span_lint(
1150 lint::builtin::FUZZY_PROVENANCE_CASTS,
1151 self.expr.hir_id,
1152 self.span,
1153 lint,
1154 );
1155 }
1156
1157 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1160 if self.cast_ty.is_bool() {
1161 let derefed = fcx
1162 .autoderef(self.expr_span, self.expr_ty)
1163 .silence_errors()
1164 .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(..)));
1165
1166 if let Some((deref_ty, _)) = derefed {
1167 if deref_ty != self.expr_ty.peel_refs() {
1169 err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1170 }
1171
1172 err.subdiagnostic(errors::UseIsEmpty {
1175 lo: self.expr_span.shrink_to_lo(),
1176 hi: self.span.with_lo(self.expr_span.hi()),
1177 expr_ty: self.expr_ty,
1178 });
1179 }
1180 }
1181 }
1182}