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::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef, elaborate};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint;
46use rustc_span::{DUMMY_SP, Span, sym};
47use rustc_trait_selection::infer::InferCtxtExt;
48use tracing::{debug, instrument};
49
50use super::FnCtxt;
51use crate::{errors, type_error_struct};
52
53#[derive(Debug)]
56pub(crate) struct CastCheck<'tcx> {
57 expr: &'tcx hir::Expr<'tcx>,
59 expr_ty: Ty<'tcx>,
61 expr_span: Span,
62 cast_ty: Ty<'tcx>,
64 cast_span: Span,
65 span: Span,
66 pub body_id: LocalDefId,
67}
68
69#[derive(Debug, Copy, Clone, PartialEq, Eq, TypeVisitable, TypeFoldable)]
73enum PointerKind<'tcx> {
74 Thin,
76 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
78 Length,
80 OfAlias(ty::AliasTy<'tcx>),
82 OfParam(ty::ParamTy),
84}
85
86impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
87 fn pointer_kind(
90 &self,
91 t: Ty<'tcx>,
92 span: Span,
93 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
94 debug!("pointer_kind({:?}, {:?})", t, span);
95
96 let t = self.resolve_vars_if_possible(t);
97 t.error_reported()?;
98
99 if self.type_is_sized_modulo_regions(self.param_env, t) {
100 return Ok(Some(PointerKind::Thin));
101 }
102
103 let t = self.try_structurally_resolve_type(span, t);
104
105 Ok(match *t.kind() {
106 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
107 ty::Dynamic(tty, _) => Some(PointerKind::VTable(tty)),
108 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
109 None => Some(PointerKind::Thin),
110 Some(f) => {
111 let field_ty = self.field_ty(span, f, args);
112 self.pointer_kind(field_ty, span)?
113 }
114 },
115 ty::Tuple(fields) => match fields.last() {
116 None => Some(PointerKind::Thin),
117 Some(&f) => self.pointer_kind(f, span)?,
118 },
119
120 ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
121
122 ty::Foreign(..) => Some(PointerKind::Thin),
124 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
126 ty::Param(p) => Some(PointerKind::OfParam(p)),
127 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
129
130 ty::Bool
131 | ty::Char
132 | ty::Int(..)
133 | ty::Uint(..)
134 | ty::Float(_)
135 | ty::Array(..)
136 | ty::CoroutineWitness(..)
137 | ty::RawPtr(_, _)
138 | ty::Ref(..)
139 | ty::Pat(..)
140 | ty::FnDef(..)
141 | ty::FnPtr(..)
142 | ty::Closure(..)
143 | ty::CoroutineClosure(..)
144 | ty::Coroutine(..)
145 | ty::Adt(..)
146 | ty::Never
147 | ty::Error(_) => {
148 let guar = self
149 .dcx()
150 .span_delayed_bug(span, format!("`{t:?}` should be sized but is not?"));
151 return Err(guar);
152 }
153 })
154 }
155}
156
157#[derive(Debug)]
158enum CastError<'tcx> {
159 ErrorGuaranteed(ErrorGuaranteed),
160
161 CastToBool,
162 CastToChar,
163 DifferingKinds {
164 src_kind: PointerKind<'tcx>,
165 dst_kind: PointerKind<'tcx>,
166 },
167 SizedUnsizedCast,
169 IllegalCast,
170 NeedDeref,
171 NeedViaPtr,
172 NeedViaThinPtr,
173 NeedViaInt,
174 NonScalar,
175 UnknownExprPtrKind,
176 UnknownCastPtrKind,
177 IntToWideCast(Option<&'static str>),
183 ForeignNonExhaustiveAdt,
184 PtrPtrAddingAutoTrait(Vec<DefId>),
185}
186
187impl From<ErrorGuaranteed> for CastError<'_> {
188 fn from(err: ErrorGuaranteed) -> Self {
189 CastError::ErrorGuaranteed(err)
190 }
191}
192
193fn make_invalid_casting_error<'a, 'tcx>(
194 span: Span,
195 expr_ty: Ty<'tcx>,
196 cast_ty: Ty<'tcx>,
197 fcx: &FnCtxt<'a, 'tcx>,
198) -> Diag<'a> {
199 type_error_struct!(
200 fcx.dcx(),
201 span,
202 expr_ty,
203 E0606,
204 "casting `{}` as `{}` is invalid",
205 fcx.ty_to_string(expr_ty),
206 fcx.ty_to_string(cast_ty)
207 )
208}
209
210pub fn check_cast<'tcx>(
215 tcx: TyCtxt<'tcx>,
216 param_env: ty::ParamEnv<'tcx>,
217 e: &'tcx hir::Expr<'tcx>,
218 from_ty: Ty<'tcx>,
219 to_ty: Ty<'tcx>,
220) -> Option<CastKind> {
221 let hir_id = e.hir_id;
222 let local_def_id = hir_id.owner.def_id;
223
224 let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
225 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
226
227 if let Ok(check) = CastCheck::new(
228 &fn_ctxt, e, from_ty, to_ty,
229 DUMMY_SP, DUMMY_SP,
231 ) {
232 check.do_check(&fn_ctxt).ok()
233 } else {
234 None
235 }
236}
237
238impl<'a, 'tcx> CastCheck<'tcx> {
239 pub(crate) fn new(
240 fcx: &FnCtxt<'a, 'tcx>,
241 expr: &'tcx hir::Expr<'tcx>,
242 expr_ty: Ty<'tcx>,
243 cast_ty: Ty<'tcx>,
244 cast_span: Span,
245 span: Span,
246 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
247 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
248 let check =
249 CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span, body_id: fcx.body_id };
250
251 match cast_ty.kind() {
255 ty::Dynamic(_, _) | ty::Slice(..) => Err(check.report_cast_to_unsized_type(fcx)),
256 _ => Ok(check),
257 }
258 }
259
260 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
261 match e {
262 CastError::ErrorGuaranteed(_) => {
263 }
265 CastError::NeedDeref => {
266 let mut err =
267 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
268
269 if matches!(self.expr.kind, ExprKind::AddrOf(..)) {
270 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
272 err.span_suggestion_verbose(
273 span,
274 "remove the unneeded borrow",
275 "",
276 Applicability::MachineApplicable,
277 );
278 } else {
279 err.span_suggestion_verbose(
280 self.expr_span.shrink_to_lo(),
281 "dereference the expression",
282 "*",
283 Applicability::MachineApplicable,
284 );
285 }
286
287 err.emit();
288 }
289 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
290 let mut err =
291 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
292 if self.cast_ty.is_integral() {
293 err.help(format!("cast through {} first", match e {
294 CastError::NeedViaPtr => "a raw pointer",
295 CastError::NeedViaThinPtr => "a thin pointer",
296 e => unreachable!("control flow means we should never encounter a {e:?}"),
297 }));
298 }
299
300 self.try_suggest_collection_to_bool(fcx, &mut err);
301
302 err.emit();
303 }
304 CastError::NeedViaInt => {
305 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
306 .with_help("cast through an integer first")
307 .emit();
308 }
309 CastError::IllegalCast => {
310 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
311 }
312 CastError::DifferingKinds { src_kind, dst_kind } => {
313 let mut err =
314 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
315
316 match (src_kind, dst_kind) {
317 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
318 err.note("the trait objects may have different vtables");
319 }
320 (
321 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
322 PointerKind::OfParam(_)
323 | PointerKind::OfAlias(_)
324 | PointerKind::VTable(_)
325 | PointerKind::Length,
326 )
327 | (
328 PointerKind::VTable(_) | PointerKind::Length,
329 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
330 ) => {
331 err.note("the pointers may have different metadata");
332 }
333 (PointerKind::VTable(_), PointerKind::Length)
334 | (PointerKind::Length, PointerKind::VTable(_)) => {
335 err.note("the pointers have different metadata");
336 }
337 (
338 PointerKind::Thin,
339 PointerKind::Thin
340 | PointerKind::VTable(_)
341 | PointerKind::Length
342 | PointerKind::OfParam(_)
343 | PointerKind::OfAlias(_),
344 )
345 | (
346 PointerKind::VTable(_)
347 | PointerKind::Length
348 | PointerKind::OfParam(_)
349 | PointerKind::OfAlias(_),
350 PointerKind::Thin,
351 )
352 | (PointerKind::Length, PointerKind::Length) => {
353 span_bug!(self.span, "unexpected cast error: {e:?}")
354 }
355 }
356
357 err.emit();
358 }
359 CastError::CastToBool => {
360 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
361 let help = if self.expr_ty.is_numeric() {
362 errors::CannotCastToBoolHelp::Numeric(
363 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
364 )
365 } else {
366 errors::CannotCastToBoolHelp::Unsupported(self.span)
367 };
368 fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help });
369 }
370 CastError::CastToChar => {
371 let mut err = type_error_struct!(
372 fcx.dcx(),
373 self.span,
374 self.expr_ty,
375 E0604,
376 "only `u8` can be cast as `char`, not `{}`",
377 self.expr_ty
378 );
379 err.span_label(self.span, "invalid cast");
380 if self.expr_ty.is_numeric() {
381 if self.expr_ty == fcx.tcx.types.u32 {
382 err.multipart_suggestion(
383 "consider using `char::from_u32` instead",
384 vec![
385 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
386 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
387 ],
388 Applicability::MachineApplicable,
389 );
390 } else if self.expr_ty == fcx.tcx.types.i8 {
391 err.span_help(self.span, "consider casting from `u8` instead");
392 } else {
393 err.span_help(
394 self.span,
395 "consider using `char::from_u32` instead (via a `u32`)",
396 );
397 };
398 }
399 err.emit();
400 }
401 CastError::NonScalar => {
402 let mut err = type_error_struct!(
403 fcx.dcx(),
404 self.span,
405 self.expr_ty,
406 E0605,
407 "non-primitive cast: `{}` as `{}`",
408 self.expr_ty,
409 fcx.ty_to_string(self.cast_ty)
410 );
411
412 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
413 && matches!(self.expr.kind, ExprKind::AddrOf(..))
414 {
415 err.note(format!(
416 "casting reference expression `{}` because `&` binds tighter than `as`",
417 snippet
418 ));
419 }
420
421 let mut sugg = None;
422 let mut sugg_mutref = false;
423 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
424 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
425 && fcx.may_coerce(
426 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
427 self.cast_ty,
428 )
429 {
430 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
431 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
432 && expr_mutbl == Mutability::Not
433 && mutbl == Mutability::Mut
434 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
435 {
436 sugg_mutref = true;
437 }
438
439 if !sugg_mutref
440 && sugg == None
441 && fcx.may_coerce(
442 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
443 self.cast_ty,
444 )
445 {
446 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
447 }
448 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
449 && fcx.may_coerce(
450 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
451 self.cast_ty,
452 )
453 {
454 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
455 }
456 if sugg_mutref {
457 err.span_label(self.span, "invalid cast");
458 err.span_note(self.expr_span, "this reference is immutable");
459 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
460 } else if let Some((sugg, remove_cast)) = sugg {
461 err.span_label(self.span, "invalid cast");
462
463 let has_parens = fcx
464 .tcx
465 .sess
466 .source_map()
467 .span_to_snippet(self.expr_span)
468 .is_ok_and(|snip| snip.starts_with('('));
469
470 let needs_parens =
474 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
475
476 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
477 if needs_parens {
478 suggestion[0].1 += "(";
479 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
480 }
481 if remove_cast {
482 suggestion.push((
483 self.expr_span.shrink_to_hi().to(self.cast_span),
484 String::new(),
485 ));
486 }
487
488 err.multipart_suggestion_verbose(
489 "consider borrowing the value",
490 suggestion,
491 Applicability::MachineApplicable,
492 );
493 } else if !matches!(
494 self.cast_ty.kind(),
495 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
496 ) {
497 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
499 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
500 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
501 if fcx
502 .infcx
503 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
504 .must_apply_modulo_regions()
505 {
506 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
507 fcx.tcx.value_path_str_with_args(def.did(), args)
508 } else {
509 self.cast_ty.to_string()
510 };
511 err.multipart_suggestion(
512 "consider using the `From` trait instead",
513 vec![
514 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
515 (
516 self.expr_span.shrink_to_hi().to(self.cast_span),
517 ")".to_string(),
518 ),
519 ],
520 Applicability::MaybeIncorrect,
521 );
522 }
523 }
524
525 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
526 && adt.is_enum()
527 && self.cast_ty.is_numeric()
528 {
529 (
530 "an `as` expression can be used to convert enum types to numeric \
531 types only if the enum type is unit-only or field-less",
532 Some(
533 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
534 ),
535 )
536 } else {
537 (
538 "an `as` expression can only be used to convert between primitive \
539 types or to coerce to a specific trait object",
540 None,
541 )
542 };
543
544 err.span_label(self.span, msg);
545
546 if let Some(note) = note {
547 err.note(note);
548 }
549 } else {
550 err.span_label(self.span, "invalid cast");
551 }
552
553 fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
554 self.try_suggest_collection_to_bool(fcx, &mut err);
555
556 err.emit();
557 }
558 CastError::SizedUnsizedCast => {
559 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
560 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
561 fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
562 span: self.span,
563 expr_ty,
564 cast_ty,
565 teach: fcx.tcx.sess.teach(E0607),
566 });
567 }
568 CastError::IntToWideCast(known_metadata) => {
569 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
570 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
571 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
572 let metadata = known_metadata.unwrap_or("type-specific metadata");
573 let known_wide = known_metadata.is_some();
574 let span = self.cast_span;
575 fcx.dcx().emit_err(errors::IntToWide {
576 span,
577 metadata,
578 expr_ty,
579 cast_ty,
580 expr_if_nightly,
581 known_wide,
582 });
583 }
584 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
585 let unknown_cast_to = match e {
586 CastError::UnknownCastPtrKind => true,
587 CastError::UnknownExprPtrKind => false,
588 e => unreachable!("control flow means we should never encounter a {e:?}"),
589 };
590 let (span, sub) = if unknown_cast_to {
591 (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
592 } else {
593 (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
594 };
595 fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
596 }
597 CastError::ForeignNonExhaustiveAdt => {
598 make_invalid_casting_error(
599 self.span,
600 self.expr_ty,
601 self.cast_ty,
602 fcx,
603 )
604 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
605 .emit();
606 }
607 CastError::PtrPtrAddingAutoTrait(added) => {
608 fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
609 span: self.span,
610 traits_len: added.len(),
611 traits: {
612 let mut traits: Vec<_> = added
613 .into_iter()
614 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
615 .collect();
616
617 traits.sort();
618 traits.into()
619 },
620 });
621 }
622 }
623 }
624
625 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
626 if let Err(err) = self.cast_ty.error_reported() {
627 return err;
628 }
629 if let Err(err) = self.expr_ty.error_reported() {
630 return err;
631 }
632
633 let tstr = fcx.ty_to_string(self.cast_ty);
634 let mut err = type_error_struct!(
635 fcx.dcx(),
636 self.span,
637 self.expr_ty,
638 E0620,
639 "cast to unsized type: `{}` as `{}`",
640 fcx.resolve_vars_if_possible(self.expr_ty),
641 tstr
642 );
643 match self.expr_ty.kind() {
644 ty::Ref(_, _, mt) => {
645 let mtstr = mt.prefix_str();
646 err.span_suggestion_verbose(
647 self.cast_span.shrink_to_lo(),
648 "consider casting to a reference instead",
649 format!("&{mtstr}"),
650 Applicability::MachineApplicable,
651 );
652 }
653 ty::Adt(def, ..) if def.is_box() => {
654 err.multipart_suggestion(
655 "you can cast to a `Box` instead",
656 vec![
657 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
658 (self.cast_span.shrink_to_hi(), ">".to_string()),
659 ],
660 Applicability::MachineApplicable,
661 );
662 }
663 _ => {
664 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
665 }
666 }
667 err.emit()
668 }
669
670 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
671 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
672 (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
673 } else {
674 (false, lint::builtin::TRIVIAL_CASTS)
675 };
676 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
677 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
678 fcx.tcx.emit_node_span_lint(
679 lint,
680 self.expr.hir_id,
681 self.span,
682 errors::TrivialCast { numeric, expr_ty, cast_ty },
683 );
684 }
685
686 #[instrument(skip(fcx), level = "debug")]
687 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
688 self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
689 self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
690
691 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
692
693 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
694 && !self.cast_ty.has_infer_types()
695 {
696 self.report_cast_to_unsized_type(fcx);
697 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
698 } else {
700 match self.try_coercion_cast(fcx) {
701 Ok(()) => {
702 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
703 debug!(" -> PointerCast");
710 } else {
711 self.trivial_cast_lint(fcx);
712 debug!(" -> CoercionCast");
713 fcx.typeck_results
714 .borrow_mut()
715 .set_coercion_cast(self.expr.hir_id.local_id);
716 }
717 }
718 Err(_) => {
719 match self.do_check(fcx) {
720 Ok(k) => {
721 debug!(" -> {:?}", k);
722 }
723 Err(e) => self.report_cast_error(fcx, e),
724 };
725 }
726 };
727 }
728 }
729 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
733 use rustc_middle::ty::cast::CastTy::*;
734 use rustc_middle::ty::cast::IntTy::*;
735
736 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
737 {
738 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
739 (None, Some(t_cast)) => {
741 match *self.expr_ty.kind() {
742 ty::FnDef(..) => {
743 let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
745 let res = fcx.coerce(
746 self.expr,
747 self.expr_ty,
748 Ty::new_fn_ptr(fcx.tcx, f),
749 AllowTwoPhase::No,
750 None,
751 );
752 if let Err(TypeError::IntrinsicCast) = res {
753 return Err(CastError::IllegalCast);
754 }
755 if res.is_err() {
756 return Err(CastError::NonScalar);
757 }
758 (FnPtr, t_cast)
759 }
760 ty::Ref(_, inner_ty, mutbl) => {
765 return match t_cast {
766 Int(_) | Float => match *inner_ty.kind() {
767 ty::Int(_)
768 | ty::Uint(_)
769 | ty::Float(_)
770 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
771 Err(CastError::NeedDeref)
772 }
773 _ => Err(CastError::NeedViaPtr),
774 },
775 Ptr(mt) => {
777 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
778 return Err(CastError::IllegalCast);
779 }
780 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
781 }
782 _ => Err(CastError::NonScalar),
783 };
784 }
785 _ => return Err(CastError::NonScalar),
786 }
787 }
788 _ => return Err(CastError::NonScalar),
789 };
790 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
791 && !adt_def.did().is_local()
792 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
793 {
794 return Err(CastError::ForeignNonExhaustiveAdt);
795 }
796 match (t_from, t_cast) {
797 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
799
800 (_, Int(Bool)) => Err(CastError::CastToBool),
802
803 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
806
807 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
809
810 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
811 Err(CastError::IllegalCast)
812 }
813
814 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), (Ptr(m_expr), Int(t_c)) => {
819 self.lossy_provenance_ptr2int_lint(fcx, t_c);
820 self.check_ptr_addr_cast(fcx, m_expr)
821 }
822 (FnPtr, Int(_)) => {
823 Ok(CastKind::FnPtrAddrCast)
825 }
826 (Int(_), Ptr(mt)) => {
828 self.fuzzy_provenance_int2ptr_lint(fcx);
829 self.check_addr_ptr_cast(fcx, mt)
830 }
831 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
833
834 (Int(CEnum), Int(_)) => {
836 self.err_if_cenum_impl_drop(fcx);
837 Ok(CastKind::EnumCast)
838 }
839 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
840
841 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
842 }
843 }
844
845 fn check_ptr_ptr_cast(
846 &self,
847 fcx: &FnCtxt<'a, 'tcx>,
848 m_src: ty::TypeAndMut<'tcx>,
849 m_dst: ty::TypeAndMut<'tcx>,
850 ) -> Result<CastKind, CastError<'tcx>> {
851 debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
852 let src_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_src.ty, self.span)?);
855 let dst_kind = fcx.tcx.erase_and_anonymize_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
856
857 let Some(dst_kind) = dst_kind else {
859 return Err(CastError::UnknownCastPtrKind);
860 };
861
862 if dst_kind == PointerKind::Thin {
864 return Ok(CastKind::PtrPtrCast);
865 }
866
867 let Some(src_kind) = src_kind else {
869 return Err(CastError::UnknownCastPtrKind);
870 };
871
872 match (src_kind, dst_kind) {
873 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
875
876 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
878 match (src_tty.principal(), dst_tty.principal()) {
879 (Some(src_principal), Some(_)) => {
888 let tcx = fcx.tcx;
889
890 let src_obj = Ty::new_dynamic(
898 tcx,
899 tcx.mk_poly_existential_predicates(
900 &src_tty.without_auto_traits().collect::<Vec<_>>(),
901 ),
902 tcx.lifetimes.re_erased,
903 );
904 let dst_obj = Ty::new_dynamic(
905 tcx,
906 tcx.mk_poly_existential_predicates(
907 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
908 ),
909 tcx.lifetimes.re_erased,
910 );
911
912 let cause = fcx.misc(self.span);
915 if fcx
916 .at(&cause, fcx.param_env)
917 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
918 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
919 .is_err()
920 {
921 return Err(CastError::DifferingKinds { src_kind, dst_kind });
922 }
923
924 let src_auto: FxHashSet<_> = src_tty
927 .auto_traits()
928 .chain(
929 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
930 .filter(|def_id| tcx.trait_is_auto(*def_id)),
931 )
932 .collect();
933
934 let added = dst_tty
935 .auto_traits()
936 .filter(|trait_did| !src_auto.contains(trait_did))
937 .collect::<Vec<_>>();
938
939 if !added.is_empty() {
940 return Err(CastError::PtrPtrAddingAutoTrait(added));
941 }
942
943 Ok(CastKind::PtrPtrCast)
944 }
945
946 (None, None) => Ok(CastKind::PtrPtrCast),
948
949 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
979
980 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
982 }
983 }
984
985 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
987
988 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
989 }
990 }
991
992 fn check_fptr_ptr_cast(
993 &self,
994 fcx: &FnCtxt<'a, 'tcx>,
995 m_cast: ty::TypeAndMut<'tcx>,
996 ) -> Result<CastKind, CastError<'tcx>> {
997 match fcx.pointer_kind(m_cast.ty, self.span)? {
1000 None => Err(CastError::UnknownCastPtrKind),
1001 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1002 _ => Err(CastError::IllegalCast),
1003 }
1004 }
1005
1006 fn check_ptr_addr_cast(
1007 &self,
1008 fcx: &FnCtxt<'a, 'tcx>,
1009 m_expr: ty::TypeAndMut<'tcx>,
1010 ) -> Result<CastKind, CastError<'tcx>> {
1011 match fcx.pointer_kind(m_expr.ty, self.span)? {
1014 None => Err(CastError::UnknownExprPtrKind),
1015 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1016 _ => Err(CastError::NeedViaThinPtr),
1017 }
1018 }
1019
1020 fn check_ref_cast(
1021 &self,
1022 fcx: &FnCtxt<'a, 'tcx>,
1023 mut m_expr: ty::TypeAndMut<'tcx>,
1024 mut m_cast: ty::TypeAndMut<'tcx>,
1025 ) -> Result<CastKind, CastError<'tcx>> {
1026 m_expr.ty = fcx.try_structurally_resolve_type(self.expr_span, m_expr.ty);
1028 m_cast.ty = fcx.try_structurally_resolve_type(self.cast_span, m_cast.ty);
1029
1030 if m_expr.mutbl >= m_cast.mutbl
1031 && let ty::Array(ety, _) = m_expr.ty.kind()
1032 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1033 {
1034 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1039 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1040 .unwrap_or_else(|_| {
1041 bug!(
1042 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1043 self.expr_ty,
1044 array_ptr_type,
1045 )
1046 });
1047
1048 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1050 return Ok(CastKind::ArrayPtrCast);
1051 }
1052
1053 Err(CastError::IllegalCast)
1054 }
1055
1056 fn check_addr_ptr_cast(
1057 &self,
1058 fcx: &FnCtxt<'a, 'tcx>,
1059 m_cast: TypeAndMut<'tcx>,
1060 ) -> Result<CastKind, CastError<'tcx>> {
1061 match fcx.pointer_kind(m_cast.ty, self.span)? {
1063 None => Err(CastError::UnknownCastPtrKind),
1064 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1065 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1066 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1067 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1068 Err(CastError::IntToWideCast(None))
1069 }
1070 }
1071 }
1072
1073 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1074 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1075 Ok(_) => Ok(()),
1076 Err(err) => Err(err),
1077 }
1078 }
1079
1080 fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1081 if let ty::Adt(d, _) = self.expr_ty.kind()
1082 && d.has_dtor(fcx.tcx)
1083 {
1084 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1085 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1086
1087 fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1088 }
1089 }
1090
1091 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1092 let expr_prec = fcx.precedence(self.expr);
1093 let needs_parens = expr_prec < ExprPrecedence::Unambiguous;
1094
1095 let needs_cast = !matches!(t_c, ty::cast::IntTy::U(ty::UintTy::Usize));
1096 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1097 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1098 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1099 let expr_span = self.expr_span.shrink_to_lo();
1100 let sugg = match (needs_parens, needs_cast) {
1101 (true, true) => errors::LossyProvenancePtr2IntSuggestion::NeedsParensCast {
1102 expr_span,
1103 cast_span,
1104 cast_ty,
1105 },
1106 (true, false) => {
1107 errors::LossyProvenancePtr2IntSuggestion::NeedsParens { expr_span, cast_span }
1108 }
1109 (false, true) => {
1110 errors::LossyProvenancePtr2IntSuggestion::NeedsCast { cast_span, cast_ty }
1111 }
1112 (false, false) => errors::LossyProvenancePtr2IntSuggestion::Other { cast_span },
1113 };
1114
1115 let lint = errors::LossyProvenancePtr2Int { expr_ty, cast_ty, sugg };
1116 fcx.tcx.emit_node_span_lint(
1117 lint::builtin::LOSSY_PROVENANCE_CASTS,
1118 self.expr.hir_id,
1119 self.span,
1120 lint,
1121 );
1122 }
1123
1124 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1125 let sugg = errors::LossyProvenanceInt2PtrSuggestion {
1126 lo: self.expr_span.shrink_to_lo(),
1127 hi: self.expr_span.shrink_to_hi().to(self.cast_span),
1128 };
1129 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1130 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1131 let lint = errors::LossyProvenanceInt2Ptr { expr_ty, cast_ty, sugg };
1132 fcx.tcx.emit_node_span_lint(
1133 lint::builtin::FUZZY_PROVENANCE_CASTS,
1134 self.expr.hir_id,
1135 self.span,
1136 lint,
1137 );
1138 }
1139
1140 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1143 if self.cast_ty.is_bool() {
1144 let derefed = fcx
1145 .autoderef(self.expr_span, self.expr_ty)
1146 .silence_errors()
1147 .find(|t| matches!(t.0.kind(), ty::Str | ty::Slice(..)));
1148
1149 if let Some((deref_ty, _)) = derefed {
1150 if deref_ty != self.expr_ty.peel_refs() {
1152 err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1153 }
1154
1155 err.subdiagnostic(errors::UseIsEmpty {
1158 lo: self.expr_span.shrink_to_lo(),
1159 hi: self.span.with_lo(self.expr_span.hi()),
1160 expr_ty: self.expr_ty,
1161 });
1162 }
1163 }
1164 }
1165}