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 rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
37 use rustc_hir::lang_items::LangItem;
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, TypeFoldable};
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;
50 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
52 /// Reifies a cast check to be checked once we have full type information for
53 /// a function context.
55 pub struct CastCheck<'tcx> {
56 expr: &'tcx hir::Expr<'tcx>,
64 /// The kind of pointer and associated metadata (thin, length or vtable) - we
65 /// only allow casts between fat pointers if their metadata have the same
67 #[derive(Copy, Clone, PartialEq, Eq)]
68 enum PointerKind<'tcx> {
69 /// No metadata attached, ie pointer to sized type or foreign type
72 Vtable(Option<DefId>),
75 /// The unsize info of this projection
76 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
77 /// The unsize info of this opaque ty
78 OfOpaque(DefId, SubstsRef<'tcx>),
79 /// The unsize info of this parameter
80 OfParam(&'tcx ty::ParamTy),
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);
95 if let Some(reported) = t.error_reported() {
99 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
100 return Ok(Some(PointerKind::Thin));
104 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
105 ty::Dynamic(ref tty, ..) => 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(ref pi) => Some(PointerKind::OfProjection(pi)),
122 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
123 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
124 // Insufficient type information.
125 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
133 | ty::GeneratorWitness(..)
146 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
147 return Err(reported);
153 #[derive(Copy, Clone)]
160 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
170 /// Cast of int to (possibly) fat raw pointer.
172 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
173 /// or "a length". If this argument is None, then the metadata is unknown, for example,
174 /// when we're typechecking a type parameter with a ?Sized bound.
175 IntToFatCast(Option<&'static str>),
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::Slice(..) => {
219 let reported = check.report_cast_to_unsized_type(fcx);
226 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
228 CastError::ErrorGuaranteed => {
229 // an error has already been reported
231 CastError::NeedDeref => {
232 let error_span = self.span;
233 let mut err = make_invalid_casting_error(
240 let cast_ty = fcx.ty_to_string(self.cast_ty);
243 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
245 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
248 "dereference the expression",
249 format!("*{}", snippet),
250 Applicability::MaybeIncorrect,
253 err.span_help(self.expr_span, "dereference the expression with `*`");
257 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
258 let mut err = make_invalid_casting_error(
265 if self.cast_ty.is_integral() {
267 "cast through {} first",
269 CastError::NeedViaPtr => "a raw pointer",
270 CastError::NeedViaThinPtr => "a thin pointer",
277 CastError::NeedViaInt => {
278 make_invalid_casting_error(
286 "cast through {} first",
288 CastError::NeedViaInt => "an integer",
294 CastError::IllegalCast => {
295 make_invalid_casting_error(
304 CastError::DifferingKinds => {
305 make_invalid_casting_error(
312 .note("vtable kinds may not match")
315 CastError::CastToBool => {
317 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
319 if self.expr_ty.is_numeric() {
320 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
324 "compare with zero instead",
325 format!("{snippet} != 0"),
326 Applicability::MachineApplicable,
330 err.span_help(self.span, "compare with zero instead");
334 err.span_label(self.span, "unsupported cast");
339 CastError::CastToChar => {
340 let mut err = type_error_struct!(
345 "only `u8` can be cast as `char`, not `{}`",
348 err.span_label(self.span, "invalid cast");
349 if self.expr_ty.is_numeric() {
352 if self.expr_ty == fcx.tcx.types.i8 {
353 "try casting from `u8` instead"
354 } else if self.expr_ty == fcx.tcx.types.u32 {
355 "try `char::from_u32` instead"
357 "try `char::from_u32` instead (via a `u32`)"
363 CastError::NonScalar => {
364 let mut err = type_error_struct!(
369 "non-primitive cast: `{}` as `{}`",
371 fcx.ty_to_string(self.cast_ty)
374 let mut sugg_mutref = false;
375 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
376 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
381 fcx.tcx.lifetimes.re_erased,
382 TypeAndMut { ty: expr_ty, mutbl },
390 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
391 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
392 && expr_mutbl == Mutability::Not
393 && mutbl == Mutability::Mut
399 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
415 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
422 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
424 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
429 fcx.tcx.lifetimes.re_erased,
430 TypeAndMut { ty: self.expr_ty, mutbl },
438 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
441 err.span_label(self.span, "invalid cast");
442 err.span_note(self.expr_span, "this reference is immutable");
443 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
444 } else if let Some((sugg, remove_cast)) = sugg {
445 err.span_label(self.span, "invalid cast");
451 .span_to_snippet(self.expr_span)
452 .map_or(false, |snip| snip.starts_with('('));
454 // Very crude check to see whether the expression must be wrapped
455 // in parentheses for the suggestion to work (issue #89497).
456 // Can/should be extended in the future.
458 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
460 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
462 suggestion[0].1 += "(";
463 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
467 self.expr_span.shrink_to_hi().to(self.cast_span),
472 err.multipart_suggestion_verbose(
473 "consider borrowing the value",
475 Applicability::MachineApplicable,
479 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
481 let mut label = true;
482 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
483 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
484 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
486 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
487 // Erase regions to avoid panic in `prove_value` when calling
488 // `type_implements_trait`.
489 let ty = fcx.tcx.erase_regions(ty);
490 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
491 let expr_ty = fcx.tcx.erase_regions(expr_ty);
492 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
495 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
496 .must_apply_modulo_regions()
501 "consider using the `From` trait instead",
502 format!("{}::from({})", self.cast_ty, snippet),
503 Applicability::MaybeIncorrect,
507 let msg = "an `as` expression can only be used to convert between primitive \
508 types or to coerce to a specific trait object";
510 err.span_label(self.span, msg);
515 err.span_label(self.span, "invalid cast");
519 CastError::SizedUnsizedCast => {
520 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
525 expr_ty: self.expr_ty,
526 cast_ty: fcx.ty_to_string(self.cast_ty),
531 CastError::IntToFatCast(known_metadata) => {
532 let mut err = struct_span_err!(
536 "cannot cast `{}` to a pointer that {} wide",
537 fcx.ty_to_string(self.expr_ty),
538 if known_metadata.is_some() { "is" } else { "may be" }
544 "creating a `{}` requires both an address and {}",
546 known_metadata.unwrap_or("type-specific metadata"),
550 if fcx.tcx.sess.is_nightly_build() {
553 "consider casting this expression to `*const ()`, \
554 then using `core::ptr::from_raw_parts`",
560 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
561 let unknown_cast_to = match e {
562 CastError::UnknownCastPtrKind => true,
563 CastError::UnknownExprPtrKind => false,
566 let mut err = struct_span_err!(
568 if unknown_cast_to { self.cast_span } else { self.span },
570 "cannot cast {} a pointer of an unknown kind",
571 if unknown_cast_to { "to" } else { "from" }
574 err.span_label(self.cast_span, "needs more type information");
576 "the type information given here is insufficient to check whether \
577 the pointer cast is valid",
582 "the type information given here is insufficient to check whether \
583 the pointer cast is valid",
591 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
592 if let Some(reported) =
593 self.cast_ty.error_reported().or_else(|| self.expr_ty.error_reported())
598 let tstr = fcx.ty_to_string(self.cast_ty);
599 let mut err = type_error_struct!(
604 "cast to unsized type: `{}` as `{}`",
605 fcx.resolve_vars_if_possible(self.expr_ty),
608 match self.expr_ty.kind() {
609 ty::Ref(_, _, mt) => {
610 let mtstr = mt.prefix_str();
611 if self.cast_ty.is_trait() {
612 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
616 "try casting to a reference instead",
617 format!("&{}{}", mtstr, s),
618 Applicability::MachineApplicable,
622 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
623 err.span_help(self.cast_span, msg);
628 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
629 err.span_help(self.span, msg);
632 ty::Adt(def, ..) if def.is_box() => {
633 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
637 "you can cast to a `Box` instead",
639 Applicability::MachineApplicable,
645 &format!("you might have meant `Box<{tstr}>`"),
651 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
657 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
658 let t_cast = self.cast_ty;
659 let t_expr = self.expr_ty;
661 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
662 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
663 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
665 ("", lint::builtin::TRIVIAL_CASTS)
667 fcx.tcx.struct_span_lint_hir(lint, self.expr.hir_id, self.span, |err| {
669 "trivial {}cast: `{}` as `{}`",
671 fcx.ty_to_string(t_expr),
672 fcx.ty_to_string(t_cast)
675 "cast can be replaced by coercion; this might \
676 require {type_asc_or}a temporary variable"
682 #[instrument(skip(fcx), level = "debug")]
683 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
684 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
685 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
687 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
689 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span)
690 && !self.cast_ty.has_infer_types()
692 self.report_cast_to_unsized_type(fcx);
693 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
694 // No sense in giving duplicate error messages
696 match self.try_coercion_cast(fcx) {
698 self.trivial_cast_lint(fcx);
699 debug!(" -> CoercionCast");
700 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
702 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
703 self.report_object_unsafe_cast(&fcx, did);
706 match self.do_check(fcx) {
708 debug!(" -> {:?}", k);
710 Err(e) => self.report_cast_error(fcx, e),
717 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
718 let violations = fcx.tcx.object_safety_violations(did);
719 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
720 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
724 /// Checks a cast, and report an error if one exists. In some cases, this
725 /// can return Ok and create type errors in the fcx rather than returning
726 /// directly. coercion-cast is handled in check instead of here.
727 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
728 use rustc_middle::ty::cast::CastTy::*;
729 use rustc_middle::ty::cast::IntTy::*;
731 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
733 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
734 // Function item types may need to be reified before casts.
735 (None, Some(t_cast)) => {
736 match *self.expr_ty.kind() {
738 // Attempt a coercion to a fn pointer type.
739 let f = fcx.normalize_associated_types_in(
741 self.expr_ty.fn_sig(fcx.tcx),
743 let res = fcx.try_coerce(
746 fcx.tcx.mk_fn_ptr(f),
750 if let Err(TypeError::IntrinsicCast) = res {
751 return Err(CastError::IllegalCast);
754 return Err(CastError::NonScalar);
758 // Special case some errors for references, and check for
759 // array-ptr-casts. `Ref` is not a CastTy because the cast
760 // is split into a coercion to a pointer type, followed by
762 ty::Ref(_, inner_ty, mutbl) => {
763 return match t_cast {
764 Int(_) | Float => match *inner_ty.kind() {
768 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
769 Err(CastError::NeedDeref)
771 _ => Err(CastError::NeedViaPtr),
775 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
777 _ => Err(CastError::NonScalar),
780 _ => return Err(CastError::NonScalar),
783 _ => return Err(CastError::NonScalar),
786 match (t_from, t_cast) {
787 // These types have invariants! can't cast into them.
788 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
791 (_, Int(Bool)) => Err(CastError::CastToBool),
794 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
795 (_, Int(Char)) => Err(CastError::CastToChar),
798 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
800 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
801 Err(CastError::IllegalCast)
805 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
808 (Ptr(m_expr), Int(t_c)) => {
809 self.lossy_provenance_ptr2int_lint(fcx, t_c);
810 self.check_ptr_addr_cast(fcx, m_expr)
813 // FIXME(#95489): there should eventually be a lint for these casts
814 Ok(CastKind::FnPtrAddrCast)
817 (Int(_), Ptr(mt)) => {
818 self.fuzzy_provenance_int2ptr_lint(fcx);
819 self.check_addr_ptr_cast(fcx, mt)
822 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
825 (Int(CEnum), Int(_)) => {
826 self.cenum_impl_drop_lint(fcx);
827 Ok(CastKind::EnumCast)
829 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
831 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
835 fn check_ptr_ptr_cast(
837 fcx: &FnCtxt<'a, 'tcx>,
838 m_expr: ty::TypeAndMut<'tcx>,
839 m_cast: ty::TypeAndMut<'tcx>,
840 ) -> Result<CastKind, CastError> {
841 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
842 // ptr-ptr cast. vtables must match.
844 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
845 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
847 let Some(cast_kind) = cast_kind else {
848 // We can't cast if target pointer kind is unknown
849 return Err(CastError::UnknownCastPtrKind);
852 // Cast to thin pointer is OK
853 if cast_kind == PointerKind::Thin {
854 return Ok(CastKind::PtrPtrCast);
857 let Some(expr_kind) = expr_kind else {
858 // We can't cast to fat pointer if source pointer kind is unknown
859 return Err(CastError::UnknownExprPtrKind);
862 // thin -> fat? report invalid cast (don't complain about vtable kinds)
863 if expr_kind == PointerKind::Thin {
864 return Err(CastError::SizedUnsizedCast);
867 // vtable kinds must match
868 if cast_kind == expr_kind {
869 Ok(CastKind::PtrPtrCast)
871 Err(CastError::DifferingKinds)
875 fn check_fptr_ptr_cast(
877 fcx: &FnCtxt<'a, 'tcx>,
878 m_cast: ty::TypeAndMut<'tcx>,
879 ) -> Result<CastKind, CastError> {
880 // fptr-ptr cast. must be to thin ptr
882 match fcx.pointer_kind(m_cast.ty, self.span)? {
883 None => Err(CastError::UnknownCastPtrKind),
884 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
885 _ => Err(CastError::IllegalCast),
889 fn check_ptr_addr_cast(
891 fcx: &FnCtxt<'a, 'tcx>,
892 m_expr: ty::TypeAndMut<'tcx>,
893 ) -> Result<CastKind, CastError> {
894 // ptr-addr cast. must be from thin ptr
896 match fcx.pointer_kind(m_expr.ty, self.span)? {
897 None => Err(CastError::UnknownExprPtrKind),
898 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
899 _ => Err(CastError::NeedViaThinPtr),
905 fcx: &FnCtxt<'a, 'tcx>,
906 m_expr: ty::TypeAndMut<'tcx>,
907 m_cast: ty::TypeAndMut<'tcx>,
908 ) -> Result<CastKind, CastError> {
909 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
910 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
911 if let ty::Array(ety, _) = m_expr.ty.kind() {
912 // Due to the limitations of LLVM global constants,
913 // region pointers end up pointing at copies of
914 // vector elements instead of the original values.
915 // To allow raw pointers to work correctly, we
916 // need to special-case obtaining a raw pointer
917 // from a region pointer to a vector.
919 // Coerce to a raw pointer so that we generate AddressOf in MIR.
920 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
921 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
922 .unwrap_or_else(|_| {
924 "could not cast from reference to array to pointer to array ({:?} to {:?})",
930 // this will report a type mismatch if needed
931 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
932 return Ok(CastKind::ArrayPtrCast);
936 Err(CastError::IllegalCast)
939 fn check_addr_ptr_cast(
941 fcx: &FnCtxt<'a, 'tcx>,
942 m_cast: TypeAndMut<'tcx>,
943 ) -> Result<CastKind, CastError> {
944 // ptr-addr cast. pointer must be thin.
945 match fcx.pointer_kind(m_cast.ty, self.span)? {
946 None => Err(CastError::UnknownCastPtrKind),
947 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
948 Some(PointerKind::Vtable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
949 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
951 PointerKind::OfProjection(_)
952 | PointerKind::OfOpaque(_, _)
953 | PointerKind::OfParam(_),
954 ) => Err(CastError::IntToFatCast(None)),
958 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
959 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
961 Err(err) => Err(err),
965 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
966 if let ty::Adt(d, _) = self.expr_ty.kind()
967 && d.has_dtor(fcx.tcx)
969 fcx.tcx.struct_span_lint_hir(
970 lint::builtin::CENUM_IMPL_DROP_CAST,
975 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
976 self.expr_ty, self.cast_ty
984 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
985 fcx.tcx.struct_span_lint_hir(
986 lint::builtin::LOSSY_PROVENANCE_CASTS,
990 let mut err = err.build(&format!(
991 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
992 self.expr_ty, self.cast_ty
995 let msg = "use `.addr()` to obtain the address of a pointer";
997 let expr_prec = self.expr.precedence().order();
998 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1000 let scalar_cast = match t_c {
1001 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1002 _ => format!(" as {}", self.cast_ty),
1005 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1008 let suggestions = vec![
1009 (self.expr_span.shrink_to_lo(), String::from("(")),
1010 (cast_span, format!(").addr(){scalar_cast}")),
1013 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1015 err.span_suggestion(
1018 format!(".addr(){scalar_cast}"),
1019 Applicability::MaybeIncorrect,
1024 "if you can't comply with strict provenance and need to expose the pointer \
1025 provenance you can use `.expose_addr()` instead"
1033 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1034 fcx.tcx.struct_span_lint_hir(
1035 lint::builtin::FUZZY_PROVENANCE_CASTS,
1039 let mut err = err.build(&format!(
1040 "strict provenance disallows casting integer `{}` to pointer `{}`",
1041 self.expr_ty, self.cast_ty
1043 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1044 let suggestions = vec![
1045 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1046 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1049 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1051 "if you can't comply with strict provenance and don't have a pointer with \
1052 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"
1061 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1062 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
1063 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
1064 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)