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, DelayDm, DiagnosticBuilder, ErrorGuaranteed};
38 use rustc_middle::mir::Mutability;
39 use rustc_middle::ty::adjustment::AllowTwoPhase;
40 use rustc_middle::ty::cast::{CastKind, CastTy};
41 use rustc_middle::ty::error::TypeError;
42 use rustc_middle::ty::subst::SubstsRef;
43 use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitable, VariantDef};
44 use rustc_session::lint;
45 use rustc_session::Session;
46 use rustc_span::symbol::sym;
48 use rustc_trait_selection::infer::InferCtxtExt;
49 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
51 /// Reifies a cast check to be checked once we have full type information for
52 /// a function context.
54 pub struct CastCheck<'tcx> {
55 /// The expression whose value is being casted
56 expr: &'tcx hir::Expr<'tcx>,
57 /// The source type for the cast expression
60 /// The target type. That is, the type we are casting to.
66 /// The kind of pointer and associated metadata (thin, length or vtable) - we
67 /// only allow casts between fat pointers if their metadata have the same
69 #[derive(Copy, Clone, PartialEq, Eq)]
70 enum PointerKind<'tcx> {
71 /// No metadata attached, ie pointer to sized type or foreign type
74 VTable(Option<DefId>),
77 /// The unsize info of this projection
78 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
79 /// The unsize info of this opaque ty
80 OfOpaque(DefId, SubstsRef<'tcx>),
81 /// The unsize info of this parameter
82 OfParam(&'tcx ty::ParamTy),
85 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
86 /// Returns the kind of unsize information of t, or None
92 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
93 debug!("pointer_kind({:?}, {:?})", t, span);
95 let t = self.resolve_vars_if_possible(t);
97 if let Some(reported) = t.error_reported() {
101 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
102 return Ok(Some(PointerKind::Thin));
106 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
107 ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
108 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
109 None => Some(PointerKind::Thin),
111 let field_ty = self.field_ty(span, f, substs);
112 self.pointer_kind(field_ty, span)?
115 ty::Tuple(fields) => match fields.last() {
116 None => Some(PointerKind::Thin),
117 Some(&f) => self.pointer_kind(f, span)?,
120 // Pointers to foreign types are thin, despite being unsized
121 ty::Foreign(..) => Some(PointerKind::Thin),
122 // We should really try to normalize here.
123 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
124 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
125 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
126 // Insufficient type information.
127 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
135 | ty::GeneratorWitness(..)
144 | ty::Dynamic(_, _, ty::DynStar)
149 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
150 return Err(reported);
156 #[derive(Copy, Clone)]
163 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
173 /// Cast of int to (possibly) fat raw pointer.
175 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
176 /// or "a length". If this argument is None, then the metadata is unknown, for example,
177 /// when we're typechecking a type parameter with a ?Sized bound.
178 IntToFatCast(Option<&'static str>),
179 ForeignNonExhaustiveAdt,
182 impl From<ErrorGuaranteed> for CastError {
183 fn from(_: ErrorGuaranteed) -> Self {
184 CastError::ErrorGuaranteed
188 fn make_invalid_casting_error<'a, 'tcx>(
193 fcx: &FnCtxt<'a, 'tcx>,
194 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
200 "casting `{}` as `{}` is invalid",
201 fcx.ty_to_string(expr_ty),
202 fcx.ty_to_string(cast_ty)
206 impl<'a, 'tcx> CastCheck<'tcx> {
208 fcx: &FnCtxt<'a, 'tcx>,
209 expr: &'tcx hir::Expr<'tcx>,
214 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
215 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
216 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
218 // For better error messages, check for some obviously unsized
219 // cases now. We do a more thorough check at the end, once
220 // inference is more completely known.
221 match cast_ty.kind() {
222 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
223 let reported = check.report_cast_to_unsized_type(fcx);
230 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
232 CastError::ErrorGuaranteed => {
233 // an error has already been reported
235 CastError::NeedDeref => {
236 let error_span = self.span;
237 let mut err = make_invalid_casting_error(
244 let cast_ty = fcx.ty_to_string(self.cast_ty);
247 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
249 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
252 "dereference the expression",
253 format!("*{}", snippet),
254 Applicability::MaybeIncorrect,
257 err.span_help(self.expr_span, "dereference the expression with `*`");
261 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
262 let mut err = make_invalid_casting_error(
269 if self.cast_ty.is_integral() {
271 "cast through {} first",
273 CastError::NeedViaPtr => "a raw pointer",
274 CastError::NeedViaThinPtr => "a thin pointer",
281 CastError::NeedViaInt => {
282 make_invalid_casting_error(
290 "cast through {} first",
292 CastError::NeedViaInt => "an integer",
298 CastError::IllegalCast => {
299 make_invalid_casting_error(
308 CastError::DifferingKinds => {
309 make_invalid_casting_error(
316 .note("vtable kinds may not match")
319 CastError::CastToBool => {
321 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
323 if self.expr_ty.is_numeric() {
324 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
328 "compare with zero instead",
329 format!("{snippet} != 0"),
330 Applicability::MachineApplicable,
334 err.span_help(self.span, "compare with zero instead");
338 err.span_label(self.span, "unsupported cast");
343 CastError::CastToChar => {
344 let mut err = type_error_struct!(
349 "only `u8` can be cast as `char`, not `{}`",
352 err.span_label(self.span, "invalid cast");
353 if self.expr_ty.is_numeric() {
354 if self.expr_ty == fcx.tcx.types.u32 {
355 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
356 Ok(snippet) => err.span_suggestion(
358 "try `char::from_u32` instead",
359 format!("char::from_u32({snippet})"),
360 Applicability::MachineApplicable,
363 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
365 } else if self.expr_ty == fcx.tcx.types.i8 {
366 err.span_help(self.span, "try casting from `u8` instead");
368 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
373 CastError::NonScalar => {
374 let mut err = type_error_struct!(
379 "non-primitive cast: `{}` as `{}`",
381 fcx.ty_to_string(self.cast_ty)
384 let mut sugg_mutref = false;
385 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
386 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
391 fcx.tcx.lifetimes.re_erased,
392 TypeAndMut { ty: expr_ty, mutbl },
400 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
401 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
402 && expr_mutbl == Mutability::Not
403 && mutbl == Mutability::Mut
409 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
425 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
432 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
434 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
439 fcx.tcx.lifetimes.re_erased,
440 TypeAndMut { ty: self.expr_ty, mutbl },
448 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
451 err.span_label(self.span, "invalid cast");
452 err.span_note(self.expr_span, "this reference is immutable");
453 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
454 } else if let Some((sugg, remove_cast)) = sugg {
455 err.span_label(self.span, "invalid cast");
461 .span_to_snippet(self.expr_span)
462 .map_or(false, |snip| snip.starts_with('('));
464 // Very crude check to see whether the expression must be wrapped
465 // in parentheses for the suggestion to work (issue #89497).
466 // Can/should be extended in the future.
468 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
470 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
472 suggestion[0].1 += "(";
473 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
477 self.expr_span.shrink_to_hi().to(self.cast_span),
482 err.multipart_suggestion_verbose(
483 "consider borrowing the value",
485 Applicability::MachineApplicable,
489 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
491 let mut label = true;
492 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
493 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
494 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
496 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
497 // Erase regions to avoid panic in `prove_value` when calling
498 // `type_implements_trait`.
499 let ty = fcx.tcx.erase_regions(ty);
500 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
501 let expr_ty = fcx.tcx.erase_regions(expr_ty);
502 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
505 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
506 .must_apply_modulo_regions()
511 "consider using the `From` trait instead",
512 format!("{}::from({})", self.cast_ty, snippet),
513 Applicability::MaybeIncorrect,
517 let msg = "an `as` expression can only be used to convert between primitive \
518 types or to coerce to a specific trait object";
520 err.span_label(self.span, msg);
525 err.span_label(self.span, "invalid cast");
529 CastError::SizedUnsizedCast => {
530 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
535 expr_ty: self.expr_ty,
536 cast_ty: fcx.ty_to_string(self.cast_ty),
541 CastError::IntToFatCast(known_metadata) => {
542 let mut err = struct_span_err!(
546 "cannot cast `{}` to a pointer that {} wide",
547 fcx.ty_to_string(self.expr_ty),
548 if known_metadata.is_some() { "is" } else { "may be" }
554 "creating a `{}` requires both an address and {}",
556 known_metadata.unwrap_or("type-specific metadata"),
560 if fcx.tcx.sess.is_nightly_build() {
563 "consider casting this expression to `*const ()`, \
564 then using `core::ptr::from_raw_parts`",
570 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
571 let unknown_cast_to = match e {
572 CastError::UnknownCastPtrKind => true,
573 CastError::UnknownExprPtrKind => false,
576 let mut err = struct_span_err!(
578 if unknown_cast_to { self.cast_span } else { self.span },
580 "cannot cast {} a pointer of an unknown kind",
581 if unknown_cast_to { "to" } else { "from" }
584 err.span_label(self.cast_span, "needs more type information");
586 "the type information given here is insufficient to check whether \
587 the pointer cast is valid",
592 "the type information given here is insufficient to check whether \
593 the pointer cast is valid",
598 CastError::ForeignNonExhaustiveAdt => {
599 make_invalid_casting_error(
606 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
612 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
613 if let Some(reported) =
614 self.cast_ty.error_reported().or_else(|| self.expr_ty.error_reported())
619 let tstr = fcx.ty_to_string(self.cast_ty);
620 let mut err = type_error_struct!(
625 "cast to unsized type: `{}` as `{}`",
626 fcx.resolve_vars_if_possible(self.expr_ty),
629 match self.expr_ty.kind() {
630 ty::Ref(_, _, mt) => {
631 let mtstr = mt.prefix_str();
632 if self.cast_ty.is_trait() {
633 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
637 "try casting to a reference instead",
638 format!("&{}{}", mtstr, s),
639 Applicability::MachineApplicable,
643 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
644 err.span_help(self.cast_span, msg);
649 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
650 err.span_help(self.span, msg);
653 ty::Adt(def, ..) if def.is_box() => {
654 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
658 "you can cast to a `Box` instead",
660 Applicability::MachineApplicable,
666 &format!("you might have meant `Box<{tstr}>`"),
672 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
678 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
679 let t_cast = self.cast_ty;
680 let t_expr = self.expr_ty;
682 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
683 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
684 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
686 ("", lint::builtin::TRIVIAL_CASTS)
688 fcx.tcx.struct_span_lint_hir(
694 "trivial {}cast: `{}` as `{}`",
696 fcx.ty_to_string(t_expr),
697 fcx.ty_to_string(t_cast)
702 "cast can be replaced by coercion; this might \
703 require {type_asc_or}a temporary variable"
709 #[instrument(skip(fcx), level = "debug")]
710 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
711 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
712 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
714 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
716 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
717 && !self.cast_ty.has_infer_types()
719 self.report_cast_to_unsized_type(fcx);
720 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
721 // No sense in giving duplicate error messages
723 match self.try_coercion_cast(fcx) {
725 self.trivial_cast_lint(fcx);
726 debug!(" -> CoercionCast");
727 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
729 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
730 self.report_object_unsafe_cast(&fcx, did);
733 match self.do_check(fcx) {
735 debug!(" -> {:?}", k);
737 Err(e) => self.report_cast_error(fcx, e),
744 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
745 let violations = fcx.tcx.object_safety_violations(did);
746 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
747 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
751 /// Checks a cast, and report an error if one exists. In some cases, this
752 /// can return Ok and create type errors in the fcx rather than returning
753 /// directly. coercion-cast is handled in check instead of here.
754 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
755 use rustc_middle::ty::cast::CastTy::*;
756 use rustc_middle::ty::cast::IntTy::*;
758 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
760 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
761 // Function item types may need to be reified before casts.
762 (None, Some(t_cast)) => {
763 match *self.expr_ty.kind() {
765 // Attempt a coercion to a fn pointer type.
766 let f = fcx.normalize_associated_types_in(
768 self.expr_ty.fn_sig(fcx.tcx),
770 let res = fcx.try_coerce(
773 fcx.tcx.mk_fn_ptr(f),
777 if let Err(TypeError::IntrinsicCast) = res {
778 return Err(CastError::IllegalCast);
781 return Err(CastError::NonScalar);
785 // Special case some errors for references, and check for
786 // array-ptr-casts. `Ref` is not a CastTy because the cast
787 // is split into a coercion to a pointer type, followed by
789 ty::Ref(_, inner_ty, mutbl) => {
790 return match t_cast {
791 Int(_) | Float => match *inner_ty.kind() {
795 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
796 Err(CastError::NeedDeref)
798 _ => Err(CastError::NeedViaPtr),
802 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
804 _ => Err(CastError::NonScalar),
807 _ => return Err(CastError::NonScalar),
810 _ => return Err(CastError::NonScalar),
813 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
814 if adt_def.did().krate != LOCAL_CRATE {
815 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
816 return Err(CastError::ForeignNonExhaustiveAdt);
821 match (t_from, t_cast) {
822 // These types have invariants! can't cast into them.
823 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
826 (_, Int(Bool)) => Err(CastError::CastToBool),
829 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
830 (_, Int(Char)) => Err(CastError::CastToChar),
833 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
835 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
836 Err(CastError::IllegalCast)
840 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
843 (Ptr(m_expr), Int(t_c)) => {
844 self.lossy_provenance_ptr2int_lint(fcx, t_c);
845 self.check_ptr_addr_cast(fcx, m_expr)
848 // FIXME(#95489): there should eventually be a lint for these casts
849 Ok(CastKind::FnPtrAddrCast)
852 (Int(_), Ptr(mt)) => {
853 self.fuzzy_provenance_int2ptr_lint(fcx);
854 self.check_addr_ptr_cast(fcx, mt)
857 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
860 (Int(CEnum), Int(_)) => {
861 self.cenum_impl_drop_lint(fcx);
862 Ok(CastKind::EnumCast)
864 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
866 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
868 (_, DynStar) | (DynStar, _) => bug!("should be handled by `try_coerce`"),
872 fn check_ptr_ptr_cast(
874 fcx: &FnCtxt<'a, 'tcx>,
875 m_expr: ty::TypeAndMut<'tcx>,
876 m_cast: ty::TypeAndMut<'tcx>,
877 ) -> Result<CastKind, CastError> {
878 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
879 // ptr-ptr cast. vtables must match.
881 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
882 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
884 let Some(cast_kind) = cast_kind else {
885 // We can't cast if target pointer kind is unknown
886 return Err(CastError::UnknownCastPtrKind);
889 // Cast to thin pointer is OK
890 if cast_kind == PointerKind::Thin {
891 return Ok(CastKind::PtrPtrCast);
894 let Some(expr_kind) = expr_kind else {
895 // We can't cast to fat pointer if source pointer kind is unknown
896 return Err(CastError::UnknownExprPtrKind);
899 // thin -> fat? report invalid cast (don't complain about vtable kinds)
900 if expr_kind == PointerKind::Thin {
901 return Err(CastError::SizedUnsizedCast);
904 // vtable kinds must match
905 if cast_kind == expr_kind {
906 Ok(CastKind::PtrPtrCast)
908 Err(CastError::DifferingKinds)
912 fn check_fptr_ptr_cast(
914 fcx: &FnCtxt<'a, 'tcx>,
915 m_cast: ty::TypeAndMut<'tcx>,
916 ) -> Result<CastKind, CastError> {
917 // fptr-ptr cast. must be to thin ptr
919 match fcx.pointer_kind(m_cast.ty, self.span)? {
920 None => Err(CastError::UnknownCastPtrKind),
921 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
922 _ => Err(CastError::IllegalCast),
926 fn check_ptr_addr_cast(
928 fcx: &FnCtxt<'a, 'tcx>,
929 m_expr: ty::TypeAndMut<'tcx>,
930 ) -> Result<CastKind, CastError> {
931 // ptr-addr cast. must be from thin ptr
933 match fcx.pointer_kind(m_expr.ty, self.span)? {
934 None => Err(CastError::UnknownExprPtrKind),
935 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
936 _ => Err(CastError::NeedViaThinPtr),
942 fcx: &FnCtxt<'a, 'tcx>,
943 m_expr: ty::TypeAndMut<'tcx>,
944 m_cast: ty::TypeAndMut<'tcx>,
945 ) -> Result<CastKind, CastError> {
946 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
947 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
948 if let ty::Array(ety, _) = m_expr.ty.kind() {
949 // Due to the limitations of LLVM global constants,
950 // region pointers end up pointing at copies of
951 // vector elements instead of the original values.
952 // To allow raw pointers to work correctly, we
953 // need to special-case obtaining a raw pointer
954 // from a region pointer to a vector.
956 // Coerce to a raw pointer so that we generate AddressOf in MIR.
957 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
958 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
959 .unwrap_or_else(|_| {
961 "could not cast from reference to array to pointer to array ({:?} to {:?})",
967 // this will report a type mismatch if needed
968 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
969 return Ok(CastKind::ArrayPtrCast);
973 Err(CastError::IllegalCast)
976 fn check_addr_ptr_cast(
978 fcx: &FnCtxt<'a, 'tcx>,
979 m_cast: TypeAndMut<'tcx>,
980 ) -> Result<CastKind, CastError> {
981 // ptr-addr cast. pointer must be thin.
982 match fcx.pointer_kind(m_cast.ty, self.span)? {
983 None => Err(CastError::UnknownCastPtrKind),
984 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
985 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
986 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
988 PointerKind::OfProjection(_)
989 | PointerKind::OfOpaque(_, _)
990 | PointerKind::OfParam(_),
991 ) => Err(CastError::IntToFatCast(None)),
995 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
996 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
998 Err(err) => Err(err),
1002 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1003 if let ty::Adt(d, _) = self.expr_ty.kind()
1004 && d.has_dtor(fcx.tcx)
1006 fcx.tcx.struct_span_lint_hir(
1007 lint::builtin::CENUM_IMPL_DROP_CAST,
1011 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1012 self.expr_ty, self.cast_ty
1021 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1022 fcx.tcx.struct_span_lint_hir(
1023 lint::builtin::LOSSY_PROVENANCE_CASTS,
1027 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1028 self.expr_ty, self.cast_ty
1031 let msg = "use `.addr()` to obtain the address of a pointer";
1033 let expr_prec = self.expr.precedence().order();
1034 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1036 let scalar_cast = match t_c {
1037 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1038 _ => format!(" as {}", self.cast_ty),
1041 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1044 let suggestions = vec![
1045 (self.expr_span.shrink_to_lo(), String::from("(")),
1046 (cast_span, format!(").addr(){scalar_cast}")),
1049 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1051 lint.span_suggestion(
1054 format!(".addr(){scalar_cast}"),
1055 Applicability::MaybeIncorrect,
1060 "if you can't comply with strict provenance and need to expose the pointer \
1061 provenance you can use `.expose_addr()` instead"
1069 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1070 fcx.tcx.struct_span_lint_hir(
1071 lint::builtin::FUZZY_PROVENANCE_CASTS,
1075 "strict provenance disallows casting integer `{}` to pointer `{}`",
1076 self.expr_ty, self.cast_ty
1079 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1080 let suggestions = vec![
1081 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1082 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1085 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1087 "if you can't comply with strict provenance and don't have a pointer with \
1088 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"