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 errors::{DiagnosticBuilder,Applicability};
34 use crate::hir::def_id::DefId;
37 use rustc::session::Session;
39 use rustc::ty::{self, Ty, TypeFoldable, TypeAndMut};
40 use rustc::ty::subst::SubstsRef;
41 use rustc::ty::adjustment::AllowTwoPhase;
42 use rustc::ty::cast::{CastKind, CastTy};
43 use rustc::ty::error::TypeError;
44 use rustc::middle::lang_items;
47 use crate::util::common::ErrorReported;
49 use rustc_error_codes::*;
51 /// Reifies a cast check to be checked once we have full type information for
52 /// a function context.
53 pub struct CastCheck<'tcx> {
54 expr: &'tcx hir::Expr,
61 /// The kind of pointer and associated metadata (thin, length or vtable) - we
62 /// only allow casts between fat pointers if their metadata have the same
64 #[derive(Copy, Clone, PartialEq, Eq)]
65 enum PointerKind<'tcx> {
66 /// No metadata attached, ie pointer to sized type or foreign type
69 Vtable(Option<DefId>),
72 /// The unsize info of this projection
73 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
74 /// The unsize info of this opaque ty
75 OfOpaque(DefId, SubstsRef<'tcx>),
76 /// The unsize info of this parameter
77 OfParam(&'tcx ty::ParamTy),
80 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
81 /// Returns the kind of unsize information of t, or None
83 fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
84 Result<Option<PointerKind<'tcx>>, ErrorReported>
86 debug!("pointer_kind({:?}, {:?})", t, span);
88 let t = self.resolve_vars_if_possible(&t);
90 if t.references_error() {
91 return Err(ErrorReported);
94 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
95 return Ok(Some(PointerKind::Thin));
99 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
100 ty::Dynamic(ref tty, ..) =>
101 Some(PointerKind::Vtable(tty.principal_def_id())),
102 ty::Adt(def, substs) if def.is_struct() => {
103 match def.non_enum_variant().fields.last() {
104 None => Some(PointerKind::Thin),
106 let field_ty = self.field_ty(span, f, substs);
107 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,
126 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
127 ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) |
128 ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) |
129 ty::FnPtr(..) | ty::Closure(..) | ty::Generator(..) |
130 ty::Adt(..) | ty::Never | ty::Error => {
131 self.tcx.sess.delay_span_bug(
132 span, &format!("`{:?}` should be sized but is not?", t));
133 return Err(ErrorReported);
139 #[derive(Copy, Clone)]
146 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
158 impl From<ErrorReported> for CastError {
159 fn from(ErrorReported: ErrorReported) -> Self {
160 CastError::ErrorReported
164 fn make_invalid_casting_error<'a, 'tcx>(
169 fcx: &FnCtxt<'a, 'tcx>,
170 ) -> DiagnosticBuilder<'a> {
171 type_error_struct!(sess, span, expr_ty, E0606,
172 "casting `{}` as `{}` is invalid",
173 fcx.ty_to_string(expr_ty),
174 fcx.ty_to_string(cast_ty))
177 impl<'a, 'tcx> CastCheck<'tcx> {
179 fcx: &FnCtxt<'a, 'tcx>,
180 expr: &'tcx hir::Expr,
185 ) -> Result<CastCheck<'tcx>, ErrorReported> {
186 let check = CastCheck {
194 // For better error messages, check for some obviously unsized
195 // cases now. We do a more thorough check at the end, once
196 // inference is more completely known.
198 ty::Dynamic(..) | ty::Slice(..) => {
199 check.report_cast_to_unsized_type(fcx);
206 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
208 CastError::ErrorReported => {
209 // an error has already been reported
211 CastError::NeedDeref => {
212 let error_span = self.span;
213 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
215 let cast_ty = fcx.ty_to_string(self.cast_ty);
216 err.span_label(error_span,
217 format!("cannot cast `{}` as `{}`",
218 fcx.ty_to_string(self.expr_ty),
220 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
223 "dereference the expression",
224 format!("*{}", snippet),
225 Applicability::MaybeIncorrect,
228 err.span_help(self.expr.span, "dereference the expression with `*`");
232 CastError::NeedViaThinPtr |
233 CastError::NeedViaPtr => {
234 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
236 if self.cast_ty.is_integral() {
237 err.help(&format!("cast through {} first",
239 CastError::NeedViaPtr => "a raw pointer",
240 CastError::NeedViaThinPtr => "a thin pointer",
246 CastError::NeedViaInt => {
247 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
248 .help(&format!("cast through {} first",
250 CastError::NeedViaInt => "an integer",
255 CastError::IllegalCast => {
256 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
259 CastError::DifferingKinds => {
260 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
261 .note("vtable kinds may not match")
264 CastError::CastToBool => {
266 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
268 if self.expr_ty.is_numeric() {
269 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
273 "compare with zero instead",
274 format!("{} != 0", snippet),
275 Applicability::MachineApplicable,
279 err.span_help(self.span, "compare with zero instead");
283 err.span_label(self.span, "unsupported cast");
288 CastError::CastToChar => {
289 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0604,
290 "only `u8` can be cast as `char`, not `{}`", self.expr_ty).emit();
292 CastError::NonScalar => {
293 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0605,
294 "non-primitive cast: `{}` as `{}`",
296 fcx.ty_to_string(self.cast_ty))
297 .note("an `as` expression can only be used to convert between \
298 primitive types. Consider using the `From` trait")
301 CastError::SizedUnsizedCast => {
302 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
303 SizedUnsizedCastError::new(&fcx.tcx.sess,
306 fcx.ty_to_string(self.cast_ty))
307 .diagnostic().emit();
309 CastError::UnknownCastPtrKind |
310 CastError::UnknownExprPtrKind => {
311 let unknown_cast_to = match e {
312 CastError::UnknownCastPtrKind => true,
313 CastError::UnknownExprPtrKind => false,
316 let mut err = struct_span_err!(fcx.tcx.sess, self.span, E0641,
317 "cannot cast {} a pointer of an unknown kind",
318 if unknown_cast_to { "to" } else { "from" });
319 err.note("The type information given here is insufficient to check whether \
320 the pointer cast is valid");
322 err.span_suggestion_short(
324 "consider giving more type information",
326 Applicability::Unspecified,
334 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
335 if self.cast_ty.references_error() || self.expr_ty.references_error() {
339 let tstr = fcx.ty_to_string(self.cast_ty);
340 let mut err = type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0620,
341 "cast to unsized type: `{}` as `{}`",
342 fcx.resolve_vars_if_possible(&self.expr_ty),
344 match self.expr_ty.kind {
345 ty::Ref(_, _, mt) => {
346 let mtstr = mt.prefix_str();
347 if self.cast_ty.is_trait() {
348 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
352 "try casting to a reference instead",
353 format!("&{}{}", mtstr, s),
354 Applicability::MachineApplicable,
358 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
364 "consider using an implicit coercion to `&{}{}` instead",
369 ty::Adt(def, ..) if def.is_box() => {
370 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
374 "try casting to a `Box` instead",
375 format!("Box<{}>", s),
376 Applicability::MachineApplicable,
379 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
385 "consider using a box or reference as appropriate");
391 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
392 let t_cast = self.cast_ty;
393 let t_expr = self.expr_ty;
394 let type_asc_or = if fcx.tcx.features().type_ascription {
395 "type ascription or "
399 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
400 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
402 ("", lint::builtin::TRIVIAL_CASTS)
404 let mut err = fcx.tcx.struct_span_lint_hir(
408 &format!("trivial {}cast: `{}` as `{}`",
410 fcx.ty_to_string(t_expr),
411 fcx.ty_to_string(t_cast)));
412 err.help(&format!("cast can be replaced by coercion; this might \
413 require {}a temporary variable", type_asc_or));
417 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
418 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
419 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
421 debug!("check_cast({}, {:?} as {:?})",
426 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
427 self.report_cast_to_unsized_type(fcx);
428 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
429 // No sense in giving duplicate error messages
431 match self.try_coercion_cast(fcx) {
433 self.trivial_cast_lint(fcx);
434 debug!(" -> CoercionCast");
435 fcx.tables.borrow_mut()
436 .set_coercion_cast(self.expr.hir_id.local_id);
438 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
439 self.report_object_unsafe_cast(&fcx, did);
442 match self.do_check(fcx) {
444 debug!(" -> {:?}", k);
446 Err(e) => self.report_cast_error(fcx, e),
453 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
454 let violations = fcx.tcx.object_safety_violations(did);
455 let mut err = fcx.tcx.report_object_safety_error(self.cast_span, did, violations);
456 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
460 /// Checks a cast, and report an error if one exists. In some cases, this
461 /// can return Ok and create type errors in the fcx rather than returning
462 /// directly. coercion-cast is handled in check instead of here.
463 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
464 use rustc::ty::cast::IntTy::*;
465 use rustc::ty::cast::CastTy::*;
467 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
468 CastTy::from_ty(self.cast_ty)) {
469 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
470 // Function item types may need to be reified before casts.
471 (None, Some(t_cast)) => {
472 if let ty::FnDef(..) = self.expr_ty.kind {
473 // Attempt a coercion to a fn pointer type.
474 let f = self.expr_ty.fn_sig(fcx.tcx);
475 let res = fcx.try_coerce(self.expr,
477 fcx.tcx.mk_fn_ptr(f),
479 if let Err(TypeError::IntrinsicCast) = res {
480 return Err(CastError::IllegalCast);
483 return Err(CastError::NonScalar);
487 return Err(CastError::NonScalar);
490 _ => return Err(CastError::NonScalar),
493 match (t_from, t_cast) {
494 // These types have invariants! can't cast into them.
495 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
498 (_, Int(Bool)) => Err(CastError::CastToBool),
501 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
502 (_, Int(Char)) => Err(CastError::CastToChar),
506 (Int(CEnum), Float) |
507 (Int(Char), Float) => Err(CastError::NeedViaInt),
509 (Int(Bool), Ptr(_)) |
510 (Int(CEnum), Ptr(_)) |
511 (Int(Char), Ptr(_)) |
514 (Float, Ptr(_)) => Err(CastError::IllegalCast),
517 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
518 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
519 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
521 (RPtr(p), Float) => {
526 Err(CastError::NeedDeref)
530 ty::InferTy::IntVar(_) |
531 ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
532 _ => Err(CastError::NeedViaPtr),
535 _ => Err(CastError::NeedViaPtr),
539 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
540 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
541 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
544 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
545 (Int(Char), Int(_)) |
546 (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
548 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
549 Ok(CastKind::NumericCast)
554 fn check_ptr_ptr_cast(
556 fcx: &FnCtxt<'a, 'tcx>,
557 m_expr: ty::TypeAndMut<'tcx>,
558 m_cast: ty::TypeAndMut<'tcx>,
559 ) -> Result<CastKind, CastError> {
560 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
561 // ptr-ptr cast. vtables must match.
563 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
564 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
566 let cast_kind = match cast_kind {
567 // We can't cast if target pointer kind is unknown
568 None => return Err(CastError::UnknownCastPtrKind),
569 Some(cast_kind) => cast_kind,
572 // Cast to thin pointer is OK
573 if cast_kind == PointerKind::Thin {
574 return Ok(CastKind::PtrPtrCast);
577 let expr_kind = match expr_kind {
578 // We can't cast to fat pointer if source pointer kind is unknown
579 None => return Err(CastError::UnknownExprPtrKind),
580 Some(expr_kind) => expr_kind,
583 // thin -> fat? report invalid cast (don't complain about vtable kinds)
584 if expr_kind == PointerKind::Thin {
585 return Err(CastError::SizedUnsizedCast);
588 // vtable kinds must match
589 if cast_kind == expr_kind {
590 Ok(CastKind::PtrPtrCast)
592 Err(CastError::DifferingKinds)
596 fn check_fptr_ptr_cast(
598 fcx: &FnCtxt<'a, 'tcx>,
599 m_cast: ty::TypeAndMut<'tcx>,
600 ) -> Result<CastKind, CastError> {
601 // fptr-ptr cast. must be to thin ptr
603 match fcx.pointer_kind(m_cast.ty, self.span)? {
604 None => Err(CastError::UnknownCastPtrKind),
605 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
606 _ => Err(CastError::IllegalCast),
610 fn check_ptr_addr_cast(
612 fcx: &FnCtxt<'a, 'tcx>,
613 m_expr: ty::TypeAndMut<'tcx>,
614 ) -> Result<CastKind, CastError> {
615 // ptr-addr cast. must be from thin ptr
617 match fcx.pointer_kind(m_expr.ty, self.span)? {
618 None => Err(CastError::UnknownExprPtrKind),
619 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
620 _ => Err(CastError::NeedViaThinPtr),
626 fcx: &FnCtxt<'a, 'tcx>,
627 m_expr: ty::TypeAndMut<'tcx>,
628 m_cast: ty::TypeAndMut<'tcx>,
629 ) -> Result<CastKind, CastError> {
632 if m_expr.mutbl == hir::Mutability::Immutable &&
633 m_cast.mutbl == hir::Mutability::Immutable {
634 if let ty::Array(ety, _) = m_expr.ty.kind {
635 // Due to the limitations of LLVM global constants,
636 // region pointers end up pointing at copies of
637 // vector elements instead of the original values.
638 // To allow raw pointers to work correctly, we
639 // need to special-case obtaining a raw pointer
640 // from a region pointer to a vector.
642 // Coerce to a raw pointer so that we generate AddressOf in MIR.
643 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
644 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
645 .unwrap_or_else(|_| bug!(
646 "could not cast from reference to array to pointer to array ({:?} to {:?})",
651 // this will report a type mismatch if needed
652 fcx.demand_eqtype(self.span, ety, m_cast.ty);
653 return Ok(CastKind::ArrayPtrCast);
657 Err(CastError::IllegalCast)
660 fn check_addr_ptr_cast(
662 fcx: &FnCtxt<'a, 'tcx>,
663 m_cast: TypeAndMut<'tcx>,
664 ) -> Result<CastKind, CastError> {
665 // ptr-addr cast. pointer must be thin.
666 match fcx.pointer_kind(m_cast.ty, self.span)? {
667 None => Err(CastError::UnknownCastPtrKind),
668 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
669 _ => Err(CastError::IllegalCast),
673 fn try_coercion_cast(
675 fcx: &FnCtxt<'a, 'tcx>,
676 ) -> Result<(), ty::error::TypeError<'_>> {
677 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
679 Err(err) => Err(err),
684 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
685 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
686 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
687 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)