1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code for type-checking cast expressions.
13 //! A cast `e as U` is valid if one of the following holds:
14 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
15 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
16 //! pointer_kind(`T`) = pointer_kind(`U_0`); *ptr-ptr-cast*
17 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
18 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
19 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
20 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
21 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
22 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
23 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
24 //! * `e` is a function pointer type and `U` has type `*T`,
25 //! while `T: Sized`; *fptr-ptr-cast*
26 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
28 //! where `&.T` and `*T` are references of either mutability,
29 //! and where pointer_kind(`T`) is the kind of the unsize info
30 //! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or
31 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
33 //! Note that lengths are not adjusted when casting raw slices -
34 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
35 //! half of the original memory.
37 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
38 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
39 //! `U1` coerces to `U2`).
43 use errors::{DiagnosticBuilder,Applicability};
44 use hir::def_id::DefId;
47 use rustc::session::Session;
49 use rustc::ty::{self, Ty, TypeFoldable, TypeAndMut};
50 use rustc::ty::adjustment::AllowTwoPhase;
51 use rustc::ty::cast::{CastKind, CastTy};
52 use rustc::ty::subst::Substs;
53 use rustc::middle::lang_items;
56 use util::common::ErrorReported;
58 /// Reifies a cast check to be checked once we have full type information for
59 /// a function context.
60 pub struct CastCheck<'tcx> {
61 expr: &'tcx hir::Expr,
68 /// The kind of pointer and associated metadata (thin, length or vtable) - we
69 /// only allow casts between fat pointers if their metadata have the same
71 #[derive(Copy, Clone, PartialEq, Eq)]
72 enum PointerKind<'tcx> {
73 /// No metadata attached, ie pointer to sized type or foreign type
79 /// The unsize info of this projection
80 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
81 /// The unsize info of this opaque ty
82 OfOpaque(DefId, &'tcx Substs<'tcx>),
83 /// The unsize info of this parameter
84 OfParam(&'tcx ty::ParamTy),
87 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
88 /// Returns the kind of unsize information of t, or None
90 fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
91 Result<Option<PointerKind<'tcx>>, ErrorReported>
93 debug!("pointer_kind({:?}, {:?})", t, span);
95 let t = self.resolve_type_vars_if_possible(&t);
97 if t.references_error() {
98 return Err(ErrorReported);
101 if self.type_is_known_to_be_sized(t, span) {
102 return Ok(Some(PointerKind::Thin));
106 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
107 ty::Dynamic(ref tty, ..) =>
108 Some(PointerKind::Vtable(tty.principal().def_id())),
109 ty::Adt(def, substs) if def.is_struct() => {
110 match def.non_enum_variant().fields.last() {
111 None => Some(PointerKind::Thin),
113 let field_ty = self.field_ty(span, f, substs);
114 self.pointer_kind(field_ty, span)?
118 ty::Tuple(fields) => match fields.last() {
119 None => Some(PointerKind::Thin),
120 Some(f) => self.pointer_kind(f, span)?
123 // Pointers to foreign types are thin, despite being unsized
124 ty::Foreign(..) => Some(PointerKind::Thin),
125 // We should really try to normalize here.
126 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
127 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
128 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
129 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
130 // Insufficient type information.
131 ty::Bound(..) | ty::Infer(_) => None,
133 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
134 ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) |
135 ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) |
136 ty::FnPtr(..) | ty::Closure(..) | ty::Generator(..) |
137 ty::Adt(..) | ty::Never | ty::Error => {
138 self.tcx.sess.delay_span_bug(
139 span, &format!("`{:?}` should be sized but is not?", t));
140 return Err(ErrorReported);
146 #[derive(Copy, Clone)]
153 /// Cast of thin to fat raw ptr (eg. `*const () as *const [u8]`)
165 impl From<ErrorReported> for CastError {
166 fn from(ErrorReported: ErrorReported) -> Self {
167 CastError::ErrorReported
171 fn make_invalid_casting_error<'a, 'gcx, 'tcx>(sess: &'a Session,
175 fcx: &FnCtxt<'a, 'gcx, 'tcx>)
176 -> DiagnosticBuilder<'a> {
177 type_error_struct!(sess, span, expr_ty, E0606,
178 "casting `{}` as `{}` is invalid",
179 fcx.ty_to_string(expr_ty),
180 fcx.ty_to_string(cast_ty))
183 impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
184 pub fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>,
185 expr: &'tcx hir::Expr,
190 -> Result<CastCheck<'tcx>, ErrorReported> {
191 let check = CastCheck {
199 // For better error messages, check for some obviously unsized
200 // cases now. We do a more thorough check at the end, once
201 // inference is more completely known.
203 ty::Dynamic(..) | ty::Slice(..) => {
204 check.report_cast_to_unsized_type(fcx);
211 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, e: CastError) {
213 CastError::ErrorReported => {
214 // an error has already been reported
216 CastError::NeedDeref => {
217 let error_span = self.span;
218 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
220 let cast_ty = fcx.ty_to_string(self.cast_ty);
221 err.span_label(error_span,
222 format!("cannot cast `{}` as `{}`",
223 fcx.ty_to_string(self.expr_ty),
225 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
226 err.span_help(self.expr.span,
227 &format!("did you mean `*{}`?", snippet));
231 CastError::NeedViaThinPtr |
232 CastError::NeedViaPtr => {
233 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
235 if self.cast_ty.is_integral() {
236 err.help(&format!("cast through {} first",
238 CastError::NeedViaPtr => "a raw pointer",
239 CastError::NeedViaThinPtr => "a thin pointer",
245 CastError::NeedViaInt => {
246 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
247 .help(&format!("cast through {} first",
249 CastError::NeedViaInt => "an integer",
254 CastError::IllegalCast => {
255 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
258 CastError::DifferingKinds => {
259 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
260 .note("vtable kinds may not match")
263 CastError::CastToBool => {
264 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`")
265 .span_label(self.span, "unsupported cast")
266 .help("compare with zero instead")
269 CastError::CastToChar => {
270 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0604,
271 "only `u8` can be cast as `char`, not `{}`", self.expr_ty).emit();
273 CastError::NonScalar => {
274 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0605,
275 "non-primitive cast: `{}` as `{}`",
277 fcx.ty_to_string(self.cast_ty))
278 .note("an `as` expression can only be used to convert between \
279 primitive types. Consider using the `From` trait")
282 CastError::SizedUnsizedCast => {
283 use structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
284 SizedUnsizedCastError::new(&fcx.tcx.sess,
287 fcx.ty_to_string(self.cast_ty))
288 .diagnostic().emit();
290 CastError::UnknownCastPtrKind |
291 CastError::UnknownExprPtrKind => {
292 let unknown_cast_to = match e {
293 CastError::UnknownCastPtrKind => true,
294 CastError::UnknownExprPtrKind => false,
297 let mut err = struct_span_err!(fcx.tcx.sess, self.span, E0641,
298 "cannot cast {} a pointer of an unknown kind",
299 if unknown_cast_to { "to" } else { "from" });
300 err.note("The type information given here is insufficient to check whether \
301 the pointer cast is valid");
303 err.span_suggestion_short_with_applicability(
305 "consider giving more type information",
307 Applicability::Unspecified,
315 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
316 if self.cast_ty.references_error() || self.expr_ty.references_error() {
320 let tstr = fcx.ty_to_string(self.cast_ty);
321 let mut err = type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0620,
322 "cast to unsized type: `{}` as `{}`",
323 fcx.resolve_type_vars_if_possible(&self.expr_ty),
325 match self.expr_ty.sty {
326 ty::Ref(_, _, mt) => {
327 let mtstr = match mt {
328 hir::MutMutable => "mut ",
329 hir::MutImmutable => "",
331 if self.cast_ty.is_trait() {
332 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
334 err.span_suggestion_with_applicability(
336 "try casting to a reference instead",
337 format!("&{}{}", mtstr, s),
338 Applicability::MachineApplicable,
342 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
348 "consider using an implicit coercion to `&{}{}` instead",
353 ty::Adt(def, ..) if def.is_box() => {
354 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
356 err.span_suggestion_with_applicability(
358 "try casting to a `Box` instead",
359 format!("Box<{}>", s),
360 Applicability::MachineApplicable,
363 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
369 "consider using a box or reference as appropriate");
375 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
376 let t_cast = self.cast_ty;
377 let t_expr = self.expr_ty;
378 let type_asc_or = if fcx.tcx.features().type_ascription {
379 "type ascription or "
383 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
384 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
386 ("", lint::builtin::TRIVIAL_CASTS)
388 let mut err = fcx.tcx.struct_span_lint_node(
392 &format!("trivial {}cast: `{}` as `{}`",
394 fcx.ty_to_string(t_expr),
395 fcx.ty_to_string(t_cast)));
396 err.help(&format!("cast can be replaced by coercion; this might \
397 require {}a temporary variable", type_asc_or));
401 pub fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
402 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
403 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
405 debug!("check_cast({}, {:?} as {:?})",
410 if !fcx.type_is_known_to_be_sized(self.cast_ty, self.span) {
411 self.report_cast_to_unsized_type(fcx);
412 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
413 // No sense in giving duplicate error messages
414 } else if self.try_coercion_cast(fcx) {
415 self.trivial_cast_lint(fcx);
416 debug!(" -> CoercionCast");
417 fcx.tables.borrow_mut().cast_kinds_mut().insert(self.expr.hir_id,
418 CastKind::CoercionCast);
420 match self.do_check(fcx) {
422 debug!(" -> {:?}", k);
423 fcx.tables.borrow_mut().cast_kinds_mut().insert(self.expr.hir_id, k);
425 Err(e) => self.report_cast_error(fcx, e),
430 /// Check a cast, and report an error if one exists. In some cases, this
431 /// can return Ok and create type errors in the fcx rather than returning
432 /// directly. coercion-cast is handled in check instead of here.
433 fn do_check(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Result<CastKind, CastError> {
434 use rustc::ty::cast::IntTy::*;
435 use rustc::ty::cast::CastTy::*;
437 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
438 CastTy::from_ty(self.cast_ty)) {
439 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
440 // Function item types may need to be reified before casts.
441 (None, Some(t_cast)) => {
442 if let ty::FnDef(..) = self.expr_ty.sty {
443 // Attempt a coercion to a fn pointer type.
444 let f = self.expr_ty.fn_sig(fcx.tcx);
445 let res = fcx.try_coerce(self.expr,
447 fcx.tcx.mk_fn_ptr(f),
450 return Err(CastError::NonScalar);
454 return Err(CastError::NonScalar);
457 _ => return Err(CastError::NonScalar),
460 match (t_from, t_cast) {
461 // These types have invariants! can't cast into them.
462 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
465 (_, Int(Bool)) => Err(CastError::CastToBool),
468 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
469 (_, Int(Char)) => Err(CastError::CastToChar),
473 (Int(CEnum), Float) |
474 (Int(Char), Float) => Err(CastError::NeedViaInt),
476 (Int(Bool), Ptr(_)) |
477 (Int(CEnum), Ptr(_)) |
478 (Int(Char), Ptr(_)) |
481 (Float, Ptr(_)) => Err(CastError::IllegalCast),
484 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
485 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
486 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
488 (RPtr(p), Float) => {
493 Err(CastError::NeedDeref)
497 ty::InferTy::IntVar(_) |
498 ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
499 _ => Err(CastError::NeedViaPtr),
502 _ => Err(CastError::NeedViaPtr),
506 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
507 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
508 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
511 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
512 (Int(Char), Int(_)) |
513 (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
515 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
516 Ok(CastKind::NumericCast)
521 fn check_ptr_ptr_cast(&self,
522 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
523 m_expr: ty::TypeAndMut<'tcx>,
524 m_cast: ty::TypeAndMut<'tcx>)
525 -> Result<CastKind, CastError> {
526 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
527 // ptr-ptr cast. vtables must match.
529 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
530 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
532 let cast_kind = match cast_kind {
533 // We can't cast if target pointer kind is unknown
534 None => return Err(CastError::UnknownCastPtrKind),
535 Some(cast_kind) => cast_kind,
538 // Cast to thin pointer is OK
539 if cast_kind == PointerKind::Thin {
540 return Ok(CastKind::PtrPtrCast);
543 let expr_kind = match expr_kind {
544 // We can't cast to fat pointer if source pointer kind is unknown
545 None => return Err(CastError::UnknownExprPtrKind),
546 Some(expr_kind) => expr_kind,
549 // thin -> fat? report invalid cast (don't complain about vtable kinds)
550 if expr_kind == PointerKind::Thin {
551 return Err(CastError::SizedUnsizedCast);
554 // vtable kinds must match
555 if cast_kind == expr_kind {
556 Ok(CastKind::PtrPtrCast)
558 Err(CastError::DifferingKinds)
562 fn check_fptr_ptr_cast(&self,
563 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
564 m_cast: ty::TypeAndMut<'tcx>)
565 -> Result<CastKind, CastError> {
566 // fptr-ptr cast. must be to thin ptr
568 match fcx.pointer_kind(m_cast.ty, self.span)? {
569 None => Err(CastError::UnknownCastPtrKind),
570 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
571 _ => Err(CastError::IllegalCast),
575 fn check_ptr_addr_cast(&self,
576 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
577 m_expr: ty::TypeAndMut<'tcx>)
578 -> Result<CastKind, CastError> {
579 // ptr-addr cast. must be from thin ptr
581 match fcx.pointer_kind(m_expr.ty, self.span)? {
582 None => Err(CastError::UnknownExprPtrKind),
583 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
584 _ => Err(CastError::NeedViaThinPtr),
588 fn check_ref_cast(&self,
589 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
590 m_expr: ty::TypeAndMut<'tcx>,
591 m_cast: ty::TypeAndMut<'tcx>)
592 -> Result<CastKind, CastError> {
595 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
596 if let ty::Array(ety, _) = m_expr.ty.sty {
597 // Due to the limitations of LLVM global constants,
598 // region pointers end up pointing at copies of
599 // vector elements instead of the original values.
600 // To allow raw pointers to work correctly, we
601 // need to special-case obtaining a raw pointer
602 // from a region pointer to a vector.
604 // this will report a type mismatch if needed
605 fcx.demand_eqtype(self.span, ety, m_cast.ty);
606 return Ok(CastKind::ArrayPtrCast);
610 Err(CastError::IllegalCast)
613 fn check_addr_ptr_cast(&self,
614 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
615 m_cast: TypeAndMut<'tcx>)
616 -> Result<CastKind, CastError> {
617 // ptr-addr cast. pointer must be thin.
618 match fcx.pointer_kind(m_cast.ty, self.span)? {
619 None => Err(CastError::UnknownCastPtrKind),
620 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
621 _ => Err(CastError::IllegalCast),
625 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> bool {
626 fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No).is_ok()
630 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
631 fn type_is_known_to_be_sized(&self, ty: Ty<'tcx>, span: Span) -> bool {
632 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
633 traits::type_known_to_meet_bound(self, self.param_env, ty, lang_item, span)