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::type_error_struct;
34 use rustc_errors::{struct_span_err, Applicability, DelayDm, DiagnosticBuilder, ErrorGuaranteed};
36 use rustc_middle::mir::Mutability;
37 use rustc_middle::ty::adjustment::AllowTwoPhase;
38 use rustc_middle::ty::cast::{CastKind, CastTy};
39 use rustc_middle::ty::error::TypeError;
40 use rustc_middle::ty::subst::SubstsRef;
41 use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitable, VariantDef};
42 use rustc_session::lint;
43 use rustc_session::Session;
44 use rustc_span::def_id::{DefId, LOCAL_CRATE};
45 use rustc_span::symbol::sym;
47 use rustc_trait_selection::infer::InferCtxtExt;
48 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
50 /// Reifies a cast check to be checked once we have full type information for
51 /// a function context.
53 pub struct CastCheck<'tcx> {
54 /// The expression whose value is being casted
55 expr: &'tcx hir::Expr<'tcx>,
56 /// The source type for the cast expression
59 /// The target type. That is, the type we are casting to.
65 /// The kind of pointer and associated metadata (thin, length or vtable) - we
66 /// only allow casts between fat pointers if their metadata have the same
68 #[derive(Copy, Clone, PartialEq, Eq)]
69 enum PointerKind<'tcx> {
70 /// No metadata attached, ie pointer to sized type or foreign type
73 VTable(Option<DefId>),
76 /// The unsize info of this projection
77 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
78 /// The unsize info of this opaque ty
79 OfOpaque(DefId, SubstsRef<'tcx>),
80 /// The unsize info of this parameter
81 OfParam(&'tcx ty::ParamTy),
84 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
85 /// Returns the kind of unsize information of t, or None
91 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
92 debug!("pointer_kind({:?}, {:?})", t, span);
94 let t = self.resolve_vars_if_possible(t);
97 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
98 return Ok(Some(PointerKind::Thin));
102 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
103 ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
104 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
105 None => Some(PointerKind::Thin),
107 let field_ty = self.field_ty(span, f, substs);
108 self.pointer_kind(field_ty, span)?
111 ty::Tuple(fields) => match fields.last() {
112 None => Some(PointerKind::Thin),
113 Some(&f) => self.pointer_kind(f, span)?,
116 // Pointers to foreign types are thin, despite being unsized
117 ty::Foreign(..) => Some(PointerKind::Thin),
118 // We should really try to normalize here.
119 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
120 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
121 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
122 // Insufficient type information.
123 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
131 | ty::GeneratorWitness(..)
140 | ty::Dynamic(_, _, ty::DynStar)
145 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
146 return Err(reported);
152 #[derive(Copy, Clone)]
159 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
169 /// Cast of int to (possibly) fat raw pointer.
171 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
172 /// or "a length". If this argument is None, then the metadata is unknown, for example,
173 /// when we're typechecking a type parameter with a ?Sized bound.
174 IntToFatCast(Option<&'static str>),
175 ForeignNonExhaustiveAdt,
178 impl From<ErrorGuaranteed> for CastError {
179 fn from(_: ErrorGuaranteed) -> Self {
180 CastError::ErrorGuaranteed
184 fn make_invalid_casting_error<'a, 'tcx>(
189 fcx: &FnCtxt<'a, 'tcx>,
190 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
196 "casting `{}` as `{}` is invalid",
197 fcx.ty_to_string(expr_ty),
198 fcx.ty_to_string(cast_ty)
202 impl<'a, 'tcx> CastCheck<'tcx> {
204 fcx: &FnCtxt<'a, 'tcx>,
205 expr: &'tcx hir::Expr<'tcx>,
210 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
211 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
212 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
214 // For better error messages, check for some obviously unsized
215 // cases now. We do a more thorough check at the end, once
216 // inference is more completely known.
217 match cast_ty.kind() {
218 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
219 Err(check.report_cast_to_unsized_type(fcx))
225 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
227 CastError::ErrorGuaranteed => {
228 // an error has already been reported
230 CastError::NeedDeref => {
231 let error_span = self.span;
232 let mut err = make_invalid_casting_error(
239 let cast_ty = fcx.ty_to_string(self.cast_ty);
242 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
244 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
247 "dereference the expression",
248 format!("*{}", snippet),
249 Applicability::MaybeIncorrect,
252 err.span_help(self.expr_span, "dereference the expression with `*`");
256 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
257 let mut err = make_invalid_casting_error(
264 if self.cast_ty.is_integral() {
266 "cast through {} first",
268 CastError::NeedViaPtr => "a raw pointer",
269 CastError::NeedViaThinPtr => "a thin pointer",
276 CastError::NeedViaInt => {
277 make_invalid_casting_error(
285 "cast through {} first",
287 CastError::NeedViaInt => "an integer",
293 CastError::IllegalCast => {
294 make_invalid_casting_error(
303 CastError::DifferingKinds => {
304 make_invalid_casting_error(
311 .note("vtable kinds may not match")
314 CastError::CastToBool => {
316 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
318 if self.expr_ty.is_numeric() {
319 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
323 "compare with zero instead",
324 format!("{snippet} != 0"),
325 Applicability::MachineApplicable,
329 err.span_help(self.span, "compare with zero instead");
333 err.span_label(self.span, "unsupported cast");
338 CastError::CastToChar => {
339 let mut err = type_error_struct!(
344 "only `u8` can be cast as `char`, not `{}`",
347 err.span_label(self.span, "invalid cast");
348 if self.expr_ty.is_numeric() {
349 if self.expr_ty == fcx.tcx.types.u32 {
350 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
351 Ok(snippet) => err.span_suggestion(
353 "try `char::from_u32` instead",
354 format!("char::from_u32({snippet})"),
355 Applicability::MachineApplicable,
358 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
360 } else if self.expr_ty == fcx.tcx.types.i8 {
361 err.span_help(self.span, "try casting from `u8` instead");
363 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
368 CastError::NonScalar => {
369 let mut err = type_error_struct!(
374 "non-primitive cast: `{}` as `{}`",
376 fcx.ty_to_string(self.cast_ty)
379 let mut sugg_mutref = false;
380 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
381 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
386 fcx.tcx.lifetimes.re_erased,
387 TypeAndMut { ty: expr_ty, mutbl },
395 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
396 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
397 && expr_mutbl == Mutability::Not
398 && mutbl == Mutability::Mut
404 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
420 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
427 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
429 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
434 fcx.tcx.lifetimes.re_erased,
435 TypeAndMut { ty: self.expr_ty, mutbl },
443 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
446 err.span_label(self.span, "invalid cast");
447 err.span_note(self.expr_span, "this reference is immutable");
448 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
449 } else if let Some((sugg, remove_cast)) = sugg {
450 err.span_label(self.span, "invalid cast");
456 .span_to_snippet(self.expr_span)
457 .map_or(false, |snip| snip.starts_with('('));
459 // Very crude check to see whether the expression must be wrapped
460 // in parentheses for the suggestion to work (issue #89497).
461 // Can/should be extended in the future.
463 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
465 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
467 suggestion[0].1 += "(";
468 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
472 self.expr_span.shrink_to_hi().to(self.cast_span),
477 err.multipart_suggestion_verbose(
478 "consider borrowing the value",
480 Applicability::MachineApplicable,
484 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
486 let mut label = true;
487 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
488 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
489 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
491 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
492 // Erase regions to avoid panic in `prove_value` when calling
493 // `type_implements_trait`.
494 let ty = fcx.tcx.erase_regions(ty);
495 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
496 let expr_ty = fcx.tcx.erase_regions(expr_ty);
497 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
500 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
501 .must_apply_modulo_regions()
506 "consider using the `From` trait instead",
507 format!("{}::from({})", self.cast_ty, snippet),
508 Applicability::MaybeIncorrect,
512 let msg = "an `as` expression can only be used to convert between primitive \
513 types or to coerce to a specific trait object";
515 err.span_label(self.span, msg);
520 err.span_label(self.span, "invalid cast");
524 CastError::SizedUnsizedCast => {
525 use rustc_hir_analysis::structured_errors::{
526 SizedUnsizedCast, StructuredDiagnostic,
532 expr_ty: self.expr_ty,
533 cast_ty: fcx.ty_to_string(self.cast_ty),
538 CastError::IntToFatCast(known_metadata) => {
539 let mut err = struct_span_err!(
543 "cannot cast `{}` to a pointer that {} wide",
544 fcx.ty_to_string(self.expr_ty),
545 if known_metadata.is_some() { "is" } else { "may be" }
551 "creating a `{}` requires both an address and {}",
553 known_metadata.unwrap_or("type-specific metadata"),
557 if fcx.tcx.sess.is_nightly_build() {
560 "consider casting this expression to `*const ()`, \
561 then using `core::ptr::from_raw_parts`",
567 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
568 let unknown_cast_to = match e {
569 CastError::UnknownCastPtrKind => true,
570 CastError::UnknownExprPtrKind => false,
573 let mut err = struct_span_err!(
575 if unknown_cast_to { self.cast_span } else { self.span },
577 "cannot cast {} a pointer of an unknown kind",
578 if unknown_cast_to { "to" } else { "from" }
581 err.span_label(self.cast_span, "needs more type information");
583 "the type information given here is insufficient to check whether \
584 the pointer cast is valid",
589 "the type information given here is insufficient to check whether \
590 the pointer cast is valid",
595 CastError::ForeignNonExhaustiveAdt => {
596 make_invalid_casting_error(
603 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
609 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
610 if let Err(err) = self.cast_ty.error_reported() {
613 if let Err(err) = self.expr_ty.error_reported() {
617 let tstr = fcx.ty_to_string(self.cast_ty);
618 let mut err = type_error_struct!(
623 "cast to unsized type: `{}` as `{}`",
624 fcx.resolve_vars_if_possible(self.expr_ty),
627 match self.expr_ty.kind() {
628 ty::Ref(_, _, mt) => {
629 let mtstr = mt.prefix_str();
630 if self.cast_ty.is_trait() {
631 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
635 "try casting to a reference instead",
636 format!("&{}{}", mtstr, s),
637 Applicability::MachineApplicable,
641 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
642 err.span_help(self.cast_span, msg);
647 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
648 err.span_help(self.span, msg);
651 ty::Adt(def, ..) if def.is_box() => {
652 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
656 "you can cast to a `Box` instead",
658 Applicability::MachineApplicable,
664 &format!("you might have meant `Box<{tstr}>`"),
670 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
676 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
677 let t_cast = self.cast_ty;
678 let t_expr = self.expr_ty;
680 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
681 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
682 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
684 ("", lint::builtin::TRIVIAL_CASTS)
686 fcx.tcx.struct_span_lint_hir(
692 "trivial {}cast: `{}` as `{}`",
694 fcx.ty_to_string(t_expr),
695 fcx.ty_to_string(t_cast)
700 "cast can be replaced by coercion; this might \
701 require {type_asc_or}a temporary variable"
707 #[instrument(skip(fcx), level = "debug")]
708 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
709 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
710 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
712 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
714 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
715 && !self.cast_ty.has_infer_types()
717 self.report_cast_to_unsized_type(fcx);
718 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
719 // No sense in giving duplicate error messages
721 match self.try_coercion_cast(fcx) {
723 self.trivial_cast_lint(fcx);
724 debug!(" -> CoercionCast");
725 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
727 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
728 self.report_object_unsafe_cast(&fcx, did);
731 match self.do_check(fcx) {
733 debug!(" -> {:?}", k);
735 Err(e) => self.report_cast_error(fcx, e),
742 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
743 let violations = fcx.tcx.object_safety_violations(did);
744 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
745 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
749 /// Checks a cast, and report an error if one exists. In some cases, this
750 /// can return Ok and create type errors in the fcx rather than returning
751 /// directly. coercion-cast is handled in check instead of here.
752 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
753 use rustc_middle::ty::cast::CastTy::*;
754 use rustc_middle::ty::cast::IntTy::*;
756 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
758 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
759 // Function item types may need to be reified before casts.
760 (None, Some(t_cast)) => {
761 match *self.expr_ty.kind() {
763 // Attempt a coercion to a fn pointer type.
764 let f = fcx.normalize_associated_types_in(
766 self.expr_ty.fn_sig(fcx.tcx),
768 let res = fcx.try_coerce(
771 fcx.tcx.mk_fn_ptr(f),
775 if let Err(TypeError::IntrinsicCast) = res {
776 return Err(CastError::IllegalCast);
779 return Err(CastError::NonScalar);
783 // Special case some errors for references, and check for
784 // array-ptr-casts. `Ref` is not a CastTy because the cast
785 // is split into a coercion to a pointer type, followed by
787 ty::Ref(_, inner_ty, mutbl) => {
788 return match t_cast {
789 Int(_) | Float => match *inner_ty.kind() {
793 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
794 Err(CastError::NeedDeref)
796 _ => Err(CastError::NeedViaPtr),
800 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
802 _ => Err(CastError::NonScalar),
805 _ => return Err(CastError::NonScalar),
808 _ => return Err(CastError::NonScalar),
811 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
812 if adt_def.did().krate != LOCAL_CRATE {
813 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
814 return Err(CastError::ForeignNonExhaustiveAdt);
819 match (t_from, t_cast) {
820 // These types have invariants! can't cast into them.
821 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
824 (_, Int(Bool)) => Err(CastError::CastToBool),
827 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
828 (_, Int(Char)) => Err(CastError::CastToChar),
831 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
833 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
834 Err(CastError::IllegalCast)
838 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
841 (Ptr(m_expr), Int(t_c)) => {
842 self.lossy_provenance_ptr2int_lint(fcx, t_c);
843 self.check_ptr_addr_cast(fcx, m_expr)
846 // FIXME(#95489): there should eventually be a lint for these casts
847 Ok(CastKind::FnPtrAddrCast)
850 (Int(_), Ptr(mt)) => {
851 self.fuzzy_provenance_int2ptr_lint(fcx);
852 self.check_addr_ptr_cast(fcx, mt)
855 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
858 (Int(CEnum), Int(_)) => {
859 self.cenum_impl_drop_lint(fcx);
860 Ok(CastKind::EnumCast)
862 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
864 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
866 (_, DynStar) | (DynStar, _) => bug!("should be handled by `try_coerce`"),
870 fn check_ptr_ptr_cast(
872 fcx: &FnCtxt<'a, 'tcx>,
873 m_expr: ty::TypeAndMut<'tcx>,
874 m_cast: ty::TypeAndMut<'tcx>,
875 ) -> Result<CastKind, CastError> {
876 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
877 // ptr-ptr cast. vtables must match.
879 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
880 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
882 let Some(cast_kind) = cast_kind else {
883 // We can't cast if target pointer kind is unknown
884 return Err(CastError::UnknownCastPtrKind);
887 // Cast to thin pointer is OK
888 if cast_kind == PointerKind::Thin {
889 return Ok(CastKind::PtrPtrCast);
892 let Some(expr_kind) = expr_kind else {
893 // We can't cast to fat pointer if source pointer kind is unknown
894 return Err(CastError::UnknownExprPtrKind);
897 // thin -> fat? report invalid cast (don't complain about vtable kinds)
898 if expr_kind == PointerKind::Thin {
899 return Err(CastError::SizedUnsizedCast);
902 // vtable kinds must match
903 if cast_kind == expr_kind {
904 Ok(CastKind::PtrPtrCast)
906 Err(CastError::DifferingKinds)
910 fn check_fptr_ptr_cast(
912 fcx: &FnCtxt<'a, 'tcx>,
913 m_cast: ty::TypeAndMut<'tcx>,
914 ) -> Result<CastKind, CastError> {
915 // fptr-ptr cast. must be to thin ptr
917 match fcx.pointer_kind(m_cast.ty, self.span)? {
918 None => Err(CastError::UnknownCastPtrKind),
919 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
920 _ => Err(CastError::IllegalCast),
924 fn check_ptr_addr_cast(
926 fcx: &FnCtxt<'a, 'tcx>,
927 m_expr: ty::TypeAndMut<'tcx>,
928 ) -> Result<CastKind, CastError> {
929 // ptr-addr cast. must be from thin ptr
931 match fcx.pointer_kind(m_expr.ty, self.span)? {
932 None => Err(CastError::UnknownExprPtrKind),
933 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
934 _ => Err(CastError::NeedViaThinPtr),
940 fcx: &FnCtxt<'a, 'tcx>,
941 m_expr: ty::TypeAndMut<'tcx>,
942 m_cast: ty::TypeAndMut<'tcx>,
943 ) -> Result<CastKind, CastError> {
944 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
945 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
946 if let ty::Array(ety, _) = m_expr.ty.kind() {
947 // Due to the limitations of LLVM global constants,
948 // region pointers end up pointing at copies of
949 // vector elements instead of the original values.
950 // To allow raw pointers to work correctly, we
951 // need to special-case obtaining a raw pointer
952 // from a region pointer to a vector.
954 // Coerce to a raw pointer so that we generate AddressOf in MIR.
955 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
956 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
957 .unwrap_or_else(|_| {
959 "could not cast from reference to array to pointer to array ({:?} to {:?})",
965 // this will report a type mismatch if needed
966 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
967 return Ok(CastKind::ArrayPtrCast);
971 Err(CastError::IllegalCast)
974 fn check_addr_ptr_cast(
976 fcx: &FnCtxt<'a, 'tcx>,
977 m_cast: TypeAndMut<'tcx>,
978 ) -> Result<CastKind, CastError> {
979 // ptr-addr cast. pointer must be thin.
980 match fcx.pointer_kind(m_cast.ty, self.span)? {
981 None => Err(CastError::UnknownCastPtrKind),
982 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
983 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
984 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
986 PointerKind::OfProjection(_)
987 | PointerKind::OfOpaque(_, _)
988 | PointerKind::OfParam(_),
989 ) => Err(CastError::IntToFatCast(None)),
993 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
994 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
996 Err(err) => Err(err),
1000 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1001 if let ty::Adt(d, _) = self.expr_ty.kind()
1002 && d.has_dtor(fcx.tcx)
1004 fcx.tcx.struct_span_lint_hir(
1005 lint::builtin::CENUM_IMPL_DROP_CAST,
1009 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1010 self.expr_ty, self.cast_ty
1019 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1020 fcx.tcx.struct_span_lint_hir(
1021 lint::builtin::LOSSY_PROVENANCE_CASTS,
1025 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1026 self.expr_ty, self.cast_ty
1029 let msg = "use `.addr()` to obtain the address of a pointer";
1031 let expr_prec = self.expr.precedence().order();
1032 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1034 let scalar_cast = match t_c {
1035 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1036 _ => format!(" as {}", self.cast_ty),
1039 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1042 let suggestions = vec![
1043 (self.expr_span.shrink_to_lo(), String::from("(")),
1044 (cast_span, format!(").addr(){scalar_cast}")),
1047 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1049 lint.span_suggestion(
1052 format!(".addr(){scalar_cast}"),
1053 Applicability::MaybeIncorrect,
1058 "if you can't comply with strict provenance and need to expose the pointer \
1059 provenance you can use `.expose_addr()` instead"
1067 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1068 fcx.tcx.struct_span_lint_hir(
1069 lint::builtin::FUZZY_PROVENANCE_CASTS,
1073 "strict provenance disallows casting integer `{}` to pointer `{}`",
1074 self.expr_ty, self.cast_ty
1077 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1078 let suggestions = vec![
1079 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1080 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1083 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1085 "if you can't comply with strict provenance and don't have a pointer with \
1086 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"