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::{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;
49 /// Reifies a cast check to be checked once we have full type information for
50 /// a function context.
52 pub struct CastCheck<'tcx> {
53 /// The expression whose value is being casted
54 expr: &'tcx hir::Expr<'tcx>,
55 /// The source type for the cast expression
58 /// The target type. That is, the type we are casting to.
62 /// whether the cast is made in a const context or not.
63 pub constness: hir::Constness,
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(Debug, Copy, Clone, PartialEq, Eq, TypeVisitable, TypeFoldable)]
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 or opaque type
78 OfAlias(ty::AliasTy<'tcx>),
79 /// The unsize info of this parameter
83 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
84 /// Returns the kind of unsize information of t, or None
90 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
91 debug!("pointer_kind({:?}, {:?})", t, span);
93 let t = self.resolve_vars_if_possible(t);
96 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
97 return Ok(Some(PointerKind::Thin));
101 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
102 ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
103 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
104 None => Some(PointerKind::Thin),
106 let field_ty = self.field_ty(span, f, substs);
107 self.pointer_kind(field_ty, span)?
110 ty::Tuple(fields) => match fields.last() {
111 None => Some(PointerKind::Thin),
112 Some(&f) => self.pointer_kind(f, span)?,
115 // Pointers to foreign types are thin, despite being unsized
116 ty::Foreign(..) => Some(PointerKind::Thin),
117 // We should really try to normalize here.
118 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
119 ty::Param(p) => Some(PointerKind::OfParam(p)),
120 // Insufficient type information.
121 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
129 | ty::GeneratorWitness(..)
138 | ty::Dynamic(_, _, ty::DynStar)
143 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
144 return Err(reported);
150 #[derive(Copy, Clone)]
157 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
167 /// Cast of int to (possibly) fat raw pointer.
169 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
170 /// or "a length". If this argument is None, then the metadata is unknown, for example,
171 /// when we're typechecking a type parameter with a ?Sized bound.
172 IntToFatCast(Option<&'static str>),
173 ForeignNonExhaustiveAdt,
176 impl From<ErrorGuaranteed> for CastError {
177 fn from(_: ErrorGuaranteed) -> Self {
178 CastError::ErrorGuaranteed
182 fn make_invalid_casting_error<'a, 'tcx>(
187 fcx: &FnCtxt<'a, 'tcx>,
188 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
194 "casting `{}` as `{}` is invalid",
195 fcx.ty_to_string(expr_ty),
196 fcx.ty_to_string(cast_ty)
200 impl<'a, 'tcx> CastCheck<'tcx> {
202 fcx: &FnCtxt<'a, 'tcx>,
203 expr: &'tcx hir::Expr<'tcx>,
208 constness: hir::Constness,
209 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
210 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
211 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span, constness };
213 // For better error messages, check for some obviously unsized
214 // cases now. We do a more thorough check at the end, once
215 // inference is more completely known.
216 match cast_ty.kind() {
217 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
218 Err(check.report_cast_to_unsized_type(fcx))
224 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
226 CastError::ErrorGuaranteed => {
227 // an error has already been reported
229 CastError::NeedDeref => {
230 let error_span = self.span;
231 let mut err = make_invalid_casting_error(
238 let cast_ty = fcx.ty_to_string(self.cast_ty);
241 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
243 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
246 "dereference the expression",
247 format!("*{}", snippet),
248 Applicability::MaybeIncorrect,
251 err.span_help(self.expr_span, "dereference the expression with `*`");
255 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
256 let mut err = make_invalid_casting_error(
263 if self.cast_ty.is_integral() {
265 "cast through {} first",
267 CastError::NeedViaPtr => "a raw pointer",
268 CastError::NeedViaThinPtr => "a thin pointer",
275 CastError::NeedViaInt => {
276 make_invalid_casting_error(
284 "cast through {} first",
286 CastError::NeedViaInt => "an integer",
292 CastError::IllegalCast => {
293 make_invalid_casting_error(
302 CastError::DifferingKinds => {
303 make_invalid_casting_error(
310 .note("vtable kinds may not match")
313 CastError::CastToBool => {
315 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
317 if self.expr_ty.is_numeric() {
318 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
322 "compare with zero instead",
323 format!("{snippet} != 0"),
324 Applicability::MachineApplicable,
328 err.span_help(self.span, "compare with zero instead");
332 err.span_label(self.span, "unsupported cast");
337 CastError::CastToChar => {
338 let mut err = type_error_struct!(
343 "only `u8` can be cast as `char`, not `{}`",
346 err.span_label(self.span, "invalid cast");
347 if self.expr_ty.is_numeric() {
348 if self.expr_ty == fcx.tcx.types.u32 {
349 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
350 Ok(snippet) => err.span_suggestion(
352 "try `char::from_u32` instead",
353 format!("char::from_u32({snippet})"),
354 Applicability::MachineApplicable,
357 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
359 } else if self.expr_ty == fcx.tcx.types.i8 {
360 err.span_help(self.span, "try casting from `u8` instead");
362 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
367 CastError::NonScalar => {
368 let mut err = type_error_struct!(
373 "non-primitive cast: `{}` as `{}`",
375 fcx.ty_to_string(self.cast_ty)
378 let mut sugg_mutref = false;
379 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
380 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
385 fcx.tcx.lifetimes.re_erased,
386 TypeAndMut { ty: expr_ty, mutbl },
394 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
395 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
396 && expr_mutbl == Mutability::Not
397 && mutbl == Mutability::Mut
403 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
419 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
426 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
428 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
433 fcx.tcx.lifetimes.re_erased,
434 TypeAndMut { ty: self.expr_ty, mutbl },
442 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
445 err.span_label(self.span, "invalid cast");
446 err.span_note(self.expr_span, "this reference is immutable");
447 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
448 } else if let Some((sugg, remove_cast)) = sugg {
449 err.span_label(self.span, "invalid cast");
455 .span_to_snippet(self.expr_span)
456 .map_or(false, |snip| snip.starts_with('('));
458 // Very crude check to see whether the expression must be wrapped
459 // in parentheses for the suggestion to work (issue #89497).
460 // Can/should be extended in the future.
462 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
464 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
466 suggestion[0].1 += "(";
467 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
471 self.expr_span.shrink_to_hi().to(self.cast_span),
476 err.multipart_suggestion_verbose(
477 "consider borrowing the value",
479 Applicability::MachineApplicable,
483 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
485 let mut label = true;
486 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
487 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
488 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
490 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
491 // Erase regions to avoid panic in `prove_value` when calling
492 // `type_implements_trait`.
493 let ty = fcx.tcx.erase_regions(ty);
494 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
495 let expr_ty = fcx.tcx.erase_regions(expr_ty);
498 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
499 .must_apply_modulo_regions()
504 "consider using the `From` trait instead",
505 format!("{}::from({})", self.cast_ty, snippet),
506 Applicability::MaybeIncorrect,
510 let msg = "an `as` expression can only be used to convert between primitive \
511 types or to coerce to a specific trait object";
513 err.span_label(self.span, msg);
518 err.span_label(self.span, "invalid cast");
522 CastError::SizedUnsizedCast => {
523 use rustc_hir_analysis::structured_errors::{
524 SizedUnsizedCast, StructuredDiagnostic,
530 expr_ty: self.expr_ty,
531 cast_ty: fcx.ty_to_string(self.cast_ty),
536 CastError::IntToFatCast(known_metadata) => {
537 let mut err = struct_span_err!(
541 "cannot cast `{}` to a pointer that {} wide",
542 fcx.ty_to_string(self.expr_ty),
543 if known_metadata.is_some() { "is" } else { "may be" }
549 "creating a `{}` requires both an address and {}",
551 known_metadata.unwrap_or("type-specific metadata"),
555 if fcx.tcx.sess.is_nightly_build() {
558 "consider casting this expression to `*const ()`, \
559 then using `core::ptr::from_raw_parts`",
565 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
566 let unknown_cast_to = match e {
567 CastError::UnknownCastPtrKind => true,
568 CastError::UnknownExprPtrKind => false,
571 let mut err = struct_span_err!(
573 if unknown_cast_to { self.cast_span } else { self.span },
575 "cannot cast {} a pointer of an unknown kind",
576 if unknown_cast_to { "to" } else { "from" }
579 err.span_label(self.cast_span, "needs more type information");
581 "the type information given here is insufficient to check whether \
582 the pointer cast is valid",
587 "the type information given here is insufficient to check whether \
588 the pointer cast is valid",
593 CastError::ForeignNonExhaustiveAdt => {
594 make_invalid_casting_error(
601 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
607 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
608 if let Err(err) = self.cast_ty.error_reported() {
611 if let Err(err) = self.expr_ty.error_reported() {
615 let tstr = fcx.ty_to_string(self.cast_ty);
616 let mut err = type_error_struct!(
621 "cast to unsized type: `{}` as `{}`",
622 fcx.resolve_vars_if_possible(self.expr_ty),
625 match self.expr_ty.kind() {
626 ty::Ref(_, _, mt) => {
627 let mtstr = mt.prefix_str();
628 if self.cast_ty.is_trait() {
629 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
633 "try casting to a reference instead",
634 format!("&{}{}", mtstr, s),
635 Applicability::MachineApplicable,
639 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
640 err.span_help(self.cast_span, msg);
645 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
646 err.span_help(self.span, msg);
649 ty::Adt(def, ..) if def.is_box() => {
650 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
654 "you can cast to a `Box` instead",
656 Applicability::MachineApplicable,
662 &format!("you might have meant `Box<{tstr}>`"),
668 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
674 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
675 let t_cast = self.cast_ty;
676 let t_expr = self.expr_ty;
678 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
679 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
680 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
682 ("", lint::builtin::TRIVIAL_CASTS)
684 fcx.tcx.struct_span_lint_hir(
690 "trivial {}cast: `{}` as `{}`",
692 fcx.ty_to_string(t_expr),
693 fcx.ty_to_string(t_cast)
698 "cast can be replaced by coercion; this might \
699 require {type_asc_or}a temporary variable"
705 #[instrument(skip(fcx), level = "debug")]
706 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
707 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
708 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
710 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
712 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
713 && !self.cast_ty.has_infer_types()
715 self.report_cast_to_unsized_type(fcx);
716 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
717 // No sense in giving duplicate error messages
719 match self.try_coercion_cast(fcx) {
721 self.trivial_cast_lint(fcx);
722 debug!(" -> CoercionCast");
723 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
726 match self.do_check(fcx) {
728 debug!(" -> {:?}", k);
730 Err(e) => self.report_cast_error(fcx, e),
736 /// Checks a cast, and report an error if one exists. In some cases, this
737 /// can return Ok and create type errors in the fcx rather than returning
738 /// directly. coercion-cast is handled in check instead of here.
739 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
740 use rustc_middle::ty::cast::CastTy::*;
741 use rustc_middle::ty::cast::IntTy::*;
743 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
745 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
746 // Function item types may need to be reified before casts.
747 (None, Some(t_cast)) => {
748 match *self.expr_ty.kind() {
750 // Attempt a coercion to a fn pointer type.
751 let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
752 let res = fcx.try_coerce(
755 fcx.tcx.mk_fn_ptr(f),
759 if let Err(TypeError::IntrinsicCast) = res {
760 return Err(CastError::IllegalCast);
763 return Err(CastError::NonScalar);
767 // Special case some errors for references, and check for
768 // array-ptr-casts. `Ref` is not a CastTy because the cast
769 // is split into a coercion to a pointer type, followed by
771 ty::Ref(_, inner_ty, mutbl) => {
772 return match t_cast {
773 Int(_) | Float => match *inner_ty.kind() {
777 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
778 Err(CastError::NeedDeref)
780 _ => Err(CastError::NeedViaPtr),
784 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
786 _ => Err(CastError::NonScalar),
789 _ => return Err(CastError::NonScalar),
792 _ => return Err(CastError::NonScalar),
795 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
796 if adt_def.did().krate != LOCAL_CRATE {
797 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
798 return Err(CastError::ForeignNonExhaustiveAdt);
803 match (t_from, t_cast) {
804 // These types have invariants! can't cast into them.
805 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
808 (_, Int(Bool)) => Err(CastError::CastToBool),
811 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
812 (_, Int(Char)) => Err(CastError::CastToChar),
815 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
817 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
818 Err(CastError::IllegalCast)
822 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
825 (Ptr(m_expr), Int(t_c)) => {
826 self.lossy_provenance_ptr2int_lint(fcx, t_c);
827 self.check_ptr_addr_cast(fcx, m_expr)
830 // FIXME(#95489): there should eventually be a lint for these casts
831 Ok(CastKind::FnPtrAddrCast)
834 (Int(_), Ptr(mt)) => {
835 self.fuzzy_provenance_int2ptr_lint(fcx);
836 self.check_addr_ptr_cast(fcx, mt)
839 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
842 (Int(CEnum), Int(_)) => {
843 self.cenum_impl_drop_lint(fcx);
844 Ok(CastKind::EnumCast)
846 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
848 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
851 if fcx.tcx.features().dyn_star {
852 bug!("should be handled by `try_coerce`")
854 Err(CastError::IllegalCast)
858 (DynStar, _) => Err(CastError::IllegalCast),
862 fn check_ptr_ptr_cast(
864 fcx: &FnCtxt<'a, 'tcx>,
865 m_expr: ty::TypeAndMut<'tcx>,
866 m_cast: ty::TypeAndMut<'tcx>,
867 ) -> Result<CastKind, CastError> {
868 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
869 // ptr-ptr cast. vtables must match.
871 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
872 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
874 let Some(cast_kind) = cast_kind else {
875 // We can't cast if target pointer kind is unknown
876 return Err(CastError::UnknownCastPtrKind);
879 // Cast to thin pointer is OK
880 if cast_kind == PointerKind::Thin {
881 return Ok(CastKind::PtrPtrCast);
884 let Some(expr_kind) = expr_kind else {
885 // We can't cast to fat pointer if source pointer kind is unknown
886 return Err(CastError::UnknownExprPtrKind);
889 // thin -> fat? report invalid cast (don't complain about vtable kinds)
890 if expr_kind == PointerKind::Thin {
891 return Err(CastError::SizedUnsizedCast);
894 // vtable kinds must match
895 if fcx.tcx.erase_regions(cast_kind) == fcx.tcx.erase_regions(expr_kind) {
896 Ok(CastKind::PtrPtrCast)
898 Err(CastError::DifferingKinds)
902 fn check_fptr_ptr_cast(
904 fcx: &FnCtxt<'a, 'tcx>,
905 m_cast: ty::TypeAndMut<'tcx>,
906 ) -> Result<CastKind, CastError> {
907 // fptr-ptr cast. must be to thin ptr
909 match fcx.pointer_kind(m_cast.ty, self.span)? {
910 None => Err(CastError::UnknownCastPtrKind),
911 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
912 _ => Err(CastError::IllegalCast),
916 fn check_ptr_addr_cast(
918 fcx: &FnCtxt<'a, 'tcx>,
919 m_expr: ty::TypeAndMut<'tcx>,
920 ) -> Result<CastKind, CastError> {
921 // ptr-addr cast. must be from thin ptr
923 match fcx.pointer_kind(m_expr.ty, self.span)? {
924 None => Err(CastError::UnknownExprPtrKind),
925 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
926 _ => Err(CastError::NeedViaThinPtr),
932 fcx: &FnCtxt<'a, 'tcx>,
933 m_expr: ty::TypeAndMut<'tcx>,
934 m_cast: ty::TypeAndMut<'tcx>,
935 ) -> Result<CastKind, CastError> {
936 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
937 if m_expr.mutbl >= m_cast.mutbl {
938 if let ty::Array(ety, _) = m_expr.ty.kind() {
939 // Due to the limitations of LLVM global constants,
940 // region pointers end up pointing at copies of
941 // vector elements instead of the original values.
942 // To allow raw pointers to work correctly, we
943 // need to special-case obtaining a raw pointer
944 // from a region pointer to a vector.
946 // Coerce to a raw pointer so that we generate AddressOf in MIR.
947 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
948 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
949 .unwrap_or_else(|_| {
951 "could not cast from reference to array to pointer to array ({:?} to {:?})",
957 // this will report a type mismatch if needed
958 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
959 return Ok(CastKind::ArrayPtrCast);
963 Err(CastError::IllegalCast)
966 fn check_addr_ptr_cast(
968 fcx: &FnCtxt<'a, 'tcx>,
969 m_cast: TypeAndMut<'tcx>,
970 ) -> Result<CastKind, CastError> {
971 // ptr-addr cast. pointer must be thin.
972 match fcx.pointer_kind(m_cast.ty, self.span)? {
973 None => Err(CastError::UnknownCastPtrKind),
974 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
975 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
976 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
977 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
978 Err(CastError::IntToFatCast(None))
983 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
984 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
986 Err(err) => Err(err),
990 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
991 if let ty::Adt(d, _) = self.expr_ty.kind()
992 && d.has_dtor(fcx.tcx)
994 fcx.tcx.struct_span_lint_hir(
995 lint::builtin::CENUM_IMPL_DROP_CAST,
999 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1000 self.expr_ty, self.cast_ty
1009 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1010 fcx.tcx.struct_span_lint_hir(
1011 lint::builtin::LOSSY_PROVENANCE_CASTS,
1015 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1016 self.expr_ty, self.cast_ty
1019 let msg = "use `.addr()` to obtain the address of a pointer";
1021 let expr_prec = self.expr.precedence().order();
1022 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1024 let scalar_cast = match t_c {
1025 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1026 _ => format!(" as {}", self.cast_ty),
1029 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1032 let suggestions = vec![
1033 (self.expr_span.shrink_to_lo(), String::from("(")),
1034 (cast_span, format!(").addr(){scalar_cast}")),
1037 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1039 lint.span_suggestion(
1042 format!(".addr(){scalar_cast}"),
1043 Applicability::MaybeIncorrect,
1048 "if you can't comply with strict provenance and need to expose the pointer \
1049 provenance you can use `.expose_addr()` instead"
1057 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1058 fcx.tcx.struct_span_lint_hir(
1059 lint::builtin::FUZZY_PROVENANCE_CASTS,
1063 "strict provenance disallows casting integer `{}` to pointer `{}`",
1064 self.expr_ty, self.cast_ty
1067 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1068 let suggestions = vec![
1069 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1070 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1073 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1075 "if you can't comply with strict provenance and don't have a pointer with \
1076 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"