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_macros::{TypeFoldable, TypeVisitable};
37 use rustc_middle::mir::Mutability;
38 use rustc_middle::ty::adjustment::AllowTwoPhase;
39 use rustc_middle::ty::cast::{CastKind, CastTy};
40 use rustc_middle::ty::error::TypeError;
41 use rustc_middle::ty::subst::SubstsRef;
42 use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitable, VariantDef};
43 use rustc_session::lint;
44 use rustc_session::Session;
45 use rustc_span::def_id::{DefId, LOCAL_CRATE};
46 use rustc_span::symbol::sym;
48 use rustc_trait_selection::infer::InferCtxtExt;
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.
63 /// whether the cast is made in a const context or not.
64 pub constness: hir::Constness,
67 /// The kind of pointer and associated metadata (thin, length or vtable) - we
68 /// only allow casts between fat pointers if their metadata have the same
70 #[derive(Debug, Copy, Clone, PartialEq, Eq, TypeVisitable, TypeFoldable)]
71 enum PointerKind<'tcx> {
72 /// No metadata attached, ie pointer to sized type or foreign type
75 VTable(Option<DefId>),
78 /// The unsize info of this projection
79 OfProjection(ty::ProjectionTy<'tcx>),
80 /// The unsize info of this opaque ty
81 OfOpaque(DefId, SubstsRef<'tcx>),
82 /// The unsize info of this parameter
86 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
87 /// Returns the kind of unsize information of t, or None
93 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
94 debug!("pointer_kind({:?}, {:?})", t, span);
96 let t = self.resolve_vars_if_possible(t);
99 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
100 return Ok(Some(PointerKind::Thin));
104 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
105 ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
106 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
107 None => Some(PointerKind::Thin),
109 let field_ty = self.field_ty(span, f, substs);
110 self.pointer_kind(field_ty, span)?
113 ty::Tuple(fields) => match fields.last() {
114 None => Some(PointerKind::Thin),
115 Some(&f) => self.pointer_kind(f, span)?,
118 // Pointers to foreign types are thin, despite being unsized
119 ty::Foreign(..) => Some(PointerKind::Thin),
120 // We should really try to normalize here.
121 ty::Projection(pi) => Some(PointerKind::OfProjection(pi)),
122 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
123 ty::Param(p) => Some(PointerKind::OfParam(p)),
124 // Insufficient type information.
125 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
133 | ty::GeneratorWitness(..)
142 | ty::Dynamic(_, _, ty::DynStar)
147 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
148 return Err(reported);
154 #[derive(Copy, Clone)]
161 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
171 /// Cast of int to (possibly) fat raw pointer.
173 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
174 /// or "a length". If this argument is None, then the metadata is unknown, for example,
175 /// when we're typechecking a type parameter with a ?Sized bound.
176 IntToFatCast(Option<&'static str>),
177 ForeignNonExhaustiveAdt,
180 impl From<ErrorGuaranteed> for CastError {
181 fn from(_: ErrorGuaranteed) -> Self {
182 CastError::ErrorGuaranteed
186 fn make_invalid_casting_error<'a, 'tcx>(
191 fcx: &FnCtxt<'a, 'tcx>,
192 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
198 "casting `{}` as `{}` is invalid",
199 fcx.ty_to_string(expr_ty),
200 fcx.ty_to_string(cast_ty)
204 impl<'a, 'tcx> CastCheck<'tcx> {
206 fcx: &FnCtxt<'a, 'tcx>,
207 expr: &'tcx hir::Expr<'tcx>,
212 constness: hir::Constness,
213 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
214 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
215 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span, constness };
217 // For better error messages, check for some obviously unsized
218 // cases now. We do a more thorough check at the end, once
219 // inference is more completely known.
220 match cast_ty.kind() {
221 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
222 Err(check.report_cast_to_unsized_type(fcx))
228 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
230 CastError::ErrorGuaranteed => {
231 // an error has already been reported
233 CastError::NeedDeref => {
234 let error_span = self.span;
235 let mut err = make_invalid_casting_error(
242 let cast_ty = fcx.ty_to_string(self.cast_ty);
245 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
247 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
250 "dereference the expression",
251 format!("*{}", snippet),
252 Applicability::MaybeIncorrect,
255 err.span_help(self.expr_span, "dereference the expression with `*`");
259 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
260 let mut err = make_invalid_casting_error(
267 if self.cast_ty.is_integral() {
269 "cast through {} first",
271 CastError::NeedViaPtr => "a raw pointer",
272 CastError::NeedViaThinPtr => "a thin pointer",
279 CastError::NeedViaInt => {
280 make_invalid_casting_error(
288 "cast through {} first",
290 CastError::NeedViaInt => "an integer",
296 CastError::IllegalCast => {
297 make_invalid_casting_error(
306 CastError::DifferingKinds => {
307 make_invalid_casting_error(
314 .note("vtable kinds may not match")
317 CastError::CastToBool => {
319 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
321 if self.expr_ty.is_numeric() {
322 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
326 "compare with zero instead",
327 format!("{snippet} != 0"),
328 Applicability::MachineApplicable,
332 err.span_help(self.span, "compare with zero instead");
336 err.span_label(self.span, "unsupported cast");
341 CastError::CastToChar => {
342 let mut err = type_error_struct!(
347 "only `u8` can be cast as `char`, not `{}`",
350 err.span_label(self.span, "invalid cast");
351 if self.expr_ty.is_numeric() {
352 if self.expr_ty == fcx.tcx.types.u32 {
353 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
354 Ok(snippet) => err.span_suggestion(
356 "try `char::from_u32` instead",
357 format!("char::from_u32({snippet})"),
358 Applicability::MachineApplicable,
361 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
363 } else if self.expr_ty == fcx.tcx.types.i8 {
364 err.span_help(self.span, "try casting from `u8` instead");
366 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
371 CastError::NonScalar => {
372 let mut err = type_error_struct!(
377 "non-primitive cast: `{}` as `{}`",
379 fcx.ty_to_string(self.cast_ty)
382 let mut sugg_mutref = false;
383 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
384 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
389 fcx.tcx.lifetimes.re_erased,
390 TypeAndMut { ty: expr_ty, mutbl },
398 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
399 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
400 && expr_mutbl == Mutability::Not
401 && mutbl == Mutability::Mut
407 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
423 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
430 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
432 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
437 fcx.tcx.lifetimes.re_erased,
438 TypeAndMut { ty: self.expr_ty, mutbl },
446 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
449 err.span_label(self.span, "invalid cast");
450 err.span_note(self.expr_span, "this reference is immutable");
451 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
452 } else if let Some((sugg, remove_cast)) = sugg {
453 err.span_label(self.span, "invalid cast");
459 .span_to_snippet(self.expr_span)
460 .map_or(false, |snip| snip.starts_with('('));
462 // Very crude check to see whether the expression must be wrapped
463 // in parentheses for the suggestion to work (issue #89497).
464 // Can/should be extended in the future.
466 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
468 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
470 suggestion[0].1 += "(";
471 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
475 self.expr_span.shrink_to_hi().to(self.cast_span),
480 err.multipart_suggestion_verbose(
481 "consider borrowing the value",
483 Applicability::MachineApplicable,
487 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
489 let mut label = true;
490 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
491 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
492 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
494 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
495 // Erase regions to avoid panic in `prove_value` when calling
496 // `type_implements_trait`.
497 let ty = fcx.tcx.erase_regions(ty);
498 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
499 let expr_ty = fcx.tcx.erase_regions(expr_ty);
502 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
503 .must_apply_modulo_regions()
508 "consider using the `From` trait instead",
509 format!("{}::from({})", self.cast_ty, snippet),
510 Applicability::MaybeIncorrect,
514 let msg = "an `as` expression can only be used to convert between primitive \
515 types or to coerce to a specific trait object";
517 err.span_label(self.span, msg);
522 err.span_label(self.span, "invalid cast");
526 CastError::SizedUnsizedCast => {
527 use rustc_hir_analysis::structured_errors::{
528 SizedUnsizedCast, StructuredDiagnostic,
534 expr_ty: self.expr_ty,
535 cast_ty: fcx.ty_to_string(self.cast_ty),
540 CastError::IntToFatCast(known_metadata) => {
541 let mut err = struct_span_err!(
545 "cannot cast `{}` to a pointer that {} wide",
546 fcx.ty_to_string(self.expr_ty),
547 if known_metadata.is_some() { "is" } else { "may be" }
553 "creating a `{}` requires both an address and {}",
555 known_metadata.unwrap_or("type-specific metadata"),
559 if fcx.tcx.sess.is_nightly_build() {
562 "consider casting this expression to `*const ()`, \
563 then using `core::ptr::from_raw_parts`",
569 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
570 let unknown_cast_to = match e {
571 CastError::UnknownCastPtrKind => true,
572 CastError::UnknownExprPtrKind => false,
575 let mut err = struct_span_err!(
577 if unknown_cast_to { self.cast_span } else { self.span },
579 "cannot cast {} a pointer of an unknown kind",
580 if unknown_cast_to { "to" } else { "from" }
583 err.span_label(self.cast_span, "needs more type information");
585 "the type information given here is insufficient to check whether \
586 the pointer cast is valid",
591 "the type information given here is insufficient to check whether \
592 the pointer cast is valid",
597 CastError::ForeignNonExhaustiveAdt => {
598 make_invalid_casting_error(
605 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
611 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
612 if let Err(err) = self.cast_ty.error_reported() {
615 if let Err(err) = 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);
730 match self.do_check(fcx) {
732 debug!(" -> {:?}", k);
734 Err(e) => self.report_cast_error(fcx, e),
740 /// Checks a cast, and report an error if one exists. In some cases, this
741 /// can return Ok and create type errors in the fcx rather than returning
742 /// directly. coercion-cast is handled in check instead of here.
743 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
744 use rustc_middle::ty::cast::CastTy::*;
745 use rustc_middle::ty::cast::IntTy::*;
747 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
749 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
750 // Function item types may need to be reified before casts.
751 (None, Some(t_cast)) => {
752 match *self.expr_ty.kind() {
754 // Attempt a coercion to a fn pointer type.
755 let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
756 let res = fcx.try_coerce(
759 fcx.tcx.mk_fn_ptr(f),
763 if let Err(TypeError::IntrinsicCast) = res {
764 return Err(CastError::IllegalCast);
767 return Err(CastError::NonScalar);
771 // Special case some errors for references, and check for
772 // array-ptr-casts. `Ref` is not a CastTy because the cast
773 // is split into a coercion to a pointer type, followed by
775 ty::Ref(_, inner_ty, mutbl) => {
776 return match t_cast {
777 Int(_) | Float => match *inner_ty.kind() {
781 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
782 Err(CastError::NeedDeref)
784 _ => Err(CastError::NeedViaPtr),
788 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
790 _ => Err(CastError::NonScalar),
793 _ => return Err(CastError::NonScalar),
796 _ => return Err(CastError::NonScalar),
799 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
800 if adt_def.did().krate != LOCAL_CRATE {
801 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
802 return Err(CastError::ForeignNonExhaustiveAdt);
807 match (t_from, t_cast) {
808 // These types have invariants! can't cast into them.
809 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
812 (_, Int(Bool)) => Err(CastError::CastToBool),
815 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
816 (_, Int(Char)) => Err(CastError::CastToChar),
819 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
821 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
822 Err(CastError::IllegalCast)
826 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
829 (Ptr(m_expr), Int(t_c)) => {
830 self.lossy_provenance_ptr2int_lint(fcx, t_c);
831 self.check_ptr_addr_cast(fcx, m_expr)
834 // FIXME(#95489): there should eventually be a lint for these casts
835 Ok(CastKind::FnPtrAddrCast)
838 (Int(_), Ptr(mt)) => {
839 self.fuzzy_provenance_int2ptr_lint(fcx);
840 self.check_addr_ptr_cast(fcx, mt)
843 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
846 (Int(CEnum), Int(_)) => {
847 self.cenum_impl_drop_lint(fcx);
848 Ok(CastKind::EnumCast)
850 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
852 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
854 (_, DynStar) | (DynStar, _) => {
855 if fcx.tcx.features().dyn_star {
856 bug!("should be handled by `try_coerce`")
858 Err(CastError::IllegalCast)
864 fn check_ptr_ptr_cast(
866 fcx: &FnCtxt<'a, 'tcx>,
867 m_expr: ty::TypeAndMut<'tcx>,
868 m_cast: ty::TypeAndMut<'tcx>,
869 ) -> Result<CastKind, CastError> {
870 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
871 // ptr-ptr cast. vtables must match.
873 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
874 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
876 let Some(cast_kind) = cast_kind else {
877 // We can't cast if target pointer kind is unknown
878 return Err(CastError::UnknownCastPtrKind);
881 // Cast to thin pointer is OK
882 if cast_kind == PointerKind::Thin {
883 return Ok(CastKind::PtrPtrCast);
886 let Some(expr_kind) = expr_kind else {
887 // We can't cast to fat pointer if source pointer kind is unknown
888 return Err(CastError::UnknownExprPtrKind);
891 // thin -> fat? report invalid cast (don't complain about vtable kinds)
892 if expr_kind == PointerKind::Thin {
893 return Err(CastError::SizedUnsizedCast);
896 // vtable kinds must match
897 if fcx.tcx.erase_regions(cast_kind) == fcx.tcx.erase_regions(expr_kind) {
898 Ok(CastKind::PtrPtrCast)
900 Err(CastError::DifferingKinds)
904 fn check_fptr_ptr_cast(
906 fcx: &FnCtxt<'a, 'tcx>,
907 m_cast: ty::TypeAndMut<'tcx>,
908 ) -> Result<CastKind, CastError> {
909 // fptr-ptr cast. must be to thin ptr
911 match fcx.pointer_kind(m_cast.ty, self.span)? {
912 None => Err(CastError::UnknownCastPtrKind),
913 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
914 _ => Err(CastError::IllegalCast),
918 fn check_ptr_addr_cast(
920 fcx: &FnCtxt<'a, 'tcx>,
921 m_expr: ty::TypeAndMut<'tcx>,
922 ) -> Result<CastKind, CastError> {
923 // ptr-addr cast. must be from thin ptr
925 match fcx.pointer_kind(m_expr.ty, self.span)? {
926 None => Err(CastError::UnknownExprPtrKind),
927 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
928 _ => Err(CastError::NeedViaThinPtr),
934 fcx: &FnCtxt<'a, 'tcx>,
935 m_expr: ty::TypeAndMut<'tcx>,
936 m_cast: ty::TypeAndMut<'tcx>,
937 ) -> Result<CastKind, CastError> {
938 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
939 if m_expr.mutbl >= m_cast.mutbl {
940 if let ty::Array(ety, _) = m_expr.ty.kind() {
941 // Due to the limitations of LLVM global constants,
942 // region pointers end up pointing at copies of
943 // vector elements instead of the original values.
944 // To allow raw pointers to work correctly, we
945 // need to special-case obtaining a raw pointer
946 // from a region pointer to a vector.
948 // Coerce to a raw pointer so that we generate AddressOf in MIR.
949 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
950 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
951 .unwrap_or_else(|_| {
953 "could not cast from reference to array to pointer to array ({:?} to {:?})",
959 // this will report a type mismatch if needed
960 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
961 return Ok(CastKind::ArrayPtrCast);
965 Err(CastError::IllegalCast)
968 fn check_addr_ptr_cast(
970 fcx: &FnCtxt<'a, 'tcx>,
971 m_cast: TypeAndMut<'tcx>,
972 ) -> Result<CastKind, CastError> {
973 // ptr-addr cast. pointer must be thin.
974 match fcx.pointer_kind(m_cast.ty, self.span)? {
975 None => Err(CastError::UnknownCastPtrKind),
976 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
977 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
978 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
980 PointerKind::OfProjection(_)
981 | PointerKind::OfOpaque(_, _)
982 | PointerKind::OfParam(_),
983 ) => Err(CastError::IntToFatCast(None)),
987 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
988 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
990 Err(err) => Err(err),
994 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
995 if let ty::Adt(d, _) = self.expr_ty.kind()
996 && d.has_dtor(fcx.tcx)
998 fcx.tcx.struct_span_lint_hir(
999 lint::builtin::CENUM_IMPL_DROP_CAST,
1003 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1004 self.expr_ty, self.cast_ty
1013 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1014 fcx.tcx.struct_span_lint_hir(
1015 lint::builtin::LOSSY_PROVENANCE_CASTS,
1019 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1020 self.expr_ty, self.cast_ty
1023 let msg = "use `.addr()` to obtain the address of a pointer";
1025 let expr_prec = self.expr.precedence().order();
1026 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1028 let scalar_cast = match t_c {
1029 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1030 _ => format!(" as {}", self.cast_ty),
1033 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1036 let suggestions = vec![
1037 (self.expr_span.shrink_to_lo(), String::from("(")),
1038 (cast_span, format!(").addr(){scalar_cast}")),
1041 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1043 lint.span_suggestion(
1046 format!(".addr(){scalar_cast}"),
1047 Applicability::MaybeIncorrect,
1052 "if you can't comply with strict provenance and need to expose the pointer \
1053 provenance you can use `.expose_addr()` instead"
1061 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1062 fcx.tcx.struct_span_lint_hir(
1063 lint::builtin::FUZZY_PROVENANCE_CASTS,
1067 "strict provenance disallows casting integer `{}` to pointer `{}`",
1068 self.expr_ty, self.cast_ty
1071 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1072 let suggestions = vec![
1073 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1074 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1077 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1079 "if you can't comply with strict provenance and don't have a pointer with \
1080 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"