1 //! Code for type-checking cast expressions.
3 //! A cast `e as U` is valid if one of the following holds:
4 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
5 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
6 //! pointer_kind(`T`) = pointer_kind(`U_0`); *ptr-ptr-cast*
7 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
8 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
9 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
10 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
11 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
12 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
13 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
14 //! * `e` is a function pointer type and `U` has type `*T`,
15 //! while `T: Sized`; *fptr-ptr-cast*
16 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
18 //! where `&.T` and `*T` are references of either mutability,
19 //! and where pointer_kind(`T`) is the kind of the unsize info
20 //! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or
21 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
23 //! Note that lengths are not adjusted when casting raw slices -
24 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
25 //! half of the original memory.
27 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
28 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
29 //! `U1` coerces to `U2`).
33 use crate::hir::def_id::DefId;
34 use crate::type_error_struct;
35 use hir::def_id::LOCAL_CRATE;
36 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
38 use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
39 use rustc_middle::mir::Mutability;
40 use rustc_middle::ty::adjustment::AllowTwoPhase;
41 use rustc_middle::ty::cast::{CastKind, CastTy};
42 use rustc_middle::ty::error::TypeError;
43 use rustc_middle::ty::subst::SubstsRef;
44 use rustc_middle::ty::{
45 self, Binder, TraitObjectRepresentation, Ty, TypeAndMut, TypeVisitable, VariantDef,
47 use rustc_session::lint;
48 use rustc_session::Session;
49 use rustc_span::symbol::sym;
51 use rustc_trait_selection::infer::InferCtxtExt;
52 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
54 /// Reifies a cast check to be checked once we have full type information for
55 /// a function context.
57 pub struct CastCheck<'tcx> {
58 /// The expression whose value is being casted
59 expr: &'tcx hir::Expr<'tcx>,
60 /// The source type for the cast expression
63 /// The target type. That is, the type we are casting to.
69 /// The kind of pointer and associated metadata (thin, length or vtable) - we
70 /// only allow casts between fat pointers if their metadata have the same
72 #[derive(Copy, Clone, PartialEq, Eq)]
73 enum PointerKind<'tcx> {
74 /// No metadata attached, ie pointer to sized type or foreign type
77 VTable(Option<DefId>),
80 /// The unsize info of this projection
81 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
82 /// The unsize info of this opaque ty
83 OfOpaque(DefId, SubstsRef<'tcx>),
84 /// The unsize info of this parameter
85 OfParam(&'tcx ty::ParamTy),
88 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
89 /// Returns the kind of unsize information of t, or None
95 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
96 debug!("pointer_kind({:?}, {:?})", t, span);
98 let t = self.resolve_vars_if_possible(t);
100 if let Some(reported) = t.error_reported() {
101 return Err(reported);
104 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
105 return Ok(Some(PointerKind::Thin));
109 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
110 ty::Dynamic(ref tty, ..) => Some(PointerKind::VTable(tty.principal_def_id())),
111 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
112 None => Some(PointerKind::Thin),
114 let field_ty = self.field_ty(span, f, substs);
115 self.pointer_kind(field_ty, span)?
118 ty::Tuple(fields) => match fields.last() {
119 None => Some(PointerKind::Thin),
120 Some(&f) => self.pointer_kind(f, span)?,
123 // Pointers to foreign types are thin, despite being unsized
124 ty::Foreign(..) => Some(PointerKind::Thin),
125 // We should really try to normalize here.
126 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
127 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
128 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
129 // Insufficient type information.
130 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
138 | ty::GeneratorWitness(..)
151 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
152 return Err(reported);
158 #[derive(Copy, Clone)]
165 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
175 /// Cast of int to (possibly) fat raw pointer.
177 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
178 /// or "a length". If this argument is None, then the metadata is unknown, for example,
179 /// when we're typechecking a type parameter with a ?Sized bound.
180 IntToFatCast(Option<&'static str>),
181 ForeignNonExhaustiveAdt,
184 impl From<ErrorGuaranteed> for CastError {
185 fn from(_: ErrorGuaranteed) -> Self {
186 CastError::ErrorGuaranteed
190 fn make_invalid_casting_error<'a, 'tcx>(
195 fcx: &FnCtxt<'a, 'tcx>,
196 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
202 "casting `{}` as `{}` is invalid",
203 fcx.ty_to_string(expr_ty),
204 fcx.ty_to_string(cast_ty)
208 pub enum CastCheckResult<'tcx> {
210 Deferred(CastCheck<'tcx>),
211 Err(ErrorGuaranteed),
214 pub fn check_cast<'tcx>(
215 fcx: &FnCtxt<'_, 'tcx>,
216 expr: &'tcx hir::Expr<'tcx>,
221 ) -> CastCheckResult<'tcx> {
222 if cast_ty.is_dyn_star() {
223 check_dyn_star_cast(fcx, expr, expr_ty, cast_ty)
225 match CastCheck::new(fcx, expr, expr_ty, cast_ty, cast_span, span) {
226 Ok(check) => CastCheckResult::Deferred(check),
227 Err(e) => CastCheckResult::Err(e),
232 fn check_dyn_star_cast<'tcx>(
233 fcx: &FnCtxt<'_, 'tcx>,
234 expr: &'tcx hir::Expr<'tcx>,
237 ) -> CastCheckResult<'tcx> {
238 // Find the bounds in the dyn*. For eaxmple, if we have
240 // let x = 22_usize as dyn* (Clone + Debug + 'static)
242 // this would return `existential_predicates = [?Self: Clone, ?Self: Debug]` and `region = 'static`.
243 let (existential_predicates, region) = match cast_ty.kind() {
244 ty::Dynamic(predicates, region, TraitObjectRepresentation::Sized) => (predicates, region),
245 _ => panic!("Invalid dyn* cast_ty"),
248 let cause = ObligationCause::new(
251 // FIXME: Use a better obligation cause code
252 ObligationCauseCode::MiscObligation,
255 // For each existential predicate (e.g., `?Self: Clone`) substitute
256 // the type of the expression (e.g., `usize` in our example above)
257 // and then require that the resulting predicate (e.g., `usize: Clone`)
259 for existential_predicate in existential_predicates.iter() {
260 let predicate = existential_predicate.with_self_ty(fcx.tcx, expr_ty);
261 fcx.register_predicate(Obligation::new(cause.clone(), fcx.param_env, predicate));
264 // Enforce the region bound `'static` (e.g., `usize: 'static`, in our example).
265 fcx.register_predicate(Obligation::new(
268 fcx.tcx.mk_predicate(Binder::dummy(ty::PredicateKind::TypeOutlives(
269 ty::OutlivesPredicate(expr_ty, *region),
276 impl<'a, 'tcx> CastCheck<'tcx> {
278 fcx: &FnCtxt<'a, 'tcx>,
279 expr: &'tcx hir::Expr<'tcx>,
284 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
285 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
286 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
288 // For better error messages, check for some obviously unsized
289 // cases now. We do a more thorough check at the end, once
290 // inference is more completely known.
291 match cast_ty.kind() {
292 ty::Dynamic(_, _, TraitObjectRepresentation::Unsized) | ty::Slice(..) => {
293 let reported = check.report_cast_to_unsized_type(fcx);
300 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
302 CastError::ErrorGuaranteed => {
303 // an error has already been reported
305 CastError::NeedDeref => {
306 let error_span = self.span;
307 let mut err = make_invalid_casting_error(
314 let cast_ty = fcx.ty_to_string(self.cast_ty);
317 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
319 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
322 "dereference the expression",
323 format!("*{}", snippet),
324 Applicability::MaybeIncorrect,
327 err.span_help(self.expr_span, "dereference the expression with `*`");
331 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
332 let mut err = make_invalid_casting_error(
339 if self.cast_ty.is_integral() {
341 "cast through {} first",
343 CastError::NeedViaPtr => "a raw pointer",
344 CastError::NeedViaThinPtr => "a thin pointer",
351 CastError::NeedViaInt => {
352 make_invalid_casting_error(
360 "cast through {} first",
362 CastError::NeedViaInt => "an integer",
368 CastError::IllegalCast => {
369 make_invalid_casting_error(
378 CastError::DifferingKinds => {
379 make_invalid_casting_error(
386 .note("vtable kinds may not match")
389 CastError::CastToBool => {
391 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
393 if self.expr_ty.is_numeric() {
394 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
398 "compare with zero instead",
399 format!("{snippet} != 0"),
400 Applicability::MachineApplicable,
404 err.span_help(self.span, "compare with zero instead");
408 err.span_label(self.span, "unsupported cast");
413 CastError::CastToChar => {
414 let mut err = type_error_struct!(
419 "only `u8` can be cast as `char`, not `{}`",
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 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
426 Ok(snippet) => err.span_suggestion(
428 "try `char::from_u32` instead",
429 format!("char::from_u32({snippet})"),
430 Applicability::MachineApplicable,
433 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
435 } else if self.expr_ty == fcx.tcx.types.i8 {
436 err.span_help(self.span, "try casting from `u8` instead");
438 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
443 CastError::NonScalar => {
444 let mut err = type_error_struct!(
449 "non-primitive cast: `{}` as `{}`",
451 fcx.ty_to_string(self.cast_ty)
454 let mut sugg_mutref = false;
455 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
456 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
461 fcx.tcx.lifetimes.re_erased,
462 TypeAndMut { ty: expr_ty, mutbl },
470 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
471 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
472 && expr_mutbl == Mutability::Not
473 && mutbl == Mutability::Mut
479 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
495 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
502 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
504 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
509 fcx.tcx.lifetimes.re_erased,
510 TypeAndMut { ty: self.expr_ty, mutbl },
518 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
521 err.span_label(self.span, "invalid cast");
522 err.span_note(self.expr_span, "this reference is immutable");
523 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
524 } else if let Some((sugg, remove_cast)) = sugg {
525 err.span_label(self.span, "invalid cast");
531 .span_to_snippet(self.expr_span)
532 .map_or(false, |snip| snip.starts_with('('));
534 // Very crude check to see whether the expression must be wrapped
535 // in parentheses for the suggestion to work (issue #89497).
536 // Can/should be extended in the future.
538 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
540 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
542 suggestion[0].1 += "(";
543 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
547 self.expr_span.shrink_to_hi().to(self.cast_span),
552 err.multipart_suggestion_verbose(
553 "consider borrowing the value",
555 Applicability::MachineApplicable,
559 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
561 let mut label = true;
562 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
563 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
564 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
566 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
567 // Erase regions to avoid panic in `prove_value` when calling
568 // `type_implements_trait`.
569 let ty = fcx.tcx.erase_regions(ty);
570 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
571 let expr_ty = fcx.tcx.erase_regions(expr_ty);
572 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
575 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
576 .must_apply_modulo_regions()
581 "consider using the `From` trait instead",
582 format!("{}::from({})", self.cast_ty, snippet),
583 Applicability::MaybeIncorrect,
587 let msg = "an `as` expression can only be used to convert between primitive \
588 types or to coerce to a specific trait object";
590 err.span_label(self.span, msg);
595 err.span_label(self.span, "invalid cast");
599 CastError::SizedUnsizedCast => {
600 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
605 expr_ty: self.expr_ty,
606 cast_ty: fcx.ty_to_string(self.cast_ty),
611 CastError::IntToFatCast(known_metadata) => {
612 let mut err = struct_span_err!(
616 "cannot cast `{}` to a pointer that {} wide",
617 fcx.ty_to_string(self.expr_ty),
618 if known_metadata.is_some() { "is" } else { "may be" }
624 "creating a `{}` requires both an address and {}",
626 known_metadata.unwrap_or("type-specific metadata"),
630 if fcx.tcx.sess.is_nightly_build() {
633 "consider casting this expression to `*const ()`, \
634 then using `core::ptr::from_raw_parts`",
640 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
641 let unknown_cast_to = match e {
642 CastError::UnknownCastPtrKind => true,
643 CastError::UnknownExprPtrKind => false,
646 let mut err = struct_span_err!(
648 if unknown_cast_to { self.cast_span } else { self.span },
650 "cannot cast {} a pointer of an unknown kind",
651 if unknown_cast_to { "to" } else { "from" }
654 err.span_label(self.cast_span, "needs more type information");
656 "the type information given here is insufficient to check whether \
657 the pointer cast is valid",
662 "the type information given here is insufficient to check whether \
663 the pointer cast is valid",
668 CastError::ForeignNonExhaustiveAdt => {
669 make_invalid_casting_error(
676 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
682 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
683 if let Some(reported) =
684 self.cast_ty.error_reported().or_else(|| self.expr_ty.error_reported())
689 let tstr = fcx.ty_to_string(self.cast_ty);
690 let mut err = type_error_struct!(
695 "cast to unsized type: `{}` as `{}`",
696 fcx.resolve_vars_if_possible(self.expr_ty),
699 match self.expr_ty.kind() {
700 ty::Ref(_, _, mt) => {
701 let mtstr = mt.prefix_str();
702 if self.cast_ty.is_trait() {
703 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
707 "try casting to a reference instead",
708 format!("&{}{}", mtstr, s),
709 Applicability::MachineApplicable,
713 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
714 err.span_help(self.cast_span, msg);
719 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
720 err.span_help(self.span, msg);
723 ty::Adt(def, ..) if def.is_box() => {
724 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
728 "you can cast to a `Box` instead",
730 Applicability::MachineApplicable,
736 &format!("you might have meant `Box<{tstr}>`"),
742 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
748 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
749 let t_cast = self.cast_ty;
750 let t_expr = self.expr_ty;
752 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
753 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
754 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
756 ("", lint::builtin::TRIVIAL_CASTS)
758 fcx.tcx.struct_span_lint_hir(lint, self.expr.hir_id, self.span, |err| {
760 "trivial {}cast: `{}` as `{}`",
762 fcx.ty_to_string(t_expr),
763 fcx.ty_to_string(t_cast)
766 "cast can be replaced by coercion; this might \
767 require {type_asc_or}a temporary variable"
773 #[instrument(skip(fcx), level = "debug")]
774 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
775 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
776 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
778 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
780 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
781 && !self.cast_ty.has_infer_types()
783 self.report_cast_to_unsized_type(fcx);
784 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
785 // No sense in giving duplicate error messages
787 match self.try_coercion_cast(fcx) {
789 self.trivial_cast_lint(fcx);
790 debug!(" -> CoercionCast");
791 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
793 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
794 self.report_object_unsafe_cast(&fcx, did);
797 match self.do_check(fcx) {
799 debug!(" -> {:?}", k);
801 Err(e) => self.report_cast_error(fcx, e),
808 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
809 let violations = fcx.tcx.object_safety_violations(did);
810 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
811 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
815 /// Checks a cast, and report an error if one exists. In some cases, this
816 /// can return Ok and create type errors in the fcx rather than returning
817 /// directly. coercion-cast is handled in check instead of here.
818 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
819 use rustc_middle::ty::cast::CastTy::*;
820 use rustc_middle::ty::cast::IntTy::*;
822 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
824 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
825 // Function item types may need to be reified before casts.
826 (None, Some(t_cast)) => {
827 match *self.expr_ty.kind() {
829 // Attempt a coercion to a fn pointer type.
830 let f = fcx.normalize_associated_types_in(
832 self.expr_ty.fn_sig(fcx.tcx),
834 let res = fcx.try_coerce(
837 fcx.tcx.mk_fn_ptr(f),
841 if let Err(TypeError::IntrinsicCast) = res {
842 return Err(CastError::IllegalCast);
845 return Err(CastError::NonScalar);
849 // Special case some errors for references, and check for
850 // array-ptr-casts. `Ref` is not a CastTy because the cast
851 // is split into a coercion to a pointer type, followed by
853 ty::Ref(_, inner_ty, mutbl) => {
854 return match t_cast {
855 Int(_) | Float => match *inner_ty.kind() {
859 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
860 Err(CastError::NeedDeref)
862 _ => Err(CastError::NeedViaPtr),
866 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
868 _ => Err(CastError::NonScalar),
871 _ => return Err(CastError::NonScalar),
874 _ => return Err(CastError::NonScalar),
877 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
878 if adt_def.did().krate != LOCAL_CRATE {
879 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
880 return Err(CastError::ForeignNonExhaustiveAdt);
885 match (t_from, t_cast) {
886 // These types have invariants! can't cast into them.
887 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
890 (_, Int(Bool)) => Err(CastError::CastToBool),
893 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
894 (_, Int(Char)) => Err(CastError::CastToChar),
897 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
899 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
900 Err(CastError::IllegalCast)
904 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
907 (Ptr(m_expr), Int(t_c)) => {
908 self.lossy_provenance_ptr2int_lint(fcx, t_c);
909 self.check_ptr_addr_cast(fcx, m_expr)
912 // FIXME(#95489): there should eventually be a lint for these casts
913 Ok(CastKind::FnPtrAddrCast)
916 (Int(_), Ptr(mt)) => {
917 self.fuzzy_provenance_int2ptr_lint(fcx);
918 self.check_addr_ptr_cast(fcx, mt)
921 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
924 (Int(CEnum), Int(_)) => {
925 self.cenum_impl_drop_lint(fcx);
926 Ok(CastKind::EnumCast)
928 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
930 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
932 // FIXME: this needs more conditions...
933 (_, DynStar) => Ok(CastKind::DynStarCast),
935 // FIXME: do we want to allow dyn* upcasting or other casts?
936 (DynStar, _) => Err(CastError::IllegalCast),
940 fn check_ptr_ptr_cast(
942 fcx: &FnCtxt<'a, 'tcx>,
943 m_expr: ty::TypeAndMut<'tcx>,
944 m_cast: ty::TypeAndMut<'tcx>,
945 ) -> Result<CastKind, CastError> {
946 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
947 // ptr-ptr cast. vtables must match.
949 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
950 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
952 let Some(cast_kind) = cast_kind else {
953 // We can't cast if target pointer kind is unknown
954 return Err(CastError::UnknownCastPtrKind);
957 // Cast to thin pointer is OK
958 if cast_kind == PointerKind::Thin {
959 return Ok(CastKind::PtrPtrCast);
962 let Some(expr_kind) = expr_kind else {
963 // We can't cast to fat pointer if source pointer kind is unknown
964 return Err(CastError::UnknownExprPtrKind);
967 // thin -> fat? report invalid cast (don't complain about vtable kinds)
968 if expr_kind == PointerKind::Thin {
969 return Err(CastError::SizedUnsizedCast);
972 // vtable kinds must match
973 if cast_kind == expr_kind {
974 Ok(CastKind::PtrPtrCast)
976 Err(CastError::DifferingKinds)
980 fn check_fptr_ptr_cast(
982 fcx: &FnCtxt<'a, 'tcx>,
983 m_cast: ty::TypeAndMut<'tcx>,
984 ) -> Result<CastKind, CastError> {
985 // fptr-ptr cast. must be to thin ptr
987 match fcx.pointer_kind(m_cast.ty, self.span)? {
988 None => Err(CastError::UnknownCastPtrKind),
989 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
990 _ => Err(CastError::IllegalCast),
994 fn check_ptr_addr_cast(
996 fcx: &FnCtxt<'a, 'tcx>,
997 m_expr: ty::TypeAndMut<'tcx>,
998 ) -> Result<CastKind, CastError> {
999 // ptr-addr cast. must be from thin ptr
1001 match fcx.pointer_kind(m_expr.ty, self.span)? {
1002 None => Err(CastError::UnknownExprPtrKind),
1003 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1004 _ => Err(CastError::NeedViaThinPtr),
1010 fcx: &FnCtxt<'a, 'tcx>,
1011 m_expr: ty::TypeAndMut<'tcx>,
1012 m_cast: ty::TypeAndMut<'tcx>,
1013 ) -> Result<CastKind, CastError> {
1014 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1015 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
1016 if let ty::Array(ety, _) = m_expr.ty.kind() {
1017 // Due to the limitations of LLVM global constants,
1018 // region pointers end up pointing at copies of
1019 // vector elements instead of the original values.
1020 // To allow raw pointers to work correctly, we
1021 // need to special-case obtaining a raw pointer
1022 // from a region pointer to a vector.
1024 // Coerce to a raw pointer so that we generate AddressOf in MIR.
1025 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
1026 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1027 .unwrap_or_else(|_| {
1029 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1035 // this will report a type mismatch if needed
1036 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1037 return Ok(CastKind::ArrayPtrCast);
1041 Err(CastError::IllegalCast)
1044 fn check_addr_ptr_cast(
1046 fcx: &FnCtxt<'a, 'tcx>,
1047 m_cast: TypeAndMut<'tcx>,
1048 ) -> Result<CastKind, CastError> {
1049 // ptr-addr cast. pointer must be thin.
1050 match fcx.pointer_kind(m_cast.ty, self.span)? {
1051 None => Err(CastError::UnknownCastPtrKind),
1052 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1053 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
1054 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
1056 PointerKind::OfProjection(_)
1057 | PointerKind::OfOpaque(_, _)
1058 | PointerKind::OfParam(_),
1059 ) => Err(CastError::IntToFatCast(None)),
1063 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1064 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1066 Err(err) => Err(err),
1070 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1071 if let ty::Adt(d, _) = self.expr_ty.kind()
1072 && d.has_dtor(fcx.tcx)
1074 fcx.tcx.struct_span_lint_hir(
1075 lint::builtin::CENUM_IMPL_DROP_CAST,
1080 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1081 self.expr_ty, self.cast_ty
1089 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1090 fcx.tcx.struct_span_lint_hir(
1091 lint::builtin::LOSSY_PROVENANCE_CASTS,
1095 let mut err = err.build(&format!(
1096 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1097 self.expr_ty, self.cast_ty
1100 let msg = "use `.addr()` to obtain the address of a pointer";
1102 let expr_prec = self.expr.precedence().order();
1103 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1105 let scalar_cast = match t_c {
1106 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1107 _ => format!(" as {}", self.cast_ty),
1110 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1113 let suggestions = vec![
1114 (self.expr_span.shrink_to_lo(), String::from("(")),
1115 (cast_span, format!(").addr(){scalar_cast}")),
1118 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1120 err.span_suggestion(
1123 format!(".addr(){scalar_cast}"),
1124 Applicability::MaybeIncorrect,
1129 "if you can't comply with strict provenance and need to expose the pointer \
1130 provenance you can use `.expose_addr()` instead"
1138 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1139 fcx.tcx.struct_span_lint_hir(
1140 lint::builtin::FUZZY_PROVENANCE_CASTS,
1144 let mut err = err.build(&format!(
1145 "strict provenance disallows casting integer `{}` to pointer `{}`",
1146 self.expr_ty, self.cast_ty
1148 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1149 let suggestions = vec![
1150 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1151 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1154 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1156 "if you can't comply with strict provenance and don't have a pointer with \
1157 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"