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 /// Reifies a cast check to be checked once we have full type information for
50 /// a function context.
51 pub struct CastCheck<'tcx> {
52 expr: &'tcx hir::Expr,
59 /// The kind of pointer and associated metadata (thin, length or vtable) - we
60 /// only allow casts between fat pointers if their metadata have the same
62 #[derive(Copy, Clone, PartialEq, Eq)]
63 enum PointerKind<'tcx> {
64 /// No metadata attached, ie pointer to sized type or foreign type
67 Vtable(Option<DefId>),
70 /// The unsize info of this projection
71 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
72 /// The unsize info of this opaque ty
73 OfOpaque(DefId, SubstsRef<'tcx>),
74 /// The unsize info of this parameter
75 OfParam(&'tcx ty::ParamTy),
78 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
79 /// Returns the kind of unsize information of t, or None
81 fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
82 Result<Option<PointerKind<'tcx>>, ErrorReported>
84 debug!("pointer_kind({:?}, {:?})", t, span);
86 let t = self.resolve_vars_if_possible(&t);
88 if t.references_error() {
89 return Err(ErrorReported);
92 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
93 return Ok(Some(PointerKind::Thin));
97 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
98 ty::Dynamic(ref tty, ..) =>
99 Some(PointerKind::Vtable(tty.principal_def_id())),
100 ty::Adt(def, substs) if def.is_struct() => {
101 match def.non_enum_variant().fields.last() {
102 None => Some(PointerKind::Thin),
104 let field_ty = self.field_ty(span, f, substs);
105 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::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
119 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
120 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
121 // Insufficient type information.
122 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
124 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
125 ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) |
126 ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) |
127 ty::FnPtr(..) | ty::Closure(..) | ty::Generator(..) |
128 ty::Adt(..) | ty::Never | ty::Error => {
129 self.tcx.sess.delay_span_bug(
130 span, &format!("`{:?}` should be sized but is not?", t));
131 return Err(ErrorReported);
137 #[derive(Copy, Clone)]
144 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
156 impl From<ErrorReported> for CastError {
157 fn from(ErrorReported: ErrorReported) -> Self {
158 CastError::ErrorReported
162 fn make_invalid_casting_error<'a, 'tcx>(
167 fcx: &FnCtxt<'a, 'tcx>,
168 ) -> DiagnosticBuilder<'a> {
169 type_error_struct!(sess, span, expr_ty, E0606,
170 "casting `{}` as `{}` is invalid",
171 fcx.ty_to_string(expr_ty),
172 fcx.ty_to_string(cast_ty))
175 impl<'a, 'tcx> CastCheck<'tcx> {
177 fcx: &FnCtxt<'a, 'tcx>,
178 expr: &'tcx hir::Expr,
183 ) -> Result<CastCheck<'tcx>, ErrorReported> {
184 let check = CastCheck {
192 // For better error messages, check for some obviously unsized
193 // cases now. We do a more thorough check at the end, once
194 // inference is more completely known.
196 ty::Dynamic(..) | ty::Slice(..) => {
197 check.report_cast_to_unsized_type(fcx);
204 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
206 CastError::ErrorReported => {
207 // an error has already been reported
209 CastError::NeedDeref => {
210 let error_span = self.span;
211 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
213 let cast_ty = fcx.ty_to_string(self.cast_ty);
214 err.span_label(error_span,
215 format!("cannot cast `{}` as `{}`",
216 fcx.ty_to_string(self.expr_ty),
218 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
221 "dereference the expression",
222 format!("*{}", snippet),
223 Applicability::MaybeIncorrect,
226 err.span_help(self.expr.span, "dereference the expression with `*`");
230 CastError::NeedViaThinPtr |
231 CastError::NeedViaPtr => {
232 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
234 if self.cast_ty.is_integral() {
235 err.help(&format!("cast through {} first",
237 CastError::NeedViaPtr => "a raw pointer",
238 CastError::NeedViaThinPtr => "a thin pointer",
244 CastError::NeedViaInt => {
245 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
246 .help(&format!("cast through {} first",
248 CastError::NeedViaInt => "an integer",
253 CastError::IllegalCast => {
254 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
257 CastError::DifferingKinds => {
258 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
259 .note("vtable kinds may not match")
262 CastError::CastToBool => {
264 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
266 if self.expr_ty.is_numeric() {
267 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
271 "compare with zero instead",
272 format!("{} != 0", snippet),
273 Applicability::MachineApplicable,
277 err.span_help(self.span, "compare with zero instead");
281 err.span_label(self.span, "unsupported cast");
286 CastError::CastToChar => {
287 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0604,
288 "only `u8` can be cast as `char`, not `{}`", self.expr_ty).emit();
290 CastError::NonScalar => {
291 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0605,
292 "non-primitive cast: `{}` as `{}`",
294 fcx.ty_to_string(self.cast_ty))
295 .note("an `as` expression can only be used to convert between \
296 primitive types. Consider using the `From` trait")
299 CastError::SizedUnsizedCast => {
300 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
301 SizedUnsizedCastError::new(&fcx.tcx.sess,
304 fcx.ty_to_string(self.cast_ty))
305 .diagnostic().emit();
307 CastError::UnknownCastPtrKind |
308 CastError::UnknownExprPtrKind => {
309 let unknown_cast_to = match e {
310 CastError::UnknownCastPtrKind => true,
311 CastError::UnknownExprPtrKind => false,
314 let mut err = struct_span_err!(fcx.tcx.sess, self.span, E0641,
315 "cannot cast {} a pointer of an unknown kind",
316 if unknown_cast_to { "to" } else { "from" });
317 err.note("The type information given here is insufficient to check whether \
318 the pointer cast is valid");
320 err.span_suggestion_short(
322 "consider giving more type information",
324 Applicability::Unspecified,
332 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
333 if self.cast_ty.references_error() || self.expr_ty.references_error() {
337 let tstr = fcx.ty_to_string(self.cast_ty);
338 let mut err = type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0620,
339 "cast to unsized type: `{}` as `{}`",
340 fcx.resolve_vars_if_possible(&self.expr_ty),
342 match self.expr_ty.kind {
343 ty::Ref(_, _, mt) => {
344 let mtstr = match mt {
345 hir::MutMutable => "mut ",
346 hir::MutImmutable => "",
348 if self.cast_ty.is_trait() {
349 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
353 "try casting to a reference instead",
354 format!("&{}{}", mtstr, s),
355 Applicability::MachineApplicable,
359 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
365 "consider using an implicit coercion to `&{}{}` instead",
370 ty::Adt(def, ..) if def.is_box() => {
371 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
375 "try casting to a `Box` instead",
376 format!("Box<{}>", s),
377 Applicability::MachineApplicable,
380 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
386 "consider using a box or reference as appropriate");
392 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
393 let t_cast = self.cast_ty;
394 let t_expr = self.expr_ty;
395 let type_asc_or = if fcx.tcx.features().type_ascription {
396 "type ascription or "
400 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
401 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
403 ("", lint::builtin::TRIVIAL_CASTS)
405 let mut err = fcx.tcx.struct_span_lint_hir(
409 &format!("trivial {}cast: `{}` as `{}`",
411 fcx.ty_to_string(t_expr),
412 fcx.ty_to_string(t_cast)));
413 err.help(&format!("cast can be replaced by coercion; this might \
414 require {}a temporary variable", type_asc_or));
418 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
419 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
420 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
422 debug!("check_cast({}, {:?} as {:?})",
427 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
428 self.report_cast_to_unsized_type(fcx);
429 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
430 // No sense in giving duplicate error messages
432 match self.try_coercion_cast(fcx) {
434 self.trivial_cast_lint(fcx);
435 debug!(" -> CoercionCast");
436 fcx.tables.borrow_mut()
437 .set_coercion_cast(self.expr.hir_id.local_id);
439 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
440 self.report_object_unsafe_cast(&fcx, did);
443 match self.do_check(fcx) {
445 debug!(" -> {:?}", k);
447 Err(e) => self.report_cast_error(fcx, e),
454 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
455 let violations = fcx.tcx.object_safety_violations(did);
456 let mut err = fcx.tcx.report_object_safety_error(self.cast_span, did, violations);
457 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
461 /// Checks a cast, and report an error if one exists. In some cases, this
462 /// can return Ok and create type errors in the fcx rather than returning
463 /// directly. coercion-cast is handled in check instead of here.
464 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
465 use rustc::ty::cast::IntTy::*;
466 use rustc::ty::cast::CastTy::*;
468 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
469 CastTy::from_ty(self.cast_ty)) {
470 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
471 // Function item types may need to be reified before casts.
472 (None, Some(t_cast)) => {
473 if let ty::FnDef(..) = self.expr_ty.kind {
474 // Attempt a coercion to a fn pointer type.
475 let f = self.expr_ty.fn_sig(fcx.tcx);
476 let res = fcx.try_coerce(self.expr,
478 fcx.tcx.mk_fn_ptr(f),
480 if let Err(TypeError::IntrinsicCast) = res {
481 return Err(CastError::IllegalCast);
484 return Err(CastError::NonScalar);
488 return Err(CastError::NonScalar);
491 _ => return Err(CastError::NonScalar),
494 match (t_from, t_cast) {
495 // These types have invariants! can't cast into them.
496 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
499 (_, Int(Bool)) => Err(CastError::CastToBool),
502 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
503 (_, Int(Char)) => Err(CastError::CastToChar),
507 (Int(CEnum), Float) |
508 (Int(Char), Float) => Err(CastError::NeedViaInt),
510 (Int(Bool), Ptr(_)) |
511 (Int(CEnum), Ptr(_)) |
512 (Int(Char), Ptr(_)) |
515 (Float, Ptr(_)) => Err(CastError::IllegalCast),
518 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
519 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
520 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
522 (RPtr(p), Float) => {
527 Err(CastError::NeedDeref)
531 ty::InferTy::IntVar(_) |
532 ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
533 _ => Err(CastError::NeedViaPtr),
536 _ => Err(CastError::NeedViaPtr),
540 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
541 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
542 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
545 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
546 (Int(Char), Int(_)) |
547 (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
549 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
550 Ok(CastKind::NumericCast)
555 fn check_ptr_ptr_cast(
557 fcx: &FnCtxt<'a, 'tcx>,
558 m_expr: ty::TypeAndMut<'tcx>,
559 m_cast: ty::TypeAndMut<'tcx>,
560 ) -> Result<CastKind, CastError> {
561 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
562 // ptr-ptr cast. vtables must match.
564 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
565 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
567 let cast_kind = match cast_kind {
568 // We can't cast if target pointer kind is unknown
569 None => return Err(CastError::UnknownCastPtrKind),
570 Some(cast_kind) => cast_kind,
573 // Cast to thin pointer is OK
574 if cast_kind == PointerKind::Thin {
575 return Ok(CastKind::PtrPtrCast);
578 let expr_kind = match expr_kind {
579 // We can't cast to fat pointer if source pointer kind is unknown
580 None => return Err(CastError::UnknownExprPtrKind),
581 Some(expr_kind) => expr_kind,
584 // thin -> fat? report invalid cast (don't complain about vtable kinds)
585 if expr_kind == PointerKind::Thin {
586 return Err(CastError::SizedUnsizedCast);
589 // vtable kinds must match
590 if cast_kind == expr_kind {
591 Ok(CastKind::PtrPtrCast)
593 Err(CastError::DifferingKinds)
597 fn check_fptr_ptr_cast(
599 fcx: &FnCtxt<'a, 'tcx>,
600 m_cast: ty::TypeAndMut<'tcx>,
601 ) -> Result<CastKind, CastError> {
602 // fptr-ptr cast. must be to thin ptr
604 match fcx.pointer_kind(m_cast.ty, self.span)? {
605 None => Err(CastError::UnknownCastPtrKind),
606 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
607 _ => Err(CastError::IllegalCast),
611 fn check_ptr_addr_cast(
613 fcx: &FnCtxt<'a, 'tcx>,
614 m_expr: ty::TypeAndMut<'tcx>,
615 ) -> Result<CastKind, CastError> {
616 // ptr-addr cast. must be from thin ptr
618 match fcx.pointer_kind(m_expr.ty, self.span)? {
619 None => Err(CastError::UnknownExprPtrKind),
620 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
621 _ => Err(CastError::NeedViaThinPtr),
627 fcx: &FnCtxt<'a, 'tcx>,
628 m_expr: ty::TypeAndMut<'tcx>,
629 m_cast: ty::TypeAndMut<'tcx>,
630 ) -> Result<CastKind, CastError> {
633 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
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 // this will report a type mismatch if needed
643 fcx.demand_eqtype(self.span, ety, m_cast.ty);
644 return Ok(CastKind::ArrayPtrCast);
648 Err(CastError::IllegalCast)
651 fn check_addr_ptr_cast(
653 fcx: &FnCtxt<'a, 'tcx>,
654 m_cast: TypeAndMut<'tcx>,
655 ) -> Result<CastKind, CastError> {
656 // ptr-addr cast. pointer must be thin.
657 match fcx.pointer_kind(m_cast.ty, self.span)? {
658 None => Err(CastError::UnknownCastPtrKind),
659 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
660 _ => Err(CastError::IllegalCast),
664 fn try_coercion_cast(
666 fcx: &FnCtxt<'a, 'tcx>,
667 ) -> Result<(), ty::error::TypeError<'_>> {
668 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
670 Err(err) => Err(err),
675 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
676 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
677 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
678 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)