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::cast::{CastKind, CastTy};
48 use middle::ty::{self, Ty, HasTypeFlags};
50 use syntax::ast::UintTy::{TyU8};
51 use syntax::codemap::Span;
53 /// Reifies a cast check to be checked once we have full type information for
54 /// a function context.
55 pub struct CastCheck<'tcx> {
62 /// The kind of the unsize info (length or vtable) - we only allow casts between
63 /// fat pointers if their unsize-infos have the same kind.
64 #[derive(Copy, Clone, PartialEq, Eq)]
65 enum UnsizeKind<'tcx> {
68 /// The unsize info of this projection
69 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
70 /// The unsize info of this parameter
71 OfParam(&'tcx ty::ParamTy)
74 /// Returns the kind of unsize information of t, or None
75 /// if t is sized or it is unknown.
76 fn unsize_kind<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>,
78 -> Option<UnsizeKind<'tcx>> {
80 ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length),
81 ty::TyTrait(ref tty) => Some(UnsizeKind::Vtable(tty.principal_def_id())),
82 ty::TyStruct(def, substs) => {
83 // FIXME(arielb1): do some kind of normalization
84 match def.struct_variant().fields.last() {
86 Some(f) => unsize_kind(fcx, f.ty(fcx.tcx(), substs))
89 // We should really try to normalize here.
90 ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)),
91 ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)),
96 #[derive(Copy, Clone)]
108 impl<'tcx> CastCheck<'tcx> {
109 pub fn new(expr: ast::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
119 fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
122 CastError::NeedViaPtr |
123 CastError::NeedViaInt |
124 CastError::NeedViaUsize => {
125 fcx.type_error_message(self.span, |actual| {
126 format!("casting `{}` as `{}` is invalid",
128 fcx.infcx().ty_to_string(self.cast_ty))
129 }, self.expr_ty, None);
130 fcx.ccx.tcx.sess.fileline_help(self.span,
131 &format!("cast through {} first", match e {
132 CastError::NeedViaPtr => "a raw pointer",
133 CastError::NeedViaInt => "an integer",
134 CastError::NeedViaUsize => "a usize",
138 CastError::CastToBool => {
139 span_err!(fcx.tcx().sess, self.span, E0054, "cannot cast as `bool`");
140 fcx.ccx.tcx.sess.fileline_help(self.span, "compare with zero instead");
142 CastError::CastToChar => {
143 fcx.type_error_message(self.span, |actual| {
144 format!("only `u8` can be cast as `char`, not `{}`", actual)
145 }, self.expr_ty, None);
147 CastError::NonScalar => {
148 fcx.type_error_message(self.span, |actual| {
149 format!("non-scalar cast: `{}` as `{}`",
151 fcx.infcx().ty_to_string(self.cast_ty))
152 }, self.expr_ty, None);
154 CastError::IllegalCast => {
155 fcx.type_error_message(self.span, |actual| {
156 format!("casting `{}` as `{}` is invalid",
158 fcx.infcx().ty_to_string(self.cast_ty))
159 }, self.expr_ty, None);
161 CastError::DifferingKinds => {
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);
167 fcx.ccx.tcx.sess.fileline_note(self.span, "vtable kinds may not match");
172 fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
173 let t_cast = self.cast_ty;
174 let t_expr = self.expr_ty;
175 if t_cast.is_numeric() && t_expr.is_numeric() {
176 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
179 format!("trivial numeric cast: `{}` as `{}`. Cast can be \
180 replaced by coercion, this might require type \
181 ascription or a temporary variable",
182 fcx.infcx().ty_to_string(t_expr),
183 fcx.infcx().ty_to_string(t_cast)));
185 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
188 format!("trivial cast: `{}` as `{}`. Cast can be \
189 replaced by coercion, this might require type \
190 ascription or a temporary variable",
191 fcx.infcx().ty_to_string(t_expr),
192 fcx.infcx().ty_to_string(t_cast)));
197 pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
198 self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
199 self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
201 debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
204 if self.expr_ty.references_error() || self.cast_ty.references_error() {
205 // No sense in giving duplicate error messages
206 } else if self.try_coercion_cast(fcx) {
207 self.trivial_cast_lint(fcx);
208 debug!(" -> CoercionCast");
209 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
210 CastKind::CoercionCast);
211 } else { match self.do_check(fcx) {
213 debug!(" -> {:?}", k);
214 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
216 Err(e) => self.report_cast_error(fcx, e)
220 /// Check a cast, and report an error if one exists. In some cases, this
221 /// can return Ok and create type errors in the fcx rather than returning
222 /// directly. coercion-cast is handled in check instead of here.
223 fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
224 use middle::cast::IntTy::*;
225 use middle::cast::CastTy::*;
227 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
228 CastTy::from_ty(self.cast_ty)) {
229 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
231 return Err(CastError::NonScalar)
235 match (t_from, t_cast) {
236 // These types have invariants! can't cast into them.
237 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
240 (_, Int(Bool)) => Err(CastError::CastToBool),
243 (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
244 (_, Int(Char)) => Err(CastError::CastToChar),
247 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
248 => Err(CastError::NeedViaInt),
249 (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
250 => Err(CastError::NeedViaUsize),
253 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
254 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
255 (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
256 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
257 (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
259 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
260 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
261 (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
262 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
265 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
266 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
271 (Float, Float) => Ok(CastKind::NumericCast),
276 fn check_ptr_ptr_cast<'a>(&self,
277 fcx: &FnCtxt<'a, 'tcx>,
278 m_expr: &'tcx ty::TypeAndMut<'tcx>,
279 m_cast: &'tcx ty::TypeAndMut<'tcx>)
280 -> Result<CastKind, CastError>
282 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
284 // ptr-ptr cast. vtables must match.
286 // Cast to sized is OK
287 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
288 return Ok(CastKind::PtrPtrCast);
291 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
292 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
293 return Err(CastError::IllegalCast);
296 // vtable kinds must match
297 match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
298 (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
299 _ => Err(CastError::DifferingKinds)
303 fn check_fptr_ptr_cast<'a>(&self,
304 fcx: &FnCtxt<'a, 'tcx>,
305 m_cast: &'tcx ty::TypeAndMut<'tcx>)
306 -> Result<CastKind, CastError>
308 // fptr-ptr cast. must be to sized ptr
310 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
311 Ok(CastKind::FnPtrPtrCast)
313 Err(CastError::IllegalCast)
317 fn check_ptr_addr_cast<'a>(&self,
318 fcx: &FnCtxt<'a, 'tcx>,
319 m_expr: &'tcx ty::TypeAndMut<'tcx>)
320 -> Result<CastKind, CastError>
322 // ptr-addr cast. must be from sized ptr
324 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
325 Ok(CastKind::PtrAddrCast)
327 Err(CastError::NeedViaPtr)
331 fn check_ref_cast<'a>(&self,
332 fcx: &FnCtxt<'a, 'tcx>,
333 m_expr: &'tcx ty::TypeAndMut<'tcx>,
334 m_cast: &'tcx ty::TypeAndMut<'tcx>)
335 -> Result<CastKind, CastError>
339 if m_expr.mutbl == ast::MutImmutable && m_cast.mutbl == ast::MutImmutable {
340 if let ty::TyArray(ety, _) = m_expr.ty.sty {
341 // Due to the limitations of LLVM global constants,
342 // region pointers end up pointing at copies of
343 // vector elements instead of the original values.
344 // To allow raw pointers to work correctly, we
345 // need to special-case obtaining a raw pointer
346 // from a region pointer to a vector.
348 // this will report a type mismatch if needed
349 demand::eqtype(fcx, self.span, ety, m_cast.ty);
350 return Ok(CastKind::ArrayPtrCast);
354 Err(CastError::IllegalCast)
357 fn check_addr_ptr_cast<'a>(&self,
358 fcx: &FnCtxt<'a, 'tcx>,
359 m_cast: &'tcx ty::TypeAndMut<'tcx>)
360 -> Result<CastKind, CastError>
362 // ptr-addr cast. pointer must be thin.
363 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
364 Ok(CastKind::AddrPtrCast)
366 Err(CastError::IllegalCast)
370 fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
371 if let Ok(()) = coercion::mk_assignty(fcx,