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::util::common::ErrorReported;
36 use errors::{Applicability, DiagnosticBuilder};
37 use rustc::middle::lang_items;
38 use rustc::session::Session;
40 use rustc::traits::error_reporting::report_object_safety_error;
41 use rustc::ty::adjustment::AllowTwoPhase;
42 use rustc::ty::cast::{CastKind, CastTy};
43 use rustc::ty::error::TypeError;
44 use rustc::ty::subst::SubstsRef;
45 use rustc::ty::{self, Ty, TypeAndMut, TypeFoldable};
50 use rustc_error_codes::*;
52 /// Reifies a cast check to be checked once we have full type information for
53 /// a function context.
54 pub struct CastCheck<'tcx> {
55 expr: &'tcx hir::Expr<'tcx>,
62 /// The kind of pointer and associated metadata (thin, length or vtable) - we
63 /// only allow casts between fat pointers if their metadata have the same
65 #[derive(Copy, Clone, PartialEq, Eq)]
66 enum PointerKind<'tcx> {
67 /// No metadata attached, ie pointer to sized type or foreign type
70 Vtable(Option<DefId>),
73 /// The unsize info of this projection
74 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
75 /// The unsize info of this opaque ty
76 OfOpaque(DefId, SubstsRef<'tcx>),
77 /// The unsize info of this parameter
78 OfParam(&'tcx ty::ParamTy),
81 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
82 /// Returns the kind of unsize information of t, or None
88 ) -> Result<Option<PointerKind<'tcx>>, ErrorReported> {
89 debug!("pointer_kind({:?}, {:?})", t, span);
91 let t = self.resolve_vars_if_possible(&t);
93 if t.references_error() {
94 return Err(ErrorReported);
97 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
98 return Ok(Some(PointerKind::Thin));
102 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
103 ty::Dynamic(ref tty, ..) => Some(PointerKind::Vtable(tty.principal_def_id())),
104 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
105 None => Some(PointerKind::Thin),
107 let field_ty = self.field_ty(span, f, substs);
108 self.pointer_kind(field_ty, span)?
111 ty::Tuple(fields) => match fields.last() {
112 None => Some(PointerKind::Thin),
113 Some(f) => self.pointer_kind(f.expect_ty(), span)?,
116 // Pointers to foreign types are thin, despite being unsized
117 ty::Foreign(..) => Some(PointerKind::Thin),
118 // We should really try to normalize here.
119 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
120 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
121 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
122 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
123 // Insufficient type information.
124 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
132 | ty::GeneratorWitness(..)
144 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
145 return Err(ErrorReported);
151 #[derive(Copy, Clone)]
158 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
170 impl From<ErrorReported> for CastError {
171 fn from(ErrorReported: ErrorReported) -> Self {
172 CastError::ErrorReported
176 fn make_invalid_casting_error<'a, 'tcx>(
181 fcx: &FnCtxt<'a, 'tcx>,
182 ) -> DiagnosticBuilder<'a> {
188 "casting `{}` as `{}` is invalid",
189 fcx.ty_to_string(expr_ty),
190 fcx.ty_to_string(cast_ty)
194 impl<'a, 'tcx> CastCheck<'tcx> {
196 fcx: &FnCtxt<'a, 'tcx>,
197 expr: &'tcx hir::Expr<'tcx>,
202 ) -> Result<CastCheck<'tcx>, ErrorReported> {
203 let check = CastCheck { expr, expr_ty, cast_ty, cast_span, span };
205 // For better error messages, check for some obviously unsized
206 // cases now. We do a more thorough check at the end, once
207 // inference is more completely known.
209 ty::Dynamic(..) | ty::Slice(..) => {
210 check.report_cast_to_unsized_type(fcx);
217 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
219 CastError::ErrorReported => {
220 // an error has already been reported
222 CastError::NeedDeref => {
223 let error_span = self.span;
224 let mut err = make_invalid_casting_error(
231 let cast_ty = fcx.ty_to_string(self.cast_ty);
234 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
236 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
239 "dereference the expression",
240 format!("*{}", snippet),
241 Applicability::MaybeIncorrect,
244 err.span_help(self.expr.span, "dereference the expression with `*`");
248 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
249 let mut err = make_invalid_casting_error(
256 if self.cast_ty.is_integral() {
258 "cast through {} first",
260 CastError::NeedViaPtr => "a raw pointer",
261 CastError::NeedViaThinPtr => "a thin pointer",
268 CastError::NeedViaInt => {
269 make_invalid_casting_error(
277 "cast through {} first",
279 CastError::NeedViaInt => "an integer",
285 CastError::IllegalCast => {
286 make_invalid_casting_error(
295 CastError::DifferingKinds => {
296 make_invalid_casting_error(
303 .note("vtable kinds may not match")
306 CastError::CastToBool => {
308 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
310 if self.expr_ty.is_numeric() {
311 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
315 "compare with zero instead",
316 format!("{} != 0", snippet),
317 Applicability::MachineApplicable,
321 err.span_help(self.span, "compare with zero instead");
325 err.span_label(self.span, "unsupported cast");
330 CastError::CastToChar => {
336 "only `u8` can be cast as `char`, not `{}`",
341 CastError::NonScalar => {
347 "non-primitive cast: `{}` as `{}`",
349 fcx.ty_to_string(self.cast_ty)
352 "an `as` expression can only be used to convert between \
353 primitive types. Consider using the `From` trait",
357 CastError::SizedUnsizedCast => {
358 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
359 SizedUnsizedCastError::new(
363 fcx.ty_to_string(self.cast_ty),
368 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
369 let unknown_cast_to = match e {
370 CastError::UnknownCastPtrKind => true,
371 CastError::UnknownExprPtrKind => false,
374 let mut err = struct_span_err!(
378 "cannot cast {} a pointer of an unknown kind",
379 if unknown_cast_to { "to" } else { "from" }
382 "The type information given here is insufficient to check whether \
383 the pointer cast is valid",
386 err.span_suggestion_short(
388 "consider giving more type information",
390 Applicability::Unspecified,
398 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
399 if self.cast_ty.references_error() || self.expr_ty.references_error() {
403 let tstr = fcx.ty_to_string(self.cast_ty);
404 let mut err = type_error_struct!(
409 "cast to unsized type: `{}` as `{}`",
410 fcx.resolve_vars_if_possible(&self.expr_ty),
413 match self.expr_ty.kind {
414 ty::Ref(_, _, mt) => {
415 let mtstr = mt.prefix_str();
416 if self.cast_ty.is_trait() {
417 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
421 "try casting to a reference instead",
422 format!("&{}{}", mtstr, s),
423 Applicability::MachineApplicable,
427 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
434 "consider using an implicit coercion to `&{}{}` instead",
440 ty::Adt(def, ..) if def.is_box() => {
441 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
445 "try casting to a `Box` instead",
446 format!("Box<{}>", s),
447 Applicability::MachineApplicable,
450 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
454 span_help!(err, self.expr.span, "consider using a box or reference as appropriate");
460 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
461 let t_cast = self.cast_ty;
462 let t_expr = self.expr_ty;
464 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
465 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
466 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
468 ("", lint::builtin::TRIVIAL_CASTS)
470 let mut err = fcx.tcx.struct_span_lint_hir(
475 "trivial {}cast: `{}` as `{}`",
477 fcx.ty_to_string(t_expr),
478 fcx.ty_to_string(t_cast)
482 "cast can be replaced by coercion; this might \
483 require {}a temporary variable",
489 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
490 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
491 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
493 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
495 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
496 self.report_cast_to_unsized_type(fcx);
497 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
498 // No sense in giving duplicate error messages
500 match self.try_coercion_cast(fcx) {
502 self.trivial_cast_lint(fcx);
503 debug!(" -> CoercionCast");
504 fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
506 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
507 self.report_object_unsafe_cast(&fcx, did);
510 match self.do_check(fcx) {
512 debug!(" -> {:?}", k);
514 Err(e) => self.report_cast_error(fcx, e),
521 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
522 let violations = fcx.tcx.object_safety_violations(did);
523 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
524 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
528 /// Checks a cast, and report an error if one exists. In some cases, this
529 /// can return Ok and create type errors in the fcx rather than returning
530 /// directly. coercion-cast is handled in check instead of here.
531 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
532 use rustc::ty::cast::CastTy::*;
533 use rustc::ty::cast::IntTy::*;
535 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
537 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
538 // Function item types may need to be reified before casts.
539 (None, Some(t_cast)) => {
540 match self.expr_ty.kind {
542 // Attempt a coercion to a fn pointer type.
543 let f = self.expr_ty.fn_sig(fcx.tcx);
544 let res = fcx.try_coerce(
547 fcx.tcx.mk_fn_ptr(f),
550 if let Err(TypeError::IntrinsicCast) = res {
551 return Err(CastError::IllegalCast);
554 return Err(CastError::NonScalar);
558 // Special case some errors for references, and check for
559 // array-ptr-casts. `Ref` is not a CastTy because the cast
560 // is split into a coercion to a pointer type, followed by
562 ty::Ref(_, inner_ty, mutbl) => {
563 return match t_cast {
564 Int(_) | Float => match inner_ty.kind {
568 | ty::Infer(ty::InferTy::IntVar(_))
569 | ty::Infer(ty::InferTy::FloatVar(_)) => Err(CastError::NeedDeref),
570 _ => Err(CastError::NeedViaPtr),
574 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
576 _ => Err(CastError::NonScalar),
579 _ => return Err(CastError::NonScalar),
582 _ => return Err(CastError::NonScalar),
585 match (t_from, t_cast) {
586 // These types have invariants! can't cast into them.
587 (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
590 (_, Int(Bool)) => Err(CastError::CastToBool),
593 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
594 (_, Int(Char)) => Err(CastError::CastToChar),
597 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float) => {
598 Err(CastError::NeedViaInt)
602 | (Int(CEnum), Ptr(_))
603 | (Int(Char), Ptr(_))
606 | (Float, Ptr(_)) => Err(CastError::IllegalCast),
609 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
610 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
611 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
614 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
615 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
618 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
619 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
621 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
622 Ok(CastKind::NumericCast)
627 fn check_ptr_ptr_cast(
629 fcx: &FnCtxt<'a, 'tcx>,
630 m_expr: ty::TypeAndMut<'tcx>,
631 m_cast: ty::TypeAndMut<'tcx>,
632 ) -> Result<CastKind, CastError> {
633 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
634 // ptr-ptr cast. vtables must match.
636 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
637 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
639 let cast_kind = match cast_kind {
640 // We can't cast if target pointer kind is unknown
641 None => return Err(CastError::UnknownCastPtrKind),
642 Some(cast_kind) => cast_kind,
645 // Cast to thin pointer is OK
646 if cast_kind == PointerKind::Thin {
647 return Ok(CastKind::PtrPtrCast);
650 let expr_kind = match expr_kind {
651 // We can't cast to fat pointer if source pointer kind is unknown
652 None => return Err(CastError::UnknownExprPtrKind),
653 Some(expr_kind) => expr_kind,
656 // thin -> fat? report invalid cast (don't complain about vtable kinds)
657 if expr_kind == PointerKind::Thin {
658 return Err(CastError::SizedUnsizedCast);
661 // vtable kinds must match
662 if cast_kind == expr_kind {
663 Ok(CastKind::PtrPtrCast)
665 Err(CastError::DifferingKinds)
669 fn check_fptr_ptr_cast(
671 fcx: &FnCtxt<'a, 'tcx>,
672 m_cast: ty::TypeAndMut<'tcx>,
673 ) -> Result<CastKind, CastError> {
674 // fptr-ptr cast. must be to thin ptr
676 match fcx.pointer_kind(m_cast.ty, self.span)? {
677 None => Err(CastError::UnknownCastPtrKind),
678 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
679 _ => Err(CastError::IllegalCast),
683 fn check_ptr_addr_cast(
685 fcx: &FnCtxt<'a, 'tcx>,
686 m_expr: ty::TypeAndMut<'tcx>,
687 ) -> Result<CastKind, CastError> {
688 // ptr-addr cast. must be from thin ptr
690 match fcx.pointer_kind(m_expr.ty, self.span)? {
691 None => Err(CastError::UnknownExprPtrKind),
692 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
693 _ => Err(CastError::NeedViaThinPtr),
699 fcx: &FnCtxt<'a, 'tcx>,
700 m_expr: ty::TypeAndMut<'tcx>,
701 m_cast: ty::TypeAndMut<'tcx>,
702 ) -> Result<CastKind, CastError> {
705 if m_expr.mutbl == hir::Mutability::Not && m_cast.mutbl == hir::Mutability::Not {
706 if let ty::Array(ety, _) = m_expr.ty.kind {
707 // Due to the limitations of LLVM global constants,
708 // region pointers end up pointing at copies of
709 // vector elements instead of the original values.
710 // To allow raw pointers to work correctly, we
711 // need to special-case obtaining a raw pointer
712 // from a region pointer to a vector.
714 // Coerce to a raw pointer so that we generate AddressOf in MIR.
715 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
716 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
717 .unwrap_or_else(|_| bug!(
718 "could not cast from reference to array to pointer to array ({:?} to {:?})",
723 // this will report a type mismatch if needed
724 fcx.demand_eqtype(self.span, ety, m_cast.ty);
725 return Ok(CastKind::ArrayPtrCast);
729 Err(CastError::IllegalCast)
732 fn check_addr_ptr_cast(
734 fcx: &FnCtxt<'a, 'tcx>,
735 m_cast: TypeAndMut<'tcx>,
736 ) -> Result<CastKind, CastError> {
737 // ptr-addr cast. pointer must be thin.
738 match fcx.pointer_kind(m_cast.ty, self.span)? {
739 None => Err(CastError::UnknownCastPtrKind),
740 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
741 _ => Err(CastError::IllegalCast),
745 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
746 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
748 Err(err) => Err(err),
753 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
754 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
755 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
756 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)