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_infer::traits::{Obligation, ObligationCause, ObligationCauseCode};
39 use rustc_middle::mir::Mutability;
40 use rustc_middle::ty::adjustment::AllowTwoPhase;
41 use rustc_middle::ty::cast::{CastKind, CastTy};
42 use rustc_middle::ty::error::TypeError;
43 use rustc_middle::ty::subst::SubstsRef;
44 use rustc_middle::ty::{self, Binder, Ty, TypeAndMut, TypeVisitable, VariantDef};
45 use rustc_session::lint;
46 use rustc_session::Session;
47 use rustc_span::symbol::sym;
49 use rustc_trait_selection::infer::InferCtxtExt;
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 /// The expression whose value is being casted
57 expr: &'tcx hir::Expr<'tcx>,
58 /// The source type for the cast expression
61 /// The target type. That is, the type we are casting to.
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(Copy, Clone, PartialEq, Eq)]
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(&'tcx ty::ProjectionTy<'tcx>),
80 /// The unsize info of this opaque ty
81 OfOpaque(DefId, SubstsRef<'tcx>),
82 /// The unsize info of this parameter
83 OfParam(&'tcx ty::ParamTy),
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);
98 if let Some(reported) = t.error_reported() {
102 if self.type_is_sized_modulo_regions(self.param_env, t, span) {
103 return Ok(Some(PointerKind::Thin));
107 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
108 ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
109 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
110 None => Some(PointerKind::Thin),
112 let field_ty = self.field_ty(span, f, substs);
113 self.pointer_kind(field_ty, span)?
116 ty::Tuple(fields) => match fields.last() {
117 None => Some(PointerKind::Thin),
118 Some(&f) => self.pointer_kind(f, span)?,
121 // Pointers to foreign types are thin, despite being unsized
122 ty::Foreign(..) => Some(PointerKind::Thin),
123 // We should really try to normalize here.
124 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
125 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
126 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
127 // Insufficient type information.
128 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
136 | ty::GeneratorWitness(..)
145 | ty::Dynamic(_, _, ty::DynStar)
150 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
151 return Err(reported);
157 #[derive(Copy, Clone)]
164 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
174 /// Cast of int to (possibly) fat raw pointer.
176 /// Argument is the specific name of the metadata in plain words, such as "a vtable"
177 /// or "a length". If this argument is None, then the metadata is unknown, for example,
178 /// when we're typechecking a type parameter with a ?Sized bound.
179 IntToFatCast(Option<&'static str>),
180 ForeignNonExhaustiveAdt,
183 impl From<ErrorGuaranteed> for CastError {
184 fn from(_: ErrorGuaranteed) -> Self {
185 CastError::ErrorGuaranteed
189 fn make_invalid_casting_error<'a, 'tcx>(
194 fcx: &FnCtxt<'a, 'tcx>,
195 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
201 "casting `{}` as `{}` is invalid",
202 fcx.ty_to_string(expr_ty),
203 fcx.ty_to_string(cast_ty)
207 pub enum CastCheckResult<'tcx> {
209 Deferred(CastCheck<'tcx>),
210 Err(ErrorGuaranteed),
213 pub fn check_cast<'tcx>(
214 fcx: &FnCtxt<'_, 'tcx>,
215 expr: &'tcx hir::Expr<'tcx>,
220 ) -> CastCheckResult<'tcx> {
221 if cast_ty.is_dyn_star() {
222 check_dyn_star_cast(fcx, expr, expr_ty, cast_ty)
224 match CastCheck::new(fcx, expr, expr_ty, cast_ty, cast_span, span) {
225 Ok(check) => CastCheckResult::Deferred(check),
226 Err(e) => CastCheckResult::Err(e),
231 fn check_dyn_star_cast<'tcx>(
232 fcx: &FnCtxt<'_, 'tcx>,
233 expr: &'tcx hir::Expr<'tcx>,
236 ) -> CastCheckResult<'tcx> {
237 // Find the bounds in the dyn*. For eaxmple, if we have
239 // let x = 22_usize as dyn* (Clone + Debug + 'static)
241 // this would return `existential_predicates = [?Self: Clone, ?Self: Debug]` and `region = 'static`.
242 let (existential_predicates, region) = match cast_ty.kind() {
243 ty::Dynamic(predicates, region, ty::DynStar) => (predicates, region),
244 _ => panic!("Invalid dyn* cast_ty"),
247 let cause = ObligationCause::new(
250 // FIXME(dyn-star): Use a better obligation cause code
251 ObligationCauseCode::MiscObligation,
254 // For each existential predicate (e.g., `?Self: Clone`) substitute
255 // the type of the expression (e.g., `usize` in our example above)
256 // and then require that the resulting predicate (e.g., `usize: Clone`)
258 for existential_predicate in existential_predicates.iter() {
259 let predicate = existential_predicate.with_self_ty(fcx.tcx, expr_ty);
260 fcx.register_predicate(Obligation::new(cause.clone(), fcx.param_env, predicate));
263 // Enforce the region bound `'static` (e.g., `usize: 'static`, in our example).
264 fcx.register_predicate(Obligation::new(
267 fcx.tcx.mk_predicate(Binder::dummy(ty::PredicateKind::TypeOutlives(
268 ty::OutlivesPredicate(expr_ty, *region),
275 impl<'a, 'tcx> CastCheck<'tcx> {
277 fcx: &FnCtxt<'a, 'tcx>,
278 expr: &'tcx hir::Expr<'tcx>,
283 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
284 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
285 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
287 // For better error messages, check for some obviously unsized
288 // cases now. We do a more thorough check at the end, once
289 // inference is more completely known.
290 match cast_ty.kind() {
291 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
292 let reported = check.report_cast_to_unsized_type(fcx);
299 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
301 CastError::ErrorGuaranteed => {
302 // an error has already been reported
304 CastError::NeedDeref => {
305 let error_span = self.span;
306 let mut err = make_invalid_casting_error(
313 let cast_ty = fcx.ty_to_string(self.cast_ty);
316 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
318 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr_span) {
321 "dereference the expression",
322 format!("*{}", snippet),
323 Applicability::MaybeIncorrect,
326 err.span_help(self.expr_span, "dereference the expression with `*`");
330 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
331 let mut err = make_invalid_casting_error(
338 if self.cast_ty.is_integral() {
340 "cast through {} first",
342 CastError::NeedViaPtr => "a raw pointer",
343 CastError::NeedViaThinPtr => "a thin pointer",
350 CastError::NeedViaInt => {
351 make_invalid_casting_error(
359 "cast through {} first",
361 CastError::NeedViaInt => "an integer",
367 CastError::IllegalCast => {
368 make_invalid_casting_error(
377 CastError::DifferingKinds => {
378 make_invalid_casting_error(
385 .note("vtable kinds may not match")
388 CastError::CastToBool => {
390 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
392 if self.expr_ty.is_numeric() {
393 match fcx.tcx.sess.source_map().span_to_snippet(self.expr_span) {
397 "compare with zero instead",
398 format!("{snippet} != 0"),
399 Applicability::MachineApplicable,
403 err.span_help(self.span, "compare with zero instead");
407 err.span_label(self.span, "unsupported cast");
412 CastError::CastToChar => {
413 let mut err = type_error_struct!(
418 "only `u8` can be cast as `char`, not `{}`",
421 err.span_label(self.span, "invalid cast");
422 if self.expr_ty.is_numeric() {
423 if self.expr_ty == fcx.tcx.types.u32 {
424 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
425 Ok(snippet) => err.span_suggestion(
427 "try `char::from_u32` instead",
428 format!("char::from_u32({snippet})"),
429 Applicability::MachineApplicable,
432 Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
434 } else if self.expr_ty == fcx.tcx.types.i8 {
435 err.span_help(self.span, "try casting from `u8` instead");
437 err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
442 CastError::NonScalar => {
443 let mut err = type_error_struct!(
448 "non-primitive cast: `{}` as `{}`",
450 fcx.ty_to_string(self.cast_ty)
453 let mut sugg_mutref = false;
454 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
455 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind()
460 fcx.tcx.lifetimes.re_erased,
461 TypeAndMut { ty: expr_ty, mutbl },
469 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
470 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
471 && expr_mutbl == Mutability::Not
472 && mutbl == Mutability::Mut
478 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
494 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
501 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
503 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind()
508 fcx.tcx.lifetimes.re_erased,
509 TypeAndMut { ty: self.expr_ty, mutbl },
517 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
520 err.span_label(self.span, "invalid cast");
521 err.span_note(self.expr_span, "this reference is immutable");
522 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
523 } else if let Some((sugg, remove_cast)) = sugg {
524 err.span_label(self.span, "invalid cast");
530 .span_to_snippet(self.expr_span)
531 .map_or(false, |snip| snip.starts_with('('));
533 // Very crude check to see whether the expression must be wrapped
534 // in parentheses for the suggestion to work (issue #89497).
535 // Can/should be extended in the future.
537 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
539 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
541 suggestion[0].1 += "(";
542 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
546 self.expr_span.shrink_to_hi().to(self.cast_span),
551 err.multipart_suggestion_verbose(
552 "consider borrowing the value",
554 Applicability::MachineApplicable,
558 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
560 let mut label = true;
561 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
562 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
563 && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
565 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
566 // Erase regions to avoid panic in `prove_value` when calling
567 // `type_implements_trait`.
568 let ty = fcx.tcx.erase_regions(ty);
569 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
570 let expr_ty = fcx.tcx.erase_regions(expr_ty);
571 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
574 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
575 .must_apply_modulo_regions()
580 "consider using the `From` trait instead",
581 format!("{}::from({})", self.cast_ty, snippet),
582 Applicability::MaybeIncorrect,
586 let msg = "an `as` expression can only be used to convert between primitive \
587 types or to coerce to a specific trait object";
589 err.span_label(self.span, msg);
594 err.span_label(self.span, "invalid cast");
598 CastError::SizedUnsizedCast => {
599 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
604 expr_ty: self.expr_ty,
605 cast_ty: fcx.ty_to_string(self.cast_ty),
610 CastError::IntToFatCast(known_metadata) => {
611 let mut err = struct_span_err!(
615 "cannot cast `{}` to a pointer that {} wide",
616 fcx.ty_to_string(self.expr_ty),
617 if known_metadata.is_some() { "is" } else { "may be" }
623 "creating a `{}` requires both an address and {}",
625 known_metadata.unwrap_or("type-specific metadata"),
629 if fcx.tcx.sess.is_nightly_build() {
632 "consider casting this expression to `*const ()`, \
633 then using `core::ptr::from_raw_parts`",
639 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
640 let unknown_cast_to = match e {
641 CastError::UnknownCastPtrKind => true,
642 CastError::UnknownExprPtrKind => false,
645 let mut err = struct_span_err!(
647 if unknown_cast_to { self.cast_span } else { self.span },
649 "cannot cast {} a pointer of an unknown kind",
650 if unknown_cast_to { "to" } else { "from" }
653 err.span_label(self.cast_span, "needs more type information");
655 "the type information given here is insufficient to check whether \
656 the pointer cast is valid",
661 "the type information given here is insufficient to check whether \
662 the pointer cast is valid",
667 CastError::ForeignNonExhaustiveAdt => {
668 make_invalid_casting_error(
675 .note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
681 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
682 if let Some(reported) =
683 self.cast_ty.error_reported().or_else(|| self.expr_ty.error_reported())
688 let tstr = fcx.ty_to_string(self.cast_ty);
689 let mut err = type_error_struct!(
694 "cast to unsized type: `{}` as `{}`",
695 fcx.resolve_vars_if_possible(self.expr_ty),
698 match self.expr_ty.kind() {
699 ty::Ref(_, _, mt) => {
700 let mtstr = mt.prefix_str();
701 if self.cast_ty.is_trait() {
702 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
706 "try casting to a reference instead",
707 format!("&{}{}", mtstr, s),
708 Applicability::MachineApplicable,
712 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
713 err.span_help(self.cast_span, msg);
718 &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
719 err.span_help(self.span, msg);
722 ty::Adt(def, ..) if def.is_box() => {
723 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
727 "you can cast to a `Box` instead",
729 Applicability::MachineApplicable,
735 &format!("you might have meant `Box<{tstr}>`"),
741 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
747 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
748 let t_cast = self.cast_ty;
749 let t_expr = self.expr_ty;
751 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
752 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
753 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
755 ("", lint::builtin::TRIVIAL_CASTS)
757 fcx.tcx.struct_span_lint_hir(
763 "trivial {}cast: `{}` as `{}`",
765 fcx.ty_to_string(t_expr),
766 fcx.ty_to_string(t_cast)
771 "cast can be replaced by coercion; this might \
772 require {type_asc_or}a temporary variable"
778 #[instrument(skip(fcx), level = "debug")]
779 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
780 self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
781 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
783 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
785 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
786 && !self.cast_ty.has_infer_types()
788 self.report_cast_to_unsized_type(fcx);
789 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
790 // No sense in giving duplicate error messages
792 match self.try_coercion_cast(fcx) {
794 self.trivial_cast_lint(fcx);
795 debug!(" -> CoercionCast");
796 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
798 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
799 self.report_object_unsafe_cast(&fcx, did);
802 match self.do_check(fcx) {
804 debug!(" -> {:?}", k);
806 Err(e) => self.report_cast_error(fcx, e),
813 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
814 let violations = fcx.tcx.object_safety_violations(did);
815 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
816 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
820 /// Checks a cast, and report an error if one exists. In some cases, this
821 /// can return Ok and create type errors in the fcx rather than returning
822 /// directly. coercion-cast is handled in check instead of here.
823 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
824 use rustc_middle::ty::cast::CastTy::*;
825 use rustc_middle::ty::cast::IntTy::*;
827 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
829 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
830 // Function item types may need to be reified before casts.
831 (None, Some(t_cast)) => {
832 match *self.expr_ty.kind() {
834 // Attempt a coercion to a fn pointer type.
835 let f = fcx.normalize_associated_types_in(
837 self.expr_ty.fn_sig(fcx.tcx),
839 let res = fcx.try_coerce(
842 fcx.tcx.mk_fn_ptr(f),
846 if let Err(TypeError::IntrinsicCast) = res {
847 return Err(CastError::IllegalCast);
850 return Err(CastError::NonScalar);
854 // Special case some errors for references, and check for
855 // array-ptr-casts. `Ref` is not a CastTy because the cast
856 // is split into a coercion to a pointer type, followed by
858 ty::Ref(_, inner_ty, mutbl) => {
859 return match t_cast {
860 Int(_) | Float => match *inner_ty.kind() {
864 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
865 Err(CastError::NeedDeref)
867 _ => Err(CastError::NeedViaPtr),
871 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
873 _ => Err(CastError::NonScalar),
876 _ => return Err(CastError::NonScalar),
879 _ => return Err(CastError::NonScalar),
882 if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
883 if adt_def.did().krate != LOCAL_CRATE {
884 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
885 return Err(CastError::ForeignNonExhaustiveAdt);
890 match (t_from, t_cast) {
891 // These types have invariants! can't cast into them.
892 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
895 (_, Int(Bool)) => Err(CastError::CastToBool),
898 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
899 (_, Int(Char)) => Err(CastError::CastToChar),
902 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
904 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
905 Err(CastError::IllegalCast)
909 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
912 (Ptr(m_expr), Int(t_c)) => {
913 self.lossy_provenance_ptr2int_lint(fcx, t_c);
914 self.check_ptr_addr_cast(fcx, m_expr)
917 // FIXME(#95489): there should eventually be a lint for these casts
918 Ok(CastKind::FnPtrAddrCast)
921 (Int(_), Ptr(mt)) => {
922 self.fuzzy_provenance_int2ptr_lint(fcx);
923 self.check_addr_ptr_cast(fcx, mt)
926 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
929 (Int(CEnum), Int(_)) => {
930 self.cenum_impl_drop_lint(fcx);
931 Ok(CastKind::EnumCast)
933 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
935 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
937 // FIXME(dyn-star): this needs more conditions...
938 (_, DynStar) => Ok(CastKind::DynStarCast),
940 // FIXME(dyn-star): do we want to allow dyn* upcasting or other casts?
941 (DynStar, _) => Err(CastError::IllegalCast),
945 fn check_ptr_ptr_cast(
947 fcx: &FnCtxt<'a, 'tcx>,
948 m_expr: ty::TypeAndMut<'tcx>,
949 m_cast: ty::TypeAndMut<'tcx>,
950 ) -> Result<CastKind, CastError> {
951 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
952 // ptr-ptr cast. vtables must match.
954 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
955 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
957 let Some(cast_kind) = cast_kind else {
958 // We can't cast if target pointer kind is unknown
959 return Err(CastError::UnknownCastPtrKind);
962 // Cast to thin pointer is OK
963 if cast_kind == PointerKind::Thin {
964 return Ok(CastKind::PtrPtrCast);
967 let Some(expr_kind) = expr_kind else {
968 // We can't cast to fat pointer if source pointer kind is unknown
969 return Err(CastError::UnknownExprPtrKind);
972 // thin -> fat? report invalid cast (don't complain about vtable kinds)
973 if expr_kind == PointerKind::Thin {
974 return Err(CastError::SizedUnsizedCast);
977 // vtable kinds must match
978 if cast_kind == expr_kind {
979 Ok(CastKind::PtrPtrCast)
981 Err(CastError::DifferingKinds)
985 fn check_fptr_ptr_cast(
987 fcx: &FnCtxt<'a, 'tcx>,
988 m_cast: ty::TypeAndMut<'tcx>,
989 ) -> Result<CastKind, CastError> {
990 // fptr-ptr cast. must be to thin ptr
992 match fcx.pointer_kind(m_cast.ty, self.span)? {
993 None => Err(CastError::UnknownCastPtrKind),
994 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
995 _ => Err(CastError::IllegalCast),
999 fn check_ptr_addr_cast(
1001 fcx: &FnCtxt<'a, 'tcx>,
1002 m_expr: ty::TypeAndMut<'tcx>,
1003 ) -> Result<CastKind, CastError> {
1004 // ptr-addr cast. must be from thin ptr
1006 match fcx.pointer_kind(m_expr.ty, self.span)? {
1007 None => Err(CastError::UnknownExprPtrKind),
1008 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1009 _ => Err(CastError::NeedViaThinPtr),
1015 fcx: &FnCtxt<'a, 'tcx>,
1016 m_expr: ty::TypeAndMut<'tcx>,
1017 m_cast: ty::TypeAndMut<'tcx>,
1018 ) -> Result<CastKind, CastError> {
1019 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1020 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
1021 if let ty::Array(ety, _) = m_expr.ty.kind() {
1022 // Due to the limitations of LLVM global constants,
1023 // region pointers end up pointing at copies of
1024 // vector elements instead of the original values.
1025 // To allow raw pointers to work correctly, we
1026 // need to special-case obtaining a raw pointer
1027 // from a region pointer to a vector.
1029 // Coerce to a raw pointer so that we generate AddressOf in MIR.
1030 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
1031 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1032 .unwrap_or_else(|_| {
1034 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1040 // this will report a type mismatch if needed
1041 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1042 return Ok(CastKind::ArrayPtrCast);
1046 Err(CastError::IllegalCast)
1049 fn check_addr_ptr_cast(
1051 fcx: &FnCtxt<'a, 'tcx>,
1052 m_cast: TypeAndMut<'tcx>,
1053 ) -> Result<CastKind, CastError> {
1054 // ptr-addr cast. pointer must be thin.
1055 match fcx.pointer_kind(m_cast.ty, self.span)? {
1056 None => Err(CastError::UnknownCastPtrKind),
1057 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1058 Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
1059 Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
1061 PointerKind::OfProjection(_)
1062 | PointerKind::OfOpaque(_, _)
1063 | PointerKind::OfParam(_),
1064 ) => Err(CastError::IntToFatCast(None)),
1068 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1069 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1071 Err(err) => Err(err),
1075 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1076 if let ty::Adt(d, _) = self.expr_ty.kind()
1077 && d.has_dtor(fcx.tcx)
1079 fcx.tcx.struct_span_lint_hir(
1080 lint::builtin::CENUM_IMPL_DROP_CAST,
1084 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1085 self.expr_ty, self.cast_ty
1094 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1095 fcx.tcx.struct_span_lint_hir(
1096 lint::builtin::LOSSY_PROVENANCE_CASTS,
1100 "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1101 self.expr_ty, self.cast_ty
1104 let msg = "use `.addr()` to obtain the address of a pointer";
1106 let expr_prec = self.expr.precedence().order();
1107 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1109 let scalar_cast = match t_c {
1110 ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1111 _ => format!(" as {}", self.cast_ty),
1114 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1117 let suggestions = vec![
1118 (self.expr_span.shrink_to_lo(), String::from("(")),
1119 (cast_span, format!(").addr(){scalar_cast}")),
1122 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1124 lint.span_suggestion(
1127 format!(".addr(){scalar_cast}"),
1128 Applicability::MaybeIncorrect,
1133 "if you can't comply with strict provenance and need to expose the pointer \
1134 provenance you can use `.expose_addr()` instead"
1142 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1143 fcx.tcx.struct_span_lint_hir(
1144 lint::builtin::FUZZY_PROVENANCE_CASTS,
1148 "strict provenance disallows casting integer `{}` to pointer `{}`",
1149 self.expr_ty, self.cast_ty
1152 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1153 let suggestions = vec![
1154 (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1155 (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1158 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1160 "if you can't comply with strict provenance and don't have a pointer with \
1161 the correct provenance you can use `std::ptr::from_exposed_addr()` instead"