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, ErrorReported};
37 use rustc_hir::lang_items::LangItem;
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, TypeFoldable};
43 use rustc_session::lint;
44 use rustc_session::Session;
45 use rustc_span::symbol::sym;
47 use rustc_trait_selection::traits;
48 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
50 /// Reifies a cast check to be checked once we have full type information for
51 /// a function context.
52 pub struct CastCheck<'tcx> {
53 expr: &'tcx hir::Expr<'tcx>,
60 /// The kind of pointer and associated metadata (thin, length or vtable) - we
61 /// only allow casts between fat pointers if their metadata have the same
63 #[derive(Copy, Clone, PartialEq, Eq)]
64 enum PointerKind<'tcx> {
65 /// No metadata attached, ie pointer to sized type or foreign type
68 Vtable(Option<DefId>),
71 /// The unsize info of this projection
72 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
73 /// The unsize info of this opaque ty
74 OfOpaque(DefId, SubstsRef<'tcx>),
75 /// The unsize info of this parameter
76 OfParam(&'tcx ty::ParamTy),
79 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
80 /// Returns the kind of unsize information of t, or None
86 ) -> Result<Option<PointerKind<'tcx>>, ErrorReported> {
87 debug!("pointer_kind({:?}, {:?})", t, span);
89 let t = self.resolve_vars_if_possible(t);
91 if t.references_error() {
92 return Err(ErrorReported);
95 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
96 return Ok(Some(PointerKind::Thin));
100 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
101 ty::Dynamic(ref tty, ..) => Some(PointerKind::Vtable(tty.principal_def_id())),
102 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
103 None => Some(PointerKind::Thin),
105 let field_ty = self.field_ty(span, f, substs);
106 self.pointer_kind(field_ty, span)?
109 ty::Tuple(fields) => match fields.last() {
110 None => Some(PointerKind::Thin),
111 Some(f) => self.pointer_kind(f.expect_ty(), span)?,
114 // Pointers to foreign types are thin, despite being unsized
115 ty::Foreign(..) => Some(PointerKind::Thin),
116 // We should really try to normalize here.
117 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
118 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
119 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
120 // Insufficient type information.
121 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
129 | ty::GeneratorWitness(..)
141 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
142 return Err(ErrorReported);
148 #[derive(Copy, Clone)]
155 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
167 impl From<ErrorReported> for CastError {
168 fn from(ErrorReported: ErrorReported) -> Self {
169 CastError::ErrorReported
173 fn make_invalid_casting_error<'a, 'tcx>(
178 fcx: &FnCtxt<'a, 'tcx>,
179 ) -> DiagnosticBuilder<'a> {
185 "casting `{}` as `{}` is invalid",
186 fcx.ty_to_string(expr_ty),
187 fcx.ty_to_string(cast_ty)
191 impl<'a, 'tcx> CastCheck<'tcx> {
193 fcx: &FnCtxt<'a, 'tcx>,
194 expr: &'tcx hir::Expr<'tcx>,
199 ) -> Result<CastCheck<'tcx>, ErrorReported> {
200 let check = CastCheck { expr, expr_ty, cast_ty, cast_span, span };
202 // For better error messages, check for some obviously unsized
203 // cases now. We do a more thorough check at the end, once
204 // inference is more completely known.
205 match cast_ty.kind() {
206 ty::Dynamic(..) | ty::Slice(..) => {
207 check.report_cast_to_unsized_type(fcx);
214 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
216 CastError::ErrorReported => {
217 // an error has already been reported
219 CastError::NeedDeref => {
220 let error_span = self.span;
221 let mut err = make_invalid_casting_error(
228 let cast_ty = fcx.ty_to_string(self.cast_ty);
231 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
233 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
236 "dereference the expression",
237 format!("*{}", snippet),
238 Applicability::MaybeIncorrect,
241 err.span_help(self.expr.span, "dereference the expression with `*`");
245 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
246 let mut err = make_invalid_casting_error(
253 if self.cast_ty.is_integral() {
255 "cast through {} first",
257 CastError::NeedViaPtr => "a raw pointer",
258 CastError::NeedViaThinPtr => "a thin pointer",
265 CastError::NeedViaInt => {
266 make_invalid_casting_error(
274 "cast through {} first",
276 CastError::NeedViaInt => "an integer",
282 CastError::IllegalCast => {
283 make_invalid_casting_error(
292 CastError::DifferingKinds => {
293 make_invalid_casting_error(
300 .note("vtable kinds may not match")
303 CastError::CastToBool => {
305 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
307 if self.expr_ty.is_numeric() {
308 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
312 "compare with zero instead",
313 format!("{} != 0", snippet),
314 Applicability::MachineApplicable,
318 err.span_help(self.span, "compare with zero instead");
322 err.span_label(self.span, "unsupported cast");
327 CastError::CastToChar => {
333 "only `u8` can be cast as `char`, not `{}`",
336 .span_label(self.span, "invalid cast")
339 CastError::NonScalar => {
340 let mut err = type_error_struct!(
345 "non-primitive cast: `{}` as `{}`",
347 fcx.ty_to_string(self.cast_ty)
350 if let ty::Ref(reg, _, mutbl) = *self.cast_ty.kind() {
354 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
360 sugg = Some(format!("&{}", mutbl.prefix_str()));
362 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind() {
367 &ty::RegionKind::ReErased,
368 TypeAndMut { ty: self.expr_ty, mutbl },
375 sugg = Some(format!("&{}", mutbl.prefix_str()));
378 if let Some(sugg) = sugg {
379 err.span_label(self.span, "invalid cast");
380 err.span_suggestion_verbose(
381 self.expr.span.shrink_to_lo(),
382 "borrow the value for the cast to be valid",
384 Applicability::MachineApplicable,
388 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
390 let mut label = true;
391 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
392 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
393 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::from_trait) {
394 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
395 // Erase regions to avoid panic in `prove_value` when calling
396 // `type_implements_trait`.
397 let ty = fcx.tcx.erase_regions(ty);
398 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
399 let expr_ty = fcx.tcx.erase_regions(expr_ty);
400 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
401 // Check for infer types because cases like `Option<{integer}>` would
403 if !expr_ty.has_infer_types()
404 && !ty.has_infer_types()
405 && fcx.tcx.type_implements_trait((
415 "consider using the `From` trait instead",
416 format!("{}::from({})", self.cast_ty, snippet),
417 Applicability::MaybeIncorrect,
422 let msg = "an `as` expression can only be used to convert between primitive \
423 types or to coerce to a specific trait object";
425 err.span_label(self.span, msg);
430 err.span_label(self.span, "invalid cast");
434 CastError::SizedUnsizedCast => {
435 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
440 expr_ty: self.expr_ty,
441 cast_ty: fcx.ty_to_string(self.cast_ty),
446 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
447 let unknown_cast_to = match e {
448 CastError::UnknownCastPtrKind => true,
449 CastError::UnknownExprPtrKind => false,
452 let mut err = struct_span_err!(
454 if unknown_cast_to { self.cast_span } else { self.span },
456 "cannot cast {} a pointer of an unknown kind",
457 if unknown_cast_to { "to" } else { "from" }
460 err.span_label(self.cast_span, "needs more type information");
462 "the type information given here is insufficient to check whether \
463 the pointer cast is valid",
468 "the type information given here is insufficient to check whether \
469 the pointer cast is valid",
477 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
478 if self.cast_ty.references_error() || self.expr_ty.references_error() {
482 let tstr = fcx.ty_to_string(self.cast_ty);
483 let mut err = type_error_struct!(
488 "cast to unsized type: `{}` as `{}`",
489 fcx.resolve_vars_if_possible(self.expr_ty),
492 match self.expr_ty.kind() {
493 ty::Ref(_, _, mt) => {
494 let mtstr = mt.prefix_str();
495 if self.cast_ty.is_trait() {
496 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
500 "try casting to a reference instead",
501 format!("&{}{}", mtstr, s),
502 Applicability::MachineApplicable,
506 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
507 err.span_help(self.cast_span, msg);
512 "consider using an implicit coercion to `&{}{}` instead",
515 err.span_help(self.span, msg);
518 ty::Adt(def, ..) if def.is_box() => {
519 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
523 "you can cast to a `Box` instead",
524 format!("Box<{}>", s),
525 Applicability::MachineApplicable,
531 &format!("you might have meant `Box<{}>`", tstr),
537 err.span_help(self.expr.span, "consider using a box or reference as appropriate");
543 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
544 let t_cast = self.cast_ty;
545 let t_expr = self.expr_ty;
547 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
548 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
549 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
551 ("", lint::builtin::TRIVIAL_CASTS)
553 fcx.tcx.struct_span_lint_hir(lint, self.expr.hir_id, self.span, |err| {
555 "trivial {}cast: `{}` as `{}`",
557 fcx.ty_to_string(t_expr),
558 fcx.ty_to_string(t_cast)
561 "cast can be replaced by coercion; this might \
562 require {}a temporary variable",
569 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
570 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
571 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
573 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
575 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
576 self.report_cast_to_unsized_type(fcx);
577 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
578 // No sense in giving duplicate error messages
580 match self.try_coercion_cast(fcx) {
582 self.trivial_cast_lint(fcx);
583 debug!(" -> CoercionCast");
584 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
586 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
587 self.report_object_unsafe_cast(&fcx, did);
590 match self.do_check(fcx) {
592 debug!(" -> {:?}", k);
594 Err(e) => self.report_cast_error(fcx, e),
601 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
602 let violations = fcx.tcx.object_safety_violations(did);
603 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
604 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
608 /// Checks a cast, and report an error if one exists. In some cases, this
609 /// can return Ok and create type errors in the fcx rather than returning
610 /// directly. coercion-cast is handled in check instead of here.
611 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
612 use rustc_middle::ty::cast::CastTy::*;
613 use rustc_middle::ty::cast::IntTy::*;
615 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
617 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
618 // Function item types may need to be reified before casts.
619 (None, Some(t_cast)) => {
620 match *self.expr_ty.kind() {
622 // Attempt a coercion to a fn pointer type.
623 let f = fcx.normalize_associated_types_in(
625 self.expr_ty.fn_sig(fcx.tcx),
627 let res = fcx.try_coerce(
630 fcx.tcx.mk_fn_ptr(f),
633 if let Err(TypeError::IntrinsicCast) = res {
634 return Err(CastError::IllegalCast);
637 return Err(CastError::NonScalar);
641 // Special case some errors for references, and check for
642 // array-ptr-casts. `Ref` is not a CastTy because the cast
643 // is split into a coercion to a pointer type, followed by
645 ty::Ref(_, inner_ty, mutbl) => {
646 return match t_cast {
647 Int(_) | Float => match *inner_ty.kind() {
651 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
652 Err(CastError::NeedDeref)
654 _ => Err(CastError::NeedViaPtr),
658 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
660 _ => Err(CastError::NonScalar),
663 _ => return Err(CastError::NonScalar),
666 _ => return Err(CastError::NonScalar),
669 match (t_from, t_cast) {
670 // These types have invariants! can't cast into them.
671 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
674 (_, Int(Bool)) => Err(CastError::CastToBool),
677 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
678 (_, Int(Char)) => Err(CastError::CastToChar),
681 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
683 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
684 Err(CastError::IllegalCast)
688 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
689 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
690 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
693 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
694 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
697 (Int(CEnum), Int(_)) => {
698 self.cenum_impl_drop_lint(fcx);
699 Ok(CastKind::EnumCast)
701 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
703 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
707 fn check_ptr_ptr_cast(
709 fcx: &FnCtxt<'a, 'tcx>,
710 m_expr: ty::TypeAndMut<'tcx>,
711 m_cast: ty::TypeAndMut<'tcx>,
712 ) -> Result<CastKind, CastError> {
713 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
714 // ptr-ptr cast. vtables must match.
716 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
717 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
719 let cast_kind = match cast_kind {
720 // We can't cast if target pointer kind is unknown
721 None => return Err(CastError::UnknownCastPtrKind),
722 Some(cast_kind) => cast_kind,
725 // Cast to thin pointer is OK
726 if cast_kind == PointerKind::Thin {
727 return Ok(CastKind::PtrPtrCast);
730 let expr_kind = match expr_kind {
731 // We can't cast to fat pointer if source pointer kind is unknown
732 None => return Err(CastError::UnknownExprPtrKind),
733 Some(expr_kind) => expr_kind,
736 // thin -> fat? report invalid cast (don't complain about vtable kinds)
737 if expr_kind == PointerKind::Thin {
738 return Err(CastError::SizedUnsizedCast);
741 // vtable kinds must match
742 if cast_kind == expr_kind {
743 Ok(CastKind::PtrPtrCast)
745 Err(CastError::DifferingKinds)
749 fn check_fptr_ptr_cast(
751 fcx: &FnCtxt<'a, 'tcx>,
752 m_cast: ty::TypeAndMut<'tcx>,
753 ) -> Result<CastKind, CastError> {
754 // fptr-ptr cast. must be to thin ptr
756 match fcx.pointer_kind(m_cast.ty, self.span)? {
757 None => Err(CastError::UnknownCastPtrKind),
758 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
759 _ => Err(CastError::IllegalCast),
763 fn check_ptr_addr_cast(
765 fcx: &FnCtxt<'a, 'tcx>,
766 m_expr: ty::TypeAndMut<'tcx>,
767 ) -> Result<CastKind, CastError> {
768 // ptr-addr cast. must be from thin ptr
770 match fcx.pointer_kind(m_expr.ty, self.span)? {
771 None => Err(CastError::UnknownExprPtrKind),
772 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
773 _ => Err(CastError::NeedViaThinPtr),
779 fcx: &FnCtxt<'a, 'tcx>,
780 m_expr: ty::TypeAndMut<'tcx>,
781 m_cast: ty::TypeAndMut<'tcx>,
782 ) -> Result<CastKind, CastError> {
783 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
784 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
785 if let ty::Array(ety, _) = m_expr.ty.kind() {
786 // Due to the limitations of LLVM global constants,
787 // region pointers end up pointing at copies of
788 // vector elements instead of the original values.
789 // To allow raw pointers to work correctly, we
790 // need to special-case obtaining a raw pointer
791 // from a region pointer to a vector.
793 // Coerce to a raw pointer so that we generate AddressOf in MIR.
794 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
795 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
796 .unwrap_or_else(|_| {
798 "could not cast from reference to array to pointer to array ({:?} to {:?})",
804 // this will report a type mismatch if needed
805 fcx.demand_eqtype(self.span, ety, m_cast.ty);
806 return Ok(CastKind::ArrayPtrCast);
810 Err(CastError::IllegalCast)
813 fn check_addr_ptr_cast(
815 fcx: &FnCtxt<'a, 'tcx>,
816 m_cast: TypeAndMut<'tcx>,
817 ) -> Result<CastKind, CastError> {
818 // ptr-addr cast. pointer must be thin.
819 match fcx.pointer_kind(m_cast.ty, self.span)? {
820 None => Err(CastError::UnknownCastPtrKind),
821 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
822 _ => Err(CastError::IllegalCast),
826 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
827 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
829 Err(err) => Err(err),
833 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
834 if let ty::Adt(d, _) = self.expr_ty.kind() {
835 if d.has_dtor(fcx.tcx) {
836 fcx.tcx.struct_span_lint_hir(
837 lint::builtin::CENUM_IMPL_DROP_CAST,
842 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
843 self.expr_ty, self.cast_ty
853 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
854 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
855 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
856 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)