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, TypeFoldable};
49 use middle::ty::cast::{CastKind, CastTy};
50 use syntax::codemap::Span;
55 /// Reifies a cast check to be checked once we have full type information for
56 /// a function context.
57 pub struct CastCheck<'tcx> {
58 expr: &'tcx hir::Expr,
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: &'tcx 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_struct(self.span, |actual| {
130 format!("casting `{}` as `{}` is invalid",
132 fcx.infcx().ty_to_string(self.cast_ty))
133 }, self.expr_ty, None)
134 .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",
144 CastError::CastToBool => {
145 struct_span_err!(fcx.tcx().sess, self.span, E0054, "cannot cast as `bool`")
146 .fileline_help(self.span, "compare with zero instead")
149 CastError::CastToChar => {
150 fcx.type_error_message(self.span, |actual| {
151 format!("only `u8` can be cast as `char`, not `{}`", actual)
152 }, self.expr_ty, None);
154 CastError::NonScalar => {
155 fcx.type_error_message(self.span, |actual| {
156 format!("non-scalar cast: `{}` as `{}`",
158 fcx.infcx().ty_to_string(self.cast_ty))
159 }, self.expr_ty, None);
161 CastError::IllegalCast => {
162 fcx.type_error_message(self.span, |actual| {
163 format!("casting `{}` as `{}` is invalid",
165 fcx.infcx().ty_to_string(self.cast_ty))
166 }, self.expr_ty, None);
168 CastError::DifferingKinds => {
169 fcx.type_error_struct(self.span, |actual| {
170 format!("casting `{}` as `{}` is invalid",
172 fcx.infcx().ty_to_string(self.cast_ty))
173 }, self.expr_ty, None)
174 .fileline_note(self.span, "vtable kinds may not match")
180 fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
181 let t_cast = self.cast_ty;
182 let t_expr = self.expr_ty;
183 if t_cast.is_numeric() && t_expr.is_numeric() {
184 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
187 format!("trivial numeric cast: `{}` as `{}`. Cast can be \
188 replaced by coercion, this might require type \
189 ascription or a temporary variable",
190 fcx.infcx().ty_to_string(t_expr),
191 fcx.infcx().ty_to_string(t_cast)));
193 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
196 format!("trivial cast: `{}` as `{}`. Cast can be \
197 replaced by coercion, this might require type \
198 ascription or a temporary variable",
199 fcx.infcx().ty_to_string(t_expr),
200 fcx.infcx().ty_to_string(t_cast)));
205 pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
206 self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
207 self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
209 debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
212 if self.expr_ty.references_error() || self.cast_ty.references_error() {
213 // No sense in giving duplicate error messages
214 } else if self.try_coercion_cast(fcx) {
215 self.trivial_cast_lint(fcx);
216 debug!(" -> CoercionCast");
217 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
218 CastKind::CoercionCast);
219 } else { match self.do_check(fcx) {
221 debug!(" -> {:?}", k);
222 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
224 Err(e) => self.report_cast_error(fcx, e)
228 /// Check a cast, and report an error if one exists. In some cases, this
229 /// can return Ok and create type errors in the fcx rather than returning
230 /// directly. coercion-cast is handled in check instead of here.
231 fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
232 use middle::ty::cast::IntTy::*;
233 use middle::ty::cast::CastTy::*;
235 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
236 CastTy::from_ty(self.cast_ty)) {
237 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
238 // Function item types may need to be reified before casts.
239 (None, Some(t_cast)) => {
240 if let ty::TyFnDef(_, _, f) = self.expr_ty.sty {
241 // Attempt a coercion to a fn pointer type.
242 let res = coercion::try(fcx, self.expr,
243 fcx.tcx().mk_ty(ty::TyFnPtr(f)));
245 return Err(CastError::NonScalar);
249 return Err(CastError::NonScalar);
253 return Err(CastError::NonScalar)
257 match (t_from, t_cast) {
258 // These types have invariants! can't cast into them.
259 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
262 (_, Int(Bool)) => Err(CastError::CastToBool),
265 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
266 (_, Int(Char)) => Err(CastError::CastToChar),
269 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
270 => Err(CastError::NeedViaInt),
271 (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
272 => Err(CastError::NeedViaUsize),
275 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
276 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
277 (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
278 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
279 (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
281 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
282 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
283 (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
284 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
287 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
288 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
293 (Float, Float) => Ok(CastKind::NumericCast),
298 fn check_ptr_ptr_cast<'a>(&self,
299 fcx: &FnCtxt<'a, 'tcx>,
300 m_expr: &'tcx ty::TypeAndMut<'tcx>,
301 m_cast: &'tcx ty::TypeAndMut<'tcx>)
302 -> Result<CastKind, CastError>
304 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
306 // ptr-ptr cast. vtables must match.
308 // Cast to sized is OK
309 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
310 return Ok(CastKind::PtrPtrCast);
313 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
314 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
315 return Err(CastError::IllegalCast);
318 // vtable kinds must match
319 match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
320 (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
321 _ => Err(CastError::DifferingKinds)
325 fn check_fptr_ptr_cast<'a>(&self,
326 fcx: &FnCtxt<'a, 'tcx>,
327 m_cast: &'tcx ty::TypeAndMut<'tcx>)
328 -> Result<CastKind, CastError>
330 // fptr-ptr cast. must be to sized ptr
332 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
333 Ok(CastKind::FnPtrPtrCast)
335 Err(CastError::IllegalCast)
339 fn check_ptr_addr_cast<'a>(&self,
340 fcx: &FnCtxt<'a, 'tcx>,
341 m_expr: &'tcx ty::TypeAndMut<'tcx>)
342 -> Result<CastKind, CastError>
344 // ptr-addr cast. must be from sized ptr
346 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
347 Ok(CastKind::PtrAddrCast)
349 Err(CastError::NeedViaThinPtr)
353 fn check_ref_cast<'a>(&self,
354 fcx: &FnCtxt<'a, 'tcx>,
355 m_expr: &'tcx ty::TypeAndMut<'tcx>,
356 m_cast: &'tcx ty::TypeAndMut<'tcx>)
357 -> Result<CastKind, CastError>
361 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
362 if let ty::TyArray(ety, _) = m_expr.ty.sty {
363 // Due to the limitations of LLVM global constants,
364 // region pointers end up pointing at copies of
365 // vector elements instead of the original values.
366 // To allow raw pointers to work correctly, we
367 // need to special-case obtaining a raw pointer
368 // from a region pointer to a vector.
370 // this will report a type mismatch if needed
371 demand::eqtype(fcx, self.span, ety, m_cast.ty);
372 return Ok(CastKind::ArrayPtrCast);
376 Err(CastError::IllegalCast)
379 fn check_addr_ptr_cast<'a>(&self,
380 fcx: &FnCtxt<'a, 'tcx>,
381 m_cast: &'tcx ty::TypeAndMut<'tcx>)
382 -> Result<CastKind, CastError>
384 // ptr-addr cast. pointer must be thin.
385 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
386 Ok(CastKind::AddrPtrCast)
388 Err(CastError::IllegalCast)
392 fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
393 coercion::try(fcx, self.expr, self.cast_ty).is_ok()