]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Use ast attributes every where (remove HIR attributes).
[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, HasTypeFlags};
49 use middle::ty::cast::{CastKind, CastTy};
50 use syntax::codemap::Span;
51 use rustc_front::hir;
52 use syntax::ast;
53 use syntax::ast::UintTy::TyU8;
54
55
56 /// Reifies a cast check to be checked once we have full type information for
57 /// a function context.
58 pub struct CastCheck<'tcx> {
59     expr: hir::Expr,
60     expr_ty: Ty<'tcx>,
61     cast_ty: Ty<'tcx>,
62     span: Span,
63 }
64
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> {
69     Vtable(DefId),
70     Length,
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)
75 }
76
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>,
80                         t: Ty<'tcx>)
81                         -> Option<UnsizeKind<'tcx>> {
82     match t.sty {
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() {
88                 None => None,
89                 Some(f) => unsize_kind(fcx, f.ty(fcx.tcx(), substs))
90             }
91         }
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)),
95         _ => None
96     }
97 }
98
99 #[derive(Copy, Clone)]
100 enum CastError {
101     CastToBool,
102     CastToChar,
103     DifferingKinds,
104     IllegalCast,
105     NeedViaPtr,
106     NeedViaThinPtr,
107     NeedViaInt,
108     NeedViaUsize,
109     NonScalar,
110 }
111
112 impl<'tcx> CastCheck<'tcx> {
113     pub fn new(expr: hir::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
114                -> CastCheck<'tcx> {
115         CastCheck {
116             expr: expr,
117             expr_ty: expr_ty,
118             cast_ty: cast_ty,
119             span: span,
120         }
121     }
122
123     fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
124                              e: CastError) {
125         match e {
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",
132                             actual,
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",
141                         _ => unreachable!()
142                 }));
143             }
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");
147             }
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);
152             }
153             CastError::NonScalar => {
154                 fcx.type_error_message(self.span, |actual| {
155                     format!("non-scalar cast: `{}` as `{}`",
156                             actual,
157                             fcx.infcx().ty_to_string(self.cast_ty))
158                 }, self.expr_ty, None);
159             }
160             CastError::IllegalCast => {
161                 fcx.type_error_message(self.span, |actual| {
162                     format!("casting `{}` as `{}` is invalid",
163                             actual,
164                             fcx.infcx().ty_to_string(self.cast_ty))
165                 }, self.expr_ty, None);
166             }
167             CastError::DifferingKinds => {
168                 fcx.type_error_message(self.span, |actual| {
169                     format!("casting `{}` as `{}` is invalid",
170                             actual,
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");
174             }
175         }
176     }
177
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,
183                                     self.expr.id,
184                                     self.span,
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)));
190         } else {
191             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
192                                     self.expr.id,
193                                     self.span,
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)));
199         }
200
201     }
202
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);
206
207         debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
208                self.cast_ty);
209
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) {
218             Ok(k) => {
219                 debug!(" -> {:?}", k);
220                 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
221             }
222             Err(e) => self.report_cast_error(fcx, e)
223         };}
224     }
225
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::*;
232
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),
236             _ => {
237                 return Err(CastError::NonScalar)
238             }
239         };
240
241         match (t_from, t_cast) {
242             // These types have invariants! can't cast into them.
243             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
244
245             // * -> Bool
246             (_, Int(Bool)) => Err(CastError::CastToBool),
247
248             // * -> Char
249             (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
250             (_, Int(Char)) => Err(CastError::CastToChar),
251
252             // prim -> float,ptr
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),
257
258             // ptr -> *
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),
264             // * -> ptr
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
269
270             // prim -> prim
271             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
272             (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
273
274             (Int(_), Int(_)) |
275             (Int(_), Float) |
276             (Float, Int(_)) |
277             (Float, Float) => Ok(CastKind::NumericCast),
278
279         }
280     }
281
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>
287     {
288         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
289                m_expr, m_cast);
290         // ptr-ptr cast. vtables must match.
291
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);
295         }
296
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);
300         }
301
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)
306         }
307     }
308
309     fn check_fptr_ptr_cast<'a>(&self,
310                                fcx: &FnCtxt<'a, 'tcx>,
311                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
312                                -> Result<CastKind, CastError>
313     {
314         // fptr-ptr cast. must be to sized ptr
315
316         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
317             Ok(CastKind::FnPtrPtrCast)
318         } else {
319             Err(CastError::IllegalCast)
320         }
321     }
322
323     fn check_ptr_addr_cast<'a>(&self,
324                                fcx: &FnCtxt<'a, 'tcx>,
325                                m_expr: &'tcx ty::TypeAndMut<'tcx>)
326                                -> Result<CastKind, CastError>
327     {
328         // ptr-addr cast. must be from sized ptr
329
330         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
331             Ok(CastKind::PtrAddrCast)
332         } else {
333             Err(CastError::NeedViaThinPtr)
334         }
335     }
336
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>
342     {
343         // array-ptr-cast.
344
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.
353
354                 // this will report a type mismatch if needed
355                 demand::eqtype(fcx, self.span, ety, m_cast.ty);
356                 return Ok(CastKind::ArrayPtrCast);
357             }
358         }
359
360         Err(CastError::IllegalCast)
361     }
362
363     fn check_addr_ptr_cast<'a>(&self,
364                                fcx: &FnCtxt<'a, 'tcx>,
365                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
366                                -> Result<CastKind, CastError>
367     {
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)
371         } else {
372            Err(CastError::IllegalCast)
373         }
374     }
375
376     fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
377         if let Ok(()) = coercion::mk_assignty(fcx,
378                                               &self.expr,
379                                               self.expr_ty,
380                                               self.cast_ty) {
381             true
382         } else {
383             false
384         }
385     }
386
387 }