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;
35 use crate::type_error_struct;
36 use crate::util::common::ErrorReported;
37 use rustc::middle::lang_items;
38 use rustc::session::Session;
40 use rustc::traits::error_reporting::report_object_safety_error;
41 use rustc::traits::object_safety_violations;
42 use rustc::ty::adjustment::AllowTwoPhase;
43 use rustc::ty::cast::{CastKind, CastTy};
44 use rustc::ty::error::TypeError;
45 use rustc::ty::subst::SubstsRef;
46 use rustc::ty::{self, Ty, TypeAndMut, TypeFoldable};
47 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
52 use rustc_error_codes::*;
54 /// Reifies a cast check to be checked once we have full type information for
55 /// a function context.
56 pub struct CastCheck<'tcx> {
57 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>>, ErrorReported> {
91 debug!("pointer_kind({:?}, {:?})", t, span);
93 let t = self.resolve_vars_if_possible(&t);
95 if t.references_error() {
96 return Err(ErrorReported);
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.expect_ty(), 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::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
123 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
124 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
125 // Insufficient type information.
126 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
134 | ty::GeneratorWitness(..)
146 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
147 return Err(ErrorReported);
153 #[derive(Copy, Clone)]
160 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
172 impl From<ErrorReported> for CastError {
173 fn from(ErrorReported: ErrorReported) -> Self {
174 CastError::ErrorReported
178 fn make_invalid_casting_error<'a, 'tcx>(
183 fcx: &FnCtxt<'a, 'tcx>,
184 ) -> DiagnosticBuilder<'a> {
190 "casting `{}` as `{}` is invalid",
191 fcx.ty_to_string(expr_ty),
192 fcx.ty_to_string(cast_ty)
196 impl<'a, 'tcx> CastCheck<'tcx> {
198 fcx: &FnCtxt<'a, 'tcx>,
199 expr: &'tcx hir::Expr<'tcx>,
204 ) -> Result<CastCheck<'tcx>, ErrorReported> {
205 let check = CastCheck { expr, expr_ty, cast_ty, cast_span, span };
207 // For better error messages, check for some obviously unsized
208 // cases now. We do a more thorough check at the end, once
209 // inference is more completely known.
211 ty::Dynamic(..) | ty::Slice(..) => {
212 check.report_cast_to_unsized_type(fcx);
219 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
221 CastError::ErrorReported => {
222 // an error has already been reported
224 CastError::NeedDeref => {
225 let error_span = self.span;
226 let mut err = make_invalid_casting_error(
233 let cast_ty = fcx.ty_to_string(self.cast_ty);
236 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
238 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
241 "dereference the expression",
242 format!("*{}", snippet),
243 Applicability::MaybeIncorrect,
246 err.span_help(self.expr.span, "dereference the expression with `*`");
250 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
251 let mut err = make_invalid_casting_error(
258 if self.cast_ty.is_integral() {
260 "cast through {} first",
262 CastError::NeedViaPtr => "a raw pointer",
263 CastError::NeedViaThinPtr => "a thin pointer",
270 CastError::NeedViaInt => {
271 make_invalid_casting_error(
279 "cast through {} first",
281 CastError::NeedViaInt => "an integer",
287 CastError::IllegalCast => {
288 make_invalid_casting_error(
297 CastError::DifferingKinds => {
298 make_invalid_casting_error(
305 .note("vtable kinds may not match")
308 CastError::CastToBool => {
310 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
312 if self.expr_ty.is_numeric() {
313 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
317 "compare with zero instead",
318 format!("{} != 0", snippet),
319 Applicability::MachineApplicable,
323 err.span_help(self.span, "compare with zero instead");
327 err.span_label(self.span, "unsupported cast");
332 CastError::CastToChar => {
338 "only `u8` can be cast as `char`, not `{}`",
343 CastError::NonScalar => {
349 "non-primitive cast: `{}` as `{}`",
351 fcx.ty_to_string(self.cast_ty)
354 "an `as` expression can only be used to convert between \
355 primitive types. Consider using the `From` trait",
359 CastError::SizedUnsizedCast => {
360 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
361 SizedUnsizedCastError::new(
365 fcx.ty_to_string(self.cast_ty),
370 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
371 let unknown_cast_to = match e {
372 CastError::UnknownCastPtrKind => true,
373 CastError::UnknownExprPtrKind => false,
376 let mut err = struct_span_err!(
380 "cannot cast {} a pointer of an unknown kind",
381 if unknown_cast_to { "to" } else { "from" }
384 "the type information given here is insufficient to check whether \
385 the pointer cast is valid",
388 err.span_suggestion_short(
390 "consider giving more type information",
392 Applicability::Unspecified,
400 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
401 if self.cast_ty.references_error() || self.expr_ty.references_error() {
405 let tstr = fcx.ty_to_string(self.cast_ty);
406 let mut err = type_error_struct!(
411 "cast to unsized type: `{}` as `{}`",
412 fcx.resolve_vars_if_possible(&self.expr_ty),
415 match self.expr_ty.kind {
416 ty::Ref(_, _, mt) => {
417 let mtstr = mt.prefix_str();
418 if self.cast_ty.is_trait() {
419 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
423 "try casting to a reference instead",
424 format!("&{}{}", mtstr, s),
425 Applicability::MachineApplicable,
429 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
430 err.span_help(self.cast_span, msg);
435 "consider using an implicit coercion to `&{}{}` instead",
438 err.span_help(self.span, msg);
441 ty::Adt(def, ..) if def.is_box() => {
442 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
446 "try casting to a `Box` instead",
447 format!("Box<{}>", s),
448 Applicability::MachineApplicable,
452 err.span_help(self.cast_span, &format!("did you mean `Box<{}>`?", tstr));
457 err.span_help(self.expr.span, "consider using a box or reference as appropriate");
463 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
464 let t_cast = self.cast_ty;
465 let t_expr = self.expr_ty;
467 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
468 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
469 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
471 ("", lint::builtin::TRIVIAL_CASTS)
473 let mut err = fcx.tcx.struct_span_lint_hir(
478 "trivial {}cast: `{}` as `{}`",
480 fcx.ty_to_string(t_expr),
481 fcx.ty_to_string(t_cast)
485 "cast can be replaced by coercion; this might \
486 require {}a temporary variable",
492 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
493 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
494 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
496 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
498 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
499 self.report_cast_to_unsized_type(fcx);
500 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
501 // No sense in giving duplicate error messages
503 match self.try_coercion_cast(fcx) {
505 self.trivial_cast_lint(fcx);
506 debug!(" -> CoercionCast");
507 fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
509 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
510 self.report_object_unsafe_cast(&fcx, did);
513 match self.do_check(fcx) {
515 debug!(" -> {:?}", k);
517 Err(e) => self.report_cast_error(fcx, e),
524 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
525 let violations = object_safety_violations(fcx.tcx, did);
526 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
527 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
531 /// Checks a cast, and report an error if one exists. In some cases, this
532 /// can return Ok and create type errors in the fcx rather than returning
533 /// directly. coercion-cast is handled in check instead of here.
534 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
535 use rustc::ty::cast::CastTy::*;
536 use rustc::ty::cast::IntTy::*;
538 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
540 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
541 // Function item types may need to be reified before casts.
542 (None, Some(t_cast)) => {
543 match self.expr_ty.kind {
545 // Attempt a coercion to a fn pointer type.
546 let f = self.expr_ty.fn_sig(fcx.tcx);
547 let res = fcx.try_coerce(
550 fcx.tcx.mk_fn_ptr(f),
553 if let Err(TypeError::IntrinsicCast) = res {
554 return Err(CastError::IllegalCast);
557 return Err(CastError::NonScalar);
561 // Special case some errors for references, and check for
562 // array-ptr-casts. `Ref` is not a CastTy because the cast
563 // is split into a coercion to a pointer type, followed by
565 ty::Ref(_, inner_ty, mutbl) => {
566 return match t_cast {
567 Int(_) | Float => match inner_ty.kind {
571 | ty::Infer(ty::InferTy::IntVar(_))
572 | ty::Infer(ty::InferTy::FloatVar(_)) => Err(CastError::NeedDeref),
573 _ => Err(CastError::NeedViaPtr),
577 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
579 _ => Err(CastError::NonScalar),
582 _ => return Err(CastError::NonScalar),
585 _ => return Err(CastError::NonScalar),
588 match (t_from, t_cast) {
589 // These types have invariants! can't cast into them.
590 (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
593 (_, Int(Bool)) => Err(CastError::CastToBool),
596 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
597 (_, Int(Char)) => Err(CastError::CastToChar),
600 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float) => {
601 Err(CastError::NeedViaInt)
605 | (Int(CEnum), Ptr(_))
606 | (Int(Char), Ptr(_))
609 | (Float, Ptr(_)) => Err(CastError::IllegalCast),
612 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
613 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
614 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
617 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
618 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
621 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
622 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
624 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
625 Ok(CastKind::NumericCast)
630 fn check_ptr_ptr_cast(
632 fcx: &FnCtxt<'a, 'tcx>,
633 m_expr: ty::TypeAndMut<'tcx>,
634 m_cast: ty::TypeAndMut<'tcx>,
635 ) -> Result<CastKind, CastError> {
636 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
637 // ptr-ptr cast. vtables must match.
639 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
640 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
642 let cast_kind = match cast_kind {
643 // We can't cast if target pointer kind is unknown
644 None => return Err(CastError::UnknownCastPtrKind),
645 Some(cast_kind) => cast_kind,
648 // Cast to thin pointer is OK
649 if cast_kind == PointerKind::Thin {
650 return Ok(CastKind::PtrPtrCast);
653 let expr_kind = match expr_kind {
654 // We can't cast to fat pointer if source pointer kind is unknown
655 None => return Err(CastError::UnknownExprPtrKind),
656 Some(expr_kind) => expr_kind,
659 // thin -> fat? report invalid cast (don't complain about vtable kinds)
660 if expr_kind == PointerKind::Thin {
661 return Err(CastError::SizedUnsizedCast);
664 // vtable kinds must match
665 if cast_kind == expr_kind {
666 Ok(CastKind::PtrPtrCast)
668 Err(CastError::DifferingKinds)
672 fn check_fptr_ptr_cast(
674 fcx: &FnCtxt<'a, 'tcx>,
675 m_cast: ty::TypeAndMut<'tcx>,
676 ) -> Result<CastKind, CastError> {
677 // fptr-ptr cast. must be to thin ptr
679 match fcx.pointer_kind(m_cast.ty, self.span)? {
680 None => Err(CastError::UnknownCastPtrKind),
681 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
682 _ => Err(CastError::IllegalCast),
686 fn check_ptr_addr_cast(
688 fcx: &FnCtxt<'a, 'tcx>,
689 m_expr: ty::TypeAndMut<'tcx>,
690 ) -> Result<CastKind, CastError> {
691 // ptr-addr cast. must be from thin ptr
693 match fcx.pointer_kind(m_expr.ty, self.span)? {
694 None => Err(CastError::UnknownExprPtrKind),
695 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
696 _ => Err(CastError::NeedViaThinPtr),
702 fcx: &FnCtxt<'a, 'tcx>,
703 m_expr: ty::TypeAndMut<'tcx>,
704 m_cast: ty::TypeAndMut<'tcx>,
705 ) -> Result<CastKind, CastError> {
708 if m_expr.mutbl == hir::Mutability::Not && m_cast.mutbl == hir::Mutability::Not {
709 if let ty::Array(ety, _) = m_expr.ty.kind {
710 // Due to the limitations of LLVM global constants,
711 // region pointers end up pointing at copies of
712 // vector elements instead of the original values.
713 // To allow raw pointers to work correctly, we
714 // need to special-case obtaining a raw pointer
715 // from a region pointer to a vector.
717 // Coerce to a raw pointer so that we generate AddressOf in MIR.
718 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
719 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
720 .unwrap_or_else(|_| bug!(
721 "could not cast from reference to array to pointer to array ({:?} to {:?})",
726 // this will report a type mismatch if needed
727 fcx.demand_eqtype(self.span, ety, m_cast.ty);
728 return Ok(CastKind::ArrayPtrCast);
732 Err(CastError::IllegalCast)
735 fn check_addr_ptr_cast(
737 fcx: &FnCtxt<'a, 'tcx>,
738 m_cast: TypeAndMut<'tcx>,
739 ) -> Result<CastKind, CastError> {
740 // ptr-addr cast. pointer must be thin.
741 match fcx.pointer_kind(m_cast.ty, self.span)? {
742 None => Err(CastError::UnknownCastPtrKind),
743 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
744 _ => Err(CastError::IllegalCast),
748 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
749 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
751 Err(err) => Err(err),
756 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
757 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
758 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
759 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)