]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Rollup merge of #26974 - tshepang:trailing-comma, r=Gankro
[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::cast::{CastKind, CastTy};
48 use middle::ty::{self, Ty, HasTypeFlags};
49 use syntax::ast;
50 use syntax::ast::UintTy::{TyU8};
51 use syntax::codemap::Span;
52
53 /// Reifies a cast check to be checked once we have full type information for
54 /// a function context.
55 pub struct CastCheck<'tcx> {
56     expr: ast::Expr,
57     expr_ty: Ty<'tcx>,
58     cast_ty: Ty<'tcx>,
59     span: Span,
60 }
61
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> {
66     Vtable(ast::DefId),
67     Length,
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)
72 }
73
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>,
77                         t: Ty<'tcx>)
78                         -> Option<UnsizeKind<'tcx>> {
79     match t.sty {
80         ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length),
81         ty::TyTrait(ref tty) => Some(UnsizeKind::Vtable(tty.principal_def_id())),
82         ty::TyStruct(did, substs) => {
83             match fcx.tcx().struct_fields(did, substs).pop() {
84                 None => None,
85                 Some(f) => unsize_kind(fcx, f.mt.ty)
86             }
87         }
88         // We should really try to normalize here.
89         ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)),
90         ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)),
91         _ => None
92     }
93 }
94
95 #[derive(Copy, Clone)]
96 enum CastError {
97     CastToBool,
98     CastToChar,
99     DifferingKinds,
100     IllegalCast,
101     NeedViaPtr,
102     NeedViaInt,
103     NeedViaUsize,
104     NonScalar,
105 }
106
107 impl<'tcx> CastCheck<'tcx> {
108     pub fn new(expr: ast::Expr, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, span: Span)
109                -> CastCheck<'tcx> {
110         CastCheck {
111             expr: expr,
112             expr_ty: expr_ty,
113             cast_ty: cast_ty,
114             span: span,
115         }
116     }
117
118     fn report_cast_error<'a>(&self, fcx: &FnCtxt<'a, 'tcx>,
119                              e: CastError) {
120         match e {
121             CastError::NeedViaPtr |
122             CastError::NeedViaInt |
123             CastError::NeedViaUsize => {
124                 fcx.type_error_message(self.span, |actual| {
125                     format!("illegal cast; cast through {} first: `{}` as `{}`",
126                             match e {
127                                 CastError::NeedViaPtr => "a raw pointer",
128                                 CastError::NeedViaInt => "an integer",
129                                 CastError::NeedViaUsize => "a usize",
130                                 _ => unreachable!()
131                             },
132                             actual,
133                             fcx.infcx().ty_to_string(self.cast_ty))
134                 }, self.expr_ty, None)
135             }
136             CastError::CastToBool => {
137                 span_err!(fcx.tcx().sess, self.span, E0054,
138                           "cannot cast as `bool`, compare with zero instead");
139             }
140             CastError::CastToChar => {
141                 fcx.type_error_message(self.span, |actual| {
142                     format!("only `u8` can be cast as `char`, not `{}`", actual)
143                 }, self.expr_ty, None);
144             }
145             CastError::NonScalar => {
146                 fcx.type_error_message(self.span, |actual| {
147                     format!("non-scalar cast: `{}` as `{}`",
148                             actual,
149                             fcx.infcx().ty_to_string(self.cast_ty))
150                 }, self.expr_ty, None);
151             }
152             CastError::IllegalCast => {
153                 fcx.type_error_message(self.span, |actual| {
154                     format!("illegal cast: `{}` as `{}`",
155                             actual,
156                             fcx.infcx().ty_to_string(self.cast_ty))
157                 }, self.expr_ty, None);
158             }
159             CastError::DifferingKinds => {
160                 fcx.type_error_message(self.span, |actual| {
161                     format!("illegal cast: `{}` as `{}`; vtable kinds may not match",
162                             actual,
163                             fcx.infcx().ty_to_string(self.cast_ty))
164                 }, self.expr_ty, None);
165             }
166         }
167     }
168
169     fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
170         let t_cast = self.cast_ty;
171         let t_expr = self.expr_ty;
172         if t_cast.is_numeric() && t_expr.is_numeric() {
173             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
174                                     self.expr.id,
175                                     self.span,
176                                     format!("trivial numeric cast: `{}` as `{}`. Cast can be \
177                                              replaced by coercion, this might require type \
178                                              ascription or a temporary variable",
179                                             fcx.infcx().ty_to_string(t_expr),
180                                             fcx.infcx().ty_to_string(t_cast)));
181         } else {
182             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
183                                     self.expr.id,
184                                     self.span,
185                                     format!("trivial 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         }
191
192     }
193
194     pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
195         self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
196         self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
197
198         debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
199                self.cast_ty);
200
201         if self.expr_ty.references_error() || self.cast_ty.references_error() {
202             // No sense in giving duplicate error messages
203         } else if self.try_coercion_cast(fcx) {
204             self.trivial_cast_lint(fcx);
205             debug!(" -> CoercionCast");
206             fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
207                                                      CastKind::CoercionCast);
208         } else { match self.do_check(fcx) {
209             Ok(k) => {
210                 debug!(" -> {:?}", k);
211                 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
212             }
213             Err(e) => self.report_cast_error(fcx, e)
214         };}
215     }
216
217     /// Check a cast, and report an error if one exists. In some cases, this
218     /// can return Ok and create type errors in the fcx rather than returning
219     /// directly. coercion-cast is handled in check instead of here.
220     fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
221         use middle::cast::IntTy::*;
222         use middle::cast::CastTy::*;
223
224         let (t_from, t_cast) = match (CastTy::from_ty(fcx.tcx(), self.expr_ty),
225                                       CastTy::from_ty(fcx.tcx(), self.cast_ty)) {
226             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
227             _ => {
228                 return Err(CastError::NonScalar)
229             }
230         };
231
232         match (t_from, t_cast) {
233             // These types have invariants! can't cast into them.
234             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
235
236             // * -> Bool
237             (_, Int(Bool)) => Err(CastError::CastToBool),
238
239             // * -> Char
240             (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
241             (_, Int(Char)) => Err(CastError::CastToChar),
242
243             // prim -> float,ptr
244             (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
245                 => Err(CastError::NeedViaInt),
246             (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
247                 => Err(CastError::NeedViaUsize),
248
249             // ptr -> *
250             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
251             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
252             (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
253             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
254             (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
255             // * -> ptr
256             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
257             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
258             (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
259             (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
260
261             // prim -> prim
262             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
263             (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
264
265             (Int(_), Int(_)) |
266             (Int(_), Float) |
267             (Float, Int(_)) |
268             (Float, Float) => Ok(CastKind::NumericCast),
269
270         }
271     }
272
273     fn check_ptr_ptr_cast<'a>(&self,
274                               fcx: &FnCtxt<'a, 'tcx>,
275                               m_expr: &'tcx ty::mt<'tcx>,
276                               m_cast: &'tcx ty::mt<'tcx>)
277                               -> Result<CastKind, CastError>
278     {
279         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
280                m_expr, m_cast);
281         // ptr-ptr cast. vtables must match.
282
283         // Cast to sized is OK
284         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
285             return Ok(CastKind::PtrPtrCast);
286         }
287
288         // sized -> unsized? report illegal cast (don't complain about vtable kinds)
289         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
290             return Err(CastError::IllegalCast);
291         }
292
293         // vtable kinds must match
294         match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
295             (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
296             _ => Err(CastError::DifferingKinds)
297         }
298     }
299
300     fn check_fptr_ptr_cast<'a>(&self,
301                                fcx: &FnCtxt<'a, 'tcx>,
302                                m_cast: &'tcx ty::mt<'tcx>)
303                                -> Result<CastKind, CastError>
304     {
305         // fptr-ptr cast. must be to sized ptr
306
307         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
308             Ok(CastKind::FnPtrPtrCast)
309         } else {
310             Err(CastError::IllegalCast)
311         }
312     }
313
314     fn check_ptr_addr_cast<'a>(&self,
315                                fcx: &FnCtxt<'a, 'tcx>,
316                                m_expr: &'tcx ty::mt<'tcx>)
317                                -> Result<CastKind, CastError>
318     {
319         // ptr-addr cast. must be from sized ptr
320
321         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
322             Ok(CastKind::PtrAddrCast)
323         } else {
324             Err(CastError::NeedViaPtr)
325         }
326     }
327
328     fn check_ref_cast<'a>(&self,
329                           fcx: &FnCtxt<'a, 'tcx>,
330                           m_expr: &'tcx ty::mt<'tcx>,
331                           m_cast: &'tcx ty::mt<'tcx>)
332                           -> Result<CastKind, CastError>
333     {
334         // array-ptr-cast.
335
336         if m_expr.mutbl == ast::MutImmutable && m_cast.mutbl == ast::MutImmutable {
337             if let ty::TyArray(ety, _) = m_expr.ty.sty {
338                 // Due to the limitations of LLVM global constants,
339                 // region pointers end up pointing at copies of
340                 // vector elements instead of the original values.
341                 // To allow raw pointers to work correctly, we
342                 // need to special-case obtaining a raw pointer
343                 // from a region pointer to a vector.
344
345                 // this will report a type mismatch if needed
346                 demand::eqtype(fcx, self.span, ety, m_cast.ty);
347                 return Ok(CastKind::ArrayPtrCast);
348             }
349         }
350
351         Err(CastError::IllegalCast)
352     }
353
354     fn check_addr_ptr_cast<'a>(&self,
355                                fcx: &FnCtxt<'a, 'tcx>,
356                                m_cast: &'tcx ty::mt<'tcx>)
357                                -> Result<CastKind, CastError>
358     {
359         // ptr-addr cast. pointer must be thin.
360         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
361            Ok(CastKind::AddrPtrCast)
362         } else {
363            Err(CastError::IllegalCast)
364         }
365     }
366
367     fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
368         if let Ok(()) = coercion::mk_assignty(fcx,
369                                               &self.expr,
370                                               self.expr_ty,
371                                               self.cast_ty) {
372             true
373         } else {
374             false
375         }
376     }
377
378 }