]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
b5cd5d7f8e5a38d391ab2f056ff70de16cc60d56
[rust.git] / src / librustc_typeck / check / cast.rs
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.
4 //
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.
10
11 //! Code for type-checking cast expressions.
12 //!
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*
27 //!
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`).
32 //!
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.
36 //!
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`).
40
41 use super::coercion;
42 use super::demand;
43 use super::FnCtxt;
44 use super::structurally_resolved_type;
45
46 use lint;
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;
51 use rustc_front::hir;
52 use syntax::ast;
53
54
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,
59     expr_ty: Ty<'tcx>,
60     cast_ty: Ty<'tcx>,
61     span: Span,
62 }
63
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> {
68     Vtable(DefId),
69     Length,
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)
74 }
75
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>,
79                         t: Ty<'tcx>)
80                         -> Option<UnsizeKind<'tcx>> {
81     match t.sty {
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() {
87                 None => None,
88                 Some(f) => unsize_kind(fcx, f.ty(fcx.tcx(), substs))
89             }
90         }
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)),
94         _ => None
95     }
96 }
97
98 #[derive(Copy, Clone)]
99 enum CastError {
100     CastToBool,
101     CastToChar,
102     DifferingKinds,
103     IllegalCast,
104     NeedViaPtr,
105     NeedViaThinPtr,
106     NeedViaInt,
107     NeedViaUsize,
108     NonScalar,
109 }
110
111 impl<'tcx> CastCheck<'tcx> {
112     pub fn new(expr: &'tcx hir::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
113                -> CastCheck<'tcx> {
114         CastCheck {
115             expr: expr,
116             expr_ty: expr_ty,
117             cast_ty: cast_ty,
118             span: span,
119         }
120     }
121
122     fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
123                              e: CastError) {
124         match e {
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",
131                             actual,
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",
140                             _ => unreachable!()
141                         }))
142                     .emit();
143             }
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")
147                     .emit();
148             }
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);
153             }
154             CastError::NonScalar => {
155                 fcx.type_error_message(self.span, |actual| {
156                     format!("non-scalar cast: `{}` as `{}`",
157                             actual,
158                             fcx.infcx().ty_to_string(self.cast_ty))
159                 }, self.expr_ty, None);
160             }
161             CastError::IllegalCast => {
162                 fcx.type_error_message(self.span, |actual| {
163                     format!("casting `{}` as `{}` is invalid",
164                             actual,
165                             fcx.infcx().ty_to_string(self.cast_ty))
166                 }, self.expr_ty, None);
167             }
168             CastError::DifferingKinds => {
169                 fcx.type_error_struct(self.span, |actual| {
170                     format!("casting `{}` as `{}` is invalid",
171                             actual,
172                             fcx.infcx().ty_to_string(self.cast_ty))
173                 }, self.expr_ty, None)
174                     .fileline_note(self.span, "vtable kinds may not match")
175                     .emit();
176             }
177         }
178     }
179
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,
185                                     self.expr.id,
186                                     self.span,
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)));
192         } else {
193             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
194                                     self.expr.id,
195                                     self.span,
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)));
201         }
202
203     }
204
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);
208
209         debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
210                self.cast_ty);
211
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) {
220             Ok(k) => {
221                 debug!(" -> {:?}", k);
222                 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
223             }
224             Err(e) => self.report_cast_error(fcx, e)
225         };}
226     }
227
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::*;
234
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)));
244                     if !res.is_ok() {
245                         return Err(CastError::NonScalar);
246                     }
247                     (FnPtr, t_cast)
248                 } else {
249                     return Err(CastError::NonScalar);
250                 }
251             }
252             _ => {
253                 return Err(CastError::NonScalar)
254             }
255         };
256
257         match (t_from, t_cast) {
258             // These types have invariants! can't cast into them.
259             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
260
261             // * -> Bool
262             (_, Int(Bool)) => Err(CastError::CastToBool),
263
264             // * -> Char
265             (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
266             (_, Int(Char)) => Err(CastError::CastToChar),
267
268             // prim -> float,ptr
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),
273
274             // ptr -> *
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),
280             // * -> ptr
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
285
286             // prim -> prim
287             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
288             (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
289
290             (Int(_), Int(_)) |
291             (Int(_), Float) |
292             (Float, Int(_)) |
293             (Float, Float) => Ok(CastKind::NumericCast),
294
295         }
296     }
297
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>
303     {
304         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
305                m_expr, m_cast);
306         // ptr-ptr cast. vtables must match.
307
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);
311         }
312
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);
316         }
317
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)
322         }
323     }
324
325     fn check_fptr_ptr_cast<'a>(&self,
326                                fcx: &FnCtxt<'a, 'tcx>,
327                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
328                                -> Result<CastKind, CastError>
329     {
330         // fptr-ptr cast. must be to sized ptr
331
332         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
333             Ok(CastKind::FnPtrPtrCast)
334         } else {
335             Err(CastError::IllegalCast)
336         }
337     }
338
339     fn check_ptr_addr_cast<'a>(&self,
340                                fcx: &FnCtxt<'a, 'tcx>,
341                                m_expr: &'tcx ty::TypeAndMut<'tcx>)
342                                -> Result<CastKind, CastError>
343     {
344         // ptr-addr cast. must be from sized ptr
345
346         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
347             Ok(CastKind::PtrAddrCast)
348         } else {
349             Err(CastError::NeedViaThinPtr)
350         }
351     }
352
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>
358     {
359         // array-ptr-cast.
360
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.
369
370                 // this will report a type mismatch if needed
371                 demand::eqtype(fcx, self.span, ety, m_cast.ty);
372                 return Ok(CastKind::ArrayPtrCast);
373             }
374         }
375
376         Err(CastError::IllegalCast)
377     }
378
379     fn check_addr_ptr_cast<'a>(&self,
380                                fcx: &FnCtxt<'a, 'tcx>,
381                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
382                                -> Result<CastKind, CastError>
383     {
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)
387         } else {
388            Err(CastError::IllegalCast)
389         }
390     }
391
392     fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
393         coercion::try(fcx, self.expr, self.cast_ty).is_ok()
394     }
395
396 }