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;
53 use syntax::ast::UintTy::TyU8;
56 /// Reifies a cast check to be checked once we have full type information for
57 /// a function context.
58 pub struct CastCheck<'tcx> {
65 /// The kind of the unsize info (length or vtable) - we only allow casts between
66 /// fat pointers if their unsize-infos have the same kind.
67 #[derive(Copy, Clone, PartialEq, Eq)]
68 enum UnsizeKind<'tcx> {
71 /// The unsize info of this projection
72 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
73 /// The unsize info of this parameter
74 OfParam(&'tcx ty::ParamTy)
77 /// Returns the kind of unsize information of t, or None
78 /// if t is sized or it is unknown.
79 fn unsize_kind<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>,
81 -> Option<UnsizeKind<'tcx>> {
83 ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length),
84 ty::TyTrait(ref tty) => Some(UnsizeKind::Vtable(tty.principal_def_id())),
85 ty::TyStruct(def, substs) => {
86 // FIXME(arielb1): do some kind of normalization
87 match def.struct_variant().fields.last() {
89 Some(f) => unsize_kind(fcx, f.ty(fcx.tcx(), substs))
92 // We should really try to normalize here.
93 ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)),
94 ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)),
99 #[derive(Copy, Clone)]
112 impl<'tcx> CastCheck<'tcx> {
113 pub fn new(expr: hir::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
123 fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
126 CastError::NeedViaPtr |
127 CastError::NeedViaThinPtr |
128 CastError::NeedViaInt |
129 CastError::NeedViaUsize => {
130 fcx.type_error_message(self.span, |actual| {
131 format!("casting `{}` as `{}` is invalid",
133 fcx.infcx().ty_to_string(self.cast_ty))
134 }, self.expr_ty, None);
135 fcx.ccx.tcx.sess.fileline_help(self.span,
136 &format!("cast through {} first", match e {
137 CastError::NeedViaPtr => "a raw pointer",
138 CastError::NeedViaThinPtr => "a thin pointer",
139 CastError::NeedViaInt => "an integer",
140 CastError::NeedViaUsize => "a usize",
144 CastError::CastToBool => {
145 span_err!(fcx.tcx().sess, self.span, E0054, "cannot cast as `bool`");
146 fcx.ccx.tcx.sess.fileline_help(self.span, "compare with zero instead");
148 CastError::CastToChar => {
149 fcx.type_error_message(self.span, |actual| {
150 format!("only `u8` can be cast as `char`, not `{}`", actual)
151 }, self.expr_ty, None);
153 CastError::NonScalar => {
154 fcx.type_error_message(self.span, |actual| {
155 format!("non-scalar cast: `{}` as `{}`",
157 fcx.infcx().ty_to_string(self.cast_ty))
158 }, self.expr_ty, None);
160 CastError::IllegalCast => {
161 fcx.type_error_message(self.span, |actual| {
162 format!("casting `{}` as `{}` is invalid",
164 fcx.infcx().ty_to_string(self.cast_ty))
165 }, self.expr_ty, None);
167 CastError::DifferingKinds => {
168 fcx.type_error_message(self.span, |actual| {
169 format!("casting `{}` as `{}` is invalid",
171 fcx.infcx().ty_to_string(self.cast_ty))
172 }, self.expr_ty, None);
173 fcx.ccx.tcx.sess.fileline_note(self.span, "vtable kinds may not match");
178 fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
179 let t_cast = self.cast_ty;
180 let t_expr = self.expr_ty;
181 if t_cast.is_numeric() && t_expr.is_numeric() {
182 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
185 format!("trivial numeric cast: `{}` as `{}`. Cast can be \
186 replaced by coercion, this might require type \
187 ascription or a temporary variable",
188 fcx.infcx().ty_to_string(t_expr),
189 fcx.infcx().ty_to_string(t_cast)));
191 fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
194 format!("trivial cast: `{}` as `{}`. Cast can be \
195 replaced by coercion, this might require type \
196 ascription or a temporary variable",
197 fcx.infcx().ty_to_string(t_expr),
198 fcx.infcx().ty_to_string(t_cast)));
203 pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
204 self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
205 self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
207 debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
210 if self.expr_ty.references_error() || self.cast_ty.references_error() {
211 // No sense in giving duplicate error messages
212 } else if self.try_coercion_cast(fcx) {
213 self.trivial_cast_lint(fcx);
214 debug!(" -> CoercionCast");
215 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
216 CastKind::CoercionCast);
217 } else { match self.do_check(fcx) {
219 debug!(" -> {:?}", k);
220 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
222 Err(e) => self.report_cast_error(fcx, e)
226 /// Check a cast, and report an error if one exists. In some cases, this
227 /// can return Ok and create type errors in the fcx rather than returning
228 /// directly. coercion-cast is handled in check instead of here.
229 fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
230 use middle::ty::cast::IntTy::*;
231 use middle::ty::cast::CastTy::*;
233 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
234 CastTy::from_ty(self.cast_ty)) {
235 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
237 return Err(CastError::NonScalar)
241 match (t_from, t_cast) {
242 // These types have invariants! can't cast into them.
243 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
246 (_, Int(Bool)) => Err(CastError::CastToBool),
249 (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
250 (_, Int(Char)) => Err(CastError::CastToChar),
253 (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
254 => Err(CastError::NeedViaInt),
255 (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
256 => Err(CastError::NeedViaUsize),
259 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
260 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
261 (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
262 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
263 (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
265 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
266 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
267 (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
268 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
271 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
272 (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
277 (Float, Float) => Ok(CastKind::NumericCast),
282 fn check_ptr_ptr_cast<'a>(&self,
283 fcx: &FnCtxt<'a, 'tcx>,
284 m_expr: &'tcx ty::TypeAndMut<'tcx>,
285 m_cast: &'tcx ty::TypeAndMut<'tcx>)
286 -> Result<CastKind, CastError>
288 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
290 // ptr-ptr cast. vtables must match.
292 // Cast to sized is OK
293 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
294 return Ok(CastKind::PtrPtrCast);
297 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
298 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
299 return Err(CastError::IllegalCast);
302 // vtable kinds must match
303 match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
304 (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
305 _ => Err(CastError::DifferingKinds)
309 fn check_fptr_ptr_cast<'a>(&self,
310 fcx: &FnCtxt<'a, 'tcx>,
311 m_cast: &'tcx ty::TypeAndMut<'tcx>)
312 -> Result<CastKind, CastError>
314 // fptr-ptr cast. must be to sized ptr
316 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
317 Ok(CastKind::FnPtrPtrCast)
319 Err(CastError::IllegalCast)
323 fn check_ptr_addr_cast<'a>(&self,
324 fcx: &FnCtxt<'a, 'tcx>,
325 m_expr: &'tcx ty::TypeAndMut<'tcx>)
326 -> Result<CastKind, CastError>
328 // ptr-addr cast. must be from sized ptr
330 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
331 Ok(CastKind::PtrAddrCast)
333 Err(CastError::NeedViaThinPtr)
337 fn check_ref_cast<'a>(&self,
338 fcx: &FnCtxt<'a, 'tcx>,
339 m_expr: &'tcx ty::TypeAndMut<'tcx>,
340 m_cast: &'tcx ty::TypeAndMut<'tcx>)
341 -> Result<CastKind, CastError>
345 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
346 if let ty::TyArray(ety, _) = m_expr.ty.sty {
347 // Due to the limitations of LLVM global constants,
348 // region pointers end up pointing at copies of
349 // vector elements instead of the original values.
350 // To allow raw pointers to work correctly, we
351 // need to special-case obtaining a raw pointer
352 // from a region pointer to a vector.
354 // this will report a type mismatch if needed
355 demand::eqtype(fcx, self.span, ety, m_cast.ty);
356 return Ok(CastKind::ArrayPtrCast);
360 Err(CastError::IllegalCast)
363 fn check_addr_ptr_cast<'a>(&self,
364 fcx: &FnCtxt<'a, 'tcx>,
365 m_cast: &'tcx ty::TypeAndMut<'tcx>)
366 -> Result<CastKind, CastError>
368 // ptr-addr cast. pointer must be thin.
369 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
370 Ok(CastKind::AddrPtrCast)
372 Err(CastError::IllegalCast)
376 fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
377 if let Ok(()) = coercion::mk_assignty(fcx,