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 //! unsize_kind(`T`) = unsize_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 unsize_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`).
44 use super::structurally_resolved_type;
47 use middle::def_id::DefId;
48 use middle::ty::{self, Ty, HasTypeFlags};
49 use middle::ty::cast::{CastKind, CastTy};
50 use syntax::codemap::Span;
52 use rustc_front::hir::UintTy::TyU8;
55 /// Reifies a cast check to be checked once we have full type information for
56 /// a function context.
57 pub struct CastCheck<'tcx> {
64 /// The kind of the unsize info (length or vtable) - we only allow casts between
65 /// fat pointers if their unsize-infos have the same kind.
66 #[derive(Copy, Clone, PartialEq, Eq)]
67 enum UnsizeKind<'tcx> {
70 /// The unsize info of this projection
71 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
72 /// The unsize info of this parameter
73 OfParam(&'tcx ty::ParamTy)
76 /// Returns the kind of unsize information of t, or None
77 /// if t is sized or it is unknown.
78 fn unsize_kind<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>,
80 -> Option<UnsizeKind<'tcx>> {
82 ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length),
83 ty::TyTrait(ref tty) => Some(UnsizeKind::Vtable(tty.principal_def_id())),
84 ty::TyStruct(def, substs) => {
85 // FIXME(arielb1): do some kind of normalization
86 match def.struct_variant().fields.last() {
88 Some(f) => unsize_kind(fcx, f.ty(fcx.tcx(), substs))
91 // We should really try to normalize here.
92 ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)),
93 ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)),
98 #[derive(Copy, Clone)]
111 impl<'tcx> CastCheck<'tcx> {
112 pub fn new(expr: hir::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
122 fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
125 CastError::NeedViaPtr |
126 CastError::NeedViaThinPtr |
127 CastError::NeedViaInt |
128 CastError::NeedViaUsize => {
129 fcx.type_error_message(self.span, |actual| {
130 format!("casting `{}` as `{}` is invalid",
132 fcx.infcx().ty_to_string(self.cast_ty))
133 }, self.expr_ty, None);
134 fcx.ccx.tcx.sess.fileline_help(self.span,
135 &format!("cast through {} first", match e {
136 CastError::NeedViaPtr => "a raw pointer",
137 CastError::NeedViaThinPtr => "a thin pointer",
138 CastError::NeedViaInt => "an integer",
139 CastError::NeedViaUsize => "a usize",
143 CastError::CastToBool => {
144 span_err!(fcx.tcx().sess, self.span, E0054, "cannot cast as `bool`");
145 fcx.ccx.tcx.sess.fileline_help(self.span, "compare with zero instead");
147 CastError::CastToChar => {
148 fcx.type_error_message(self.span, |actual| {
149 format!("only `u8` can be cast as `char`, not `{}`", actual)
150 }, self.expr_ty, None);
152 CastError::NonScalar => {
153 fcx.type_error_message(self.span, |actual| {
154 format!("non-scalar cast: `{}` as `{}`",
156 fcx.infcx().ty_to_string(self.cast_ty))
157 }, self.expr_ty, None);
159 CastError::IllegalCast => {
160 fcx.type_error_message(self.span, |actual| {
161 format!("casting `{}` as `{}` is invalid",
163 fcx.infcx().ty_to_string(self.cast_ty))
164 }, self.expr_ty, None);
166 CastError::DifferingKinds => {
167 fcx.type_error_message(self.span, |actual| {
168 format!("casting `{}` as `{}` is invalid",
170 fcx.infcx().ty_to_string(self.cast_ty))
171 }, self.expr_ty, None);
172 fcx.ccx.tcx.sess.fileline_note(self.span, "vtable kinds may not match");
177 fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
178 let t_cast = self.cast_ty;
179 let t_expr = self.expr_ty;
180 if t_cast.is_numeric() && t_expr.is_numeric() {
181 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
184 format!("trivial numeric cast: `{}` as `{}`. Cast can be \
185 replaced by coercion, this might require type \
186 ascription or a temporary variable",
187 fcx.infcx().ty_to_string(t_expr),
188 fcx.infcx().ty_to_string(t_cast)));
190 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
193 format!("trivial cast: `{}` as `{}`. Cast can be \
194 replaced by coercion, this might require type \
195 ascription or a temporary variable",
196 fcx.infcx().ty_to_string(t_expr),
197 fcx.infcx().ty_to_string(t_cast)));
202 pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
203 self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
204 self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
206 debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
209 if self.expr_ty.references_error() || self.cast_ty.references_error() {
210 // No sense in giving duplicate error messages
211 } else if self.try_coercion_cast(fcx) {
212 self.trivial_cast_lint(fcx);
213 debug!(" -> CoercionCast");
214 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
215 CastKind::CoercionCast);
216 } else { match self.do_check(fcx) {
218 debug!(" -> {:?}", k);
219 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
221 Err(e) => self.report_cast_error(fcx, e)
225 /// Check a cast, and report an error if one exists. In some cases, this
226 /// can return Ok and create type errors in the fcx rather than returning
227 /// directly. coercion-cast is handled in check instead of here.
228 fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
229 use middle::ty::cast::IntTy::*;
230 use middle::ty::cast::CastTy::*;
232 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
233 CastTy::from_ty(self.cast_ty)) {
234 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
236 return Err(CastError::NonScalar)
240 match (t_from, t_cast) {
241 // These types have invariants! can't cast into them.
242 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
245 (_, Int(Bool)) => Err(CastError::CastToBool),
248 (Int(U(hir::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
249 (_, Int(Char)) => Err(CastError::CastToChar),
252 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
253 => Err(CastError::NeedViaInt),
254 (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
255 => Err(CastError::NeedViaUsize),
258 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
259 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
260 (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
261 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
262 (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
264 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
265 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
266 (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
267 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
270 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
271 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
276 (Float, Float) => Ok(CastKind::NumericCast),
281 fn check_ptr_ptr_cast<'a>(&self,
282 fcx: &FnCtxt<'a, 'tcx>,
283 m_expr: &'tcx ty::TypeAndMut<'tcx>,
284 m_cast: &'tcx ty::TypeAndMut<'tcx>)
285 -> Result<CastKind, CastError>
287 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
289 // ptr-ptr cast. vtables must match.
291 // Cast to sized is OK
292 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
293 return Ok(CastKind::PtrPtrCast);
296 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
297 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
298 return Err(CastError::IllegalCast);
301 // vtable kinds must match
302 match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
303 (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
304 _ => Err(CastError::DifferingKinds)
308 fn check_fptr_ptr_cast<'a>(&self,
309 fcx: &FnCtxt<'a, 'tcx>,
310 m_cast: &'tcx ty::TypeAndMut<'tcx>)
311 -> Result<CastKind, CastError>
313 // fptr-ptr cast. must be to sized ptr
315 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
316 Ok(CastKind::FnPtrPtrCast)
318 Err(CastError::IllegalCast)
322 fn check_ptr_addr_cast<'a>(&self,
323 fcx: &FnCtxt<'a, 'tcx>,
324 m_expr: &'tcx ty::TypeAndMut<'tcx>)
325 -> Result<CastKind, CastError>
327 // ptr-addr cast. must be from sized ptr
329 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
330 Ok(CastKind::PtrAddrCast)
332 Err(CastError::NeedViaThinPtr)
336 fn check_ref_cast<'a>(&self,
337 fcx: &FnCtxt<'a, 'tcx>,
338 m_expr: &'tcx ty::TypeAndMut<'tcx>,
339 m_cast: &'tcx ty::TypeAndMut<'tcx>)
340 -> Result<CastKind, CastError>
344 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
345 if let ty::TyArray(ety, _) = m_expr.ty.sty {
346 // Due to the limitations of LLVM global constants,
347 // region pointers end up pointing at copies of
348 // vector elements instead of the original values.
349 // To allow raw pointers to work correctly, we
350 // need to special-case obtaining a raw pointer
351 // from a region pointer to a vector.
353 // this will report a type mismatch if needed
354 demand::eqtype(fcx, self.span, ety, m_cast.ty);
355 return Ok(CastKind::ArrayPtrCast);
359 Err(CastError::IllegalCast)
362 fn check_addr_ptr_cast<'a>(&self,
363 fcx: &FnCtxt<'a, 'tcx>,
364 m_cast: &'tcx ty::TypeAndMut<'tcx>)
365 -> Result<CastKind, CastError>
367 // ptr-addr cast. pointer must be thin.
368 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
369 Ok(CastKind::AddrPtrCast)
371 Err(CastError::IllegalCast)
375 fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
376 if let Ok(()) = coercion::mk_assignty(fcx,