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::middle::lang_items;
46 use crate::util::common::ErrorReported;
48 /// Reifies a cast check to be checked once we have full type information for
49 /// a function context.
50 pub struct CastCheck<'tcx> {
51 expr: &'tcx hir::Expr,
58 /// The kind of pointer and associated metadata (thin, length or vtable) - we
59 /// only allow casts between fat pointers if their metadata have the same
61 #[derive(Copy, Clone, PartialEq, Eq)]
62 enum PointerKind<'tcx> {
63 /// No metadata attached, ie pointer to sized type or foreign type
66 Vtable(Option<DefId>),
69 /// The unsize info of this projection
70 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
71 /// The unsize info of this opaque ty
72 OfOpaque(DefId, SubstsRef<'tcx>),
73 /// The unsize info of this parameter
74 OfParam(&'tcx ty::ParamTy),
77 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
78 /// Returns the kind of unsize information of t, or None
80 fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
81 Result<Option<PointerKind<'tcx>>, ErrorReported>
83 debug!("pointer_kind({:?}, {:?})", t, span);
85 let t = self.resolve_vars_if_possible(&t);
87 if t.references_error() {
88 return Err(ErrorReported);
91 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
92 return Ok(Some(PointerKind::Thin));
96 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
97 ty::Dynamic(ref tty, ..) =>
98 Some(PointerKind::Vtable(tty.principal_def_id())),
99 ty::Adt(def, substs) if def.is_struct() => {
100 match def.non_enum_variant().fields.last() {
101 None => Some(PointerKind::Thin),
103 let field_ty = self.field_ty(span, f, substs);
104 self.pointer_kind(field_ty, span)?
108 ty::Tuple(fields) => match fields.last() {
109 None => Some(PointerKind::Thin),
110 Some(f) => self.pointer_kind(f.expect_ty(), span)?
113 // Pointers to foreign types are thin, despite being unsized
114 ty::Foreign(..) => Some(PointerKind::Thin),
115 // We should really try to normalize here.
116 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
117 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
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,
123 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
124 ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) |
125 ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) |
126 ty::FnPtr(..) | ty::Closure(..) | ty::Generator(..) |
127 ty::Adt(..) | ty::Never | ty::Error => {
128 self.tcx.sess.delay_span_bug(
129 span, &format!("`{:?}` should be sized but is not?", t));
130 return Err(ErrorReported);
136 #[derive(Copy, Clone)]
143 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
155 impl From<ErrorReported> for CastError {
156 fn from(ErrorReported: ErrorReported) -> Self {
157 CastError::ErrorReported
161 fn make_invalid_casting_error<'a, 'gcx, 'tcx>(sess: &'a Session,
165 fcx: &FnCtxt<'a, 'gcx, 'tcx>)
166 -> DiagnosticBuilder<'a> {
167 type_error_struct!(sess, span, expr_ty, E0606,
168 "casting `{}` as `{}` is invalid",
169 fcx.ty_to_string(expr_ty),
170 fcx.ty_to_string(cast_ty))
173 impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
174 pub fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>,
175 expr: &'tcx hir::Expr,
180 -> Result<CastCheck<'tcx>, ErrorReported> {
181 let check = CastCheck {
189 // For better error messages, check for some obviously unsized
190 // cases now. We do a more thorough check at the end, once
191 // inference is more completely known.
193 ty::Dynamic(..) | ty::Slice(..) => {
194 check.report_cast_to_unsized_type(fcx);
201 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, e: CastError) {
203 CastError::ErrorReported => {
204 // an error has already been reported
206 CastError::NeedDeref => {
207 let error_span = self.span;
208 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
210 let cast_ty = fcx.ty_to_string(self.cast_ty);
211 err.span_label(error_span,
212 format!("cannot cast `{}` as `{}`",
213 fcx.ty_to_string(self.expr_ty),
215 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
218 "dereference the expression",
219 format!("*{}", snippet),
220 Applicability::MaybeIncorrect,
223 err.span_help(self.expr.span, "dereference the expression with `*`");
227 CastError::NeedViaThinPtr |
228 CastError::NeedViaPtr => {
229 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
231 if self.cast_ty.is_integral() {
232 err.help(&format!("cast through {} first",
234 CastError::NeedViaPtr => "a raw pointer",
235 CastError::NeedViaThinPtr => "a thin pointer",
241 CastError::NeedViaInt => {
242 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
243 .help(&format!("cast through {} first",
245 CastError::NeedViaInt => "an integer",
250 CastError::IllegalCast => {
251 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
254 CastError::DifferingKinds => {
255 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
256 .note("vtable kinds may not match")
259 CastError::CastToBool => {
261 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
263 if self.expr_ty.is_numeric() {
264 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
268 "compare with zero instead",
269 format!("{} != 0", snippet),
270 Applicability::MachineApplicable,
274 err.span_help(self.span, "compare with zero instead");
278 err.span_label(self.span, "unsupported cast");
283 CastError::CastToChar => {
284 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0604,
285 "only `u8` can be cast as `char`, not `{}`", self.expr_ty).emit();
287 CastError::NonScalar => {
288 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0605,
289 "non-primitive cast: `{}` as `{}`",
291 fcx.ty_to_string(self.cast_ty))
292 .note("an `as` expression can only be used to convert between \
293 primitive types. Consider using the `From` trait")
296 CastError::SizedUnsizedCast => {
297 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
298 SizedUnsizedCastError::new(&fcx.tcx.sess,
301 fcx.ty_to_string(self.cast_ty))
302 .diagnostic().emit();
304 CastError::UnknownCastPtrKind |
305 CastError::UnknownExprPtrKind => {
306 let unknown_cast_to = match e {
307 CastError::UnknownCastPtrKind => true,
308 CastError::UnknownExprPtrKind => false,
311 let mut err = struct_span_err!(fcx.tcx.sess, self.span, E0641,
312 "cannot cast {} a pointer of an unknown kind",
313 if unknown_cast_to { "to" } else { "from" });
314 err.note("The type information given here is insufficient to check whether \
315 the pointer cast is valid");
317 err.span_suggestion_short(
319 "consider giving more type information",
321 Applicability::Unspecified,
329 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
330 if self.cast_ty.references_error() || self.expr_ty.references_error() {
334 let tstr = fcx.ty_to_string(self.cast_ty);
335 let mut err = type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0620,
336 "cast to unsized type: `{}` as `{}`",
337 fcx.resolve_vars_if_possible(&self.expr_ty),
339 match self.expr_ty.sty {
340 ty::Ref(_, _, mt) => {
341 let mtstr = match mt {
342 hir::MutMutable => "mut ",
343 hir::MutImmutable => "",
345 if self.cast_ty.is_trait() {
346 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
350 "try casting to a reference instead",
351 format!("&{}{}", mtstr, s),
352 Applicability::MachineApplicable,
356 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
362 "consider using an implicit coercion to `&{}{}` instead",
367 ty::Adt(def, ..) if def.is_box() => {
368 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
372 "try casting to a `Box` instead",
373 format!("Box<{}>", s),
374 Applicability::MachineApplicable,
377 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
383 "consider using a box or reference as appropriate");
389 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
390 let t_cast = self.cast_ty;
391 let t_expr = self.expr_ty;
392 let type_asc_or = if fcx.tcx.features().type_ascription {
393 "type ascription or "
397 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
398 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
400 ("", lint::builtin::TRIVIAL_CASTS)
402 let mut err = fcx.tcx.struct_span_lint_hir(
406 &format!("trivial {}cast: `{}` as `{}`",
408 fcx.ty_to_string(t_expr),
409 fcx.ty_to_string(t_cast)));
410 err.help(&format!("cast can be replaced by coercion; this might \
411 require {}a temporary variable", type_asc_or));
415 pub fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
416 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
417 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
419 debug!("check_cast({}, {:?} as {:?})",
424 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
425 self.report_cast_to_unsized_type(fcx);
426 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
427 // No sense in giving duplicate error messages
428 } else if self.try_coercion_cast(fcx) {
429 self.trivial_cast_lint(fcx);
430 debug!(" -> CoercionCast");
431 fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
434 match self.do_check(fcx) {
436 debug!(" -> {:?}", k);
438 Err(e) => self.report_cast_error(fcx, e),
443 /// Checks a cast, and report an error if one exists. In some cases, this
444 /// can return Ok and create type errors in the fcx rather than returning
445 /// directly. coercion-cast is handled in check instead of here.
446 fn do_check(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Result<CastKind, CastError> {
447 use rustc::ty::cast::IntTy::*;
448 use rustc::ty::cast::CastTy::*;
450 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
451 CastTy::from_ty(self.cast_ty)) {
452 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
453 // Function item types may need to be reified before casts.
454 (None, Some(t_cast)) => {
455 if let ty::FnDef(..) = self.expr_ty.sty {
456 // Attempt a coercion to a fn pointer type.
457 let f = self.expr_ty.fn_sig(fcx.tcx);
458 let res = fcx.try_coerce(self.expr,
460 fcx.tcx.mk_fn_ptr(f),
463 return Err(CastError::NonScalar);
467 return Err(CastError::NonScalar);
470 _ => return Err(CastError::NonScalar),
473 match (t_from, t_cast) {
474 // These types have invariants! can't cast into them.
475 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
478 (_, Int(Bool)) => Err(CastError::CastToBool),
481 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
482 (_, Int(Char)) => Err(CastError::CastToChar),
486 (Int(CEnum), Float) |
487 (Int(Char), Float) => Err(CastError::NeedViaInt),
489 (Int(Bool), Ptr(_)) |
490 (Int(CEnum), Ptr(_)) |
491 (Int(Char), Ptr(_)) |
494 (Float, Ptr(_)) => Err(CastError::IllegalCast),
497 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
498 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
499 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
501 (RPtr(p), Float) => {
506 Err(CastError::NeedDeref)
510 ty::InferTy::IntVar(_) |
511 ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
512 _ => Err(CastError::NeedViaPtr),
515 _ => Err(CastError::NeedViaPtr),
519 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
520 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
521 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
524 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
525 (Int(Char), Int(_)) |
526 (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
528 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
529 Ok(CastKind::NumericCast)
534 fn check_ptr_ptr_cast(&self,
535 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
536 m_expr: ty::TypeAndMut<'tcx>,
537 m_cast: ty::TypeAndMut<'tcx>)
538 -> Result<CastKind, CastError> {
539 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
540 // ptr-ptr cast. vtables must match.
542 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
543 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
545 let cast_kind = match cast_kind {
546 // We can't cast if target pointer kind is unknown
547 None => return Err(CastError::UnknownCastPtrKind),
548 Some(cast_kind) => cast_kind,
551 // Cast to thin pointer is OK
552 if cast_kind == PointerKind::Thin {
553 return Ok(CastKind::PtrPtrCast);
556 let expr_kind = match expr_kind {
557 // We can't cast to fat pointer if source pointer kind is unknown
558 None => return Err(CastError::UnknownExprPtrKind),
559 Some(expr_kind) => expr_kind,
562 // thin -> fat? report invalid cast (don't complain about vtable kinds)
563 if expr_kind == PointerKind::Thin {
564 return Err(CastError::SizedUnsizedCast);
567 // vtable kinds must match
568 if cast_kind == expr_kind {
569 Ok(CastKind::PtrPtrCast)
571 Err(CastError::DifferingKinds)
575 fn check_fptr_ptr_cast(&self,
576 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
577 m_cast: ty::TypeAndMut<'tcx>)
578 -> Result<CastKind, CastError> {
579 // fptr-ptr cast. must be to thin ptr
581 match fcx.pointer_kind(m_cast.ty, self.span)? {
582 None => Err(CastError::UnknownCastPtrKind),
583 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
584 _ => Err(CastError::IllegalCast),
588 fn check_ptr_addr_cast(&self,
589 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
590 m_expr: ty::TypeAndMut<'tcx>)
591 -> Result<CastKind, CastError> {
592 // ptr-addr cast. must be from thin ptr
594 match fcx.pointer_kind(m_expr.ty, self.span)? {
595 None => Err(CastError::UnknownExprPtrKind),
596 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
597 _ => Err(CastError::NeedViaThinPtr),
601 fn check_ref_cast(&self,
602 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
603 m_expr: ty::TypeAndMut<'tcx>,
604 m_cast: ty::TypeAndMut<'tcx>)
605 -> Result<CastKind, CastError> {
608 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
609 if let ty::Array(ety, _) = m_expr.ty.sty {
610 // Due to the limitations of LLVM global constants,
611 // region pointers end up pointing at copies of
612 // vector elements instead of the original values.
613 // To allow raw pointers to work correctly, we
614 // need to special-case obtaining a raw pointer
615 // from a region pointer to a vector.
617 // this will report a type mismatch if needed
618 fcx.demand_eqtype(self.span, ety, m_cast.ty);
619 return Ok(CastKind::ArrayPtrCast);
623 Err(CastError::IllegalCast)
626 fn check_addr_ptr_cast(&self,
627 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
628 m_cast: TypeAndMut<'tcx>)
629 -> Result<CastKind, CastError> {
630 // ptr-addr cast. pointer must be thin.
631 match fcx.pointer_kind(m_cast.ty, self.span)? {
632 None => Err(CastError::UnknownCastPtrKind),
633 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
634 _ => Err(CastError::IllegalCast),
638 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> bool {
639 fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No).is_ok()
643 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
644 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
645 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
646 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)