]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Rollup merge of #27326 - steveklabnik:doc_show_use, 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!("casting `{}` as `{}` is invalid",
126                             actual,
127                             fcx.infcx().ty_to_string(self.cast_ty))
128                 }, self.expr_ty, None);
129                 fcx.ccx.tcx.sess.fileline_help(self.span,
130                     &format!("cast through {} first", match e {
131                         CastError::NeedViaPtr => "a raw pointer",
132                         CastError::NeedViaInt => "an integer",
133                         CastError::NeedViaUsize => "a usize",
134                         _ => unreachable!()
135                 }));
136             }
137             CastError::CastToBool => {
138                 span_err!(fcx.tcx().sess, self.span, E0054, "cannot cast as `bool`");
139                 fcx.ccx.tcx.sess.fileline_help(self.span, "compare with zero instead");
140             }
141             CastError::CastToChar => {
142                 fcx.type_error_message(self.span, |actual| {
143                     format!("only `u8` can be cast as `char`, not `{}`", actual)
144                 }, self.expr_ty, None);
145             }
146             CastError::NonScalar => {
147                 fcx.type_error_message(self.span, |actual| {
148                     format!("non-scalar cast: `{}` as `{}`",
149                             actual,
150                             fcx.infcx().ty_to_string(self.cast_ty))
151                 }, self.expr_ty, None);
152             }
153             CastError::IllegalCast => {
154                 fcx.type_error_message(self.span, |actual| {
155                     format!("casting `{}` as `{}` is invalid",
156                             actual,
157                             fcx.infcx().ty_to_string(self.cast_ty))
158                 }, self.expr_ty, None);
159             }
160             CastError::DifferingKinds => {
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                 fcx.ccx.tcx.sess.fileline_note(self.span, "vtable kinds may not match");
167             }
168         }
169     }
170
171     fn trivial_cast_lint<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) {
172         let t_cast = self.cast_ty;
173         let t_expr = self.expr_ty;
174         if t_cast.is_numeric() && t_expr.is_numeric() {
175             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
176                                     self.expr.id,
177                                     self.span,
178                                     format!("trivial numeric cast: `{}` as `{}`. Cast can be \
179                                              replaced by coercion, this might require type \
180                                              ascription or a temporary variable",
181                                             fcx.infcx().ty_to_string(t_expr),
182                                             fcx.infcx().ty_to_string(t_cast)));
183         } else {
184             fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
185                                     self.expr.id,
186                                     self.span,
187                                     format!("trivial 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         }
193
194     }
195
196     pub fn check<'a>(mut self, fcx: &FnCtxt<'a, 'tcx>) {
197         self.expr_ty = structurally_resolved_type(fcx, self.span, self.expr_ty);
198         self.cast_ty = structurally_resolved_type(fcx, self.span, self.cast_ty);
199
200         debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty,
201                self.cast_ty);
202
203         if self.expr_ty.references_error() || self.cast_ty.references_error() {
204             // No sense in giving duplicate error messages
205         } else if self.try_coercion_cast(fcx) {
206             self.trivial_cast_lint(fcx);
207             debug!(" -> CoercionCast");
208             fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id,
209                                                      CastKind::CoercionCast);
210         } else { match self.do_check(fcx) {
211             Ok(k) => {
212                 debug!(" -> {:?}", k);
213                 fcx.tcx().cast_kinds.borrow_mut().insert(self.expr.id, k);
214             }
215             Err(e) => self.report_cast_error(fcx, e)
216         };}
217     }
218
219     /// Check a cast, and report an error if one exists. In some cases, this
220     /// can return Ok and create type errors in the fcx rather than returning
221     /// directly. coercion-cast is handled in check instead of here.
222     fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
223         use middle::cast::IntTy::*;
224         use middle::cast::CastTy::*;
225
226         let (t_from, t_cast) = match (CastTy::from_ty(fcx.tcx(), self.expr_ty),
227                                       CastTy::from_ty(fcx.tcx(), self.cast_ty)) {
228             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
229             _ => {
230                 return Err(CastError::NonScalar)
231             }
232         };
233
234         match (t_from, t_cast) {
235             // These types have invariants! can't cast into them.
236             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
237
238             // * -> Bool
239             (_, Int(Bool)) => Err(CastError::CastToBool),
240
241             // * -> Char
242             (Int(U(ast::TyU8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
243             (_, Int(Char)) => Err(CastError::CastToChar),
244
245             // prim -> float,ptr
246             (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float)
247                 => Err(CastError::NeedViaInt),
248             (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_))
249                 => Err(CastError::NeedViaUsize),
250
251             // ptr -> *
252             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
253             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
254             (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize),
255             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
256             (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr),
257             // * -> ptr
258             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
259             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
260             (Float, Ptr(_)) => Err(CastError::NeedViaUsize),
261             (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
262
263             // prim -> prim
264             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
265             (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
266
267             (Int(_), Int(_)) |
268             (Int(_), Float) |
269             (Float, Int(_)) |
270             (Float, Float) => Ok(CastKind::NumericCast),
271
272         }
273     }
274
275     fn check_ptr_ptr_cast<'a>(&self,
276                               fcx: &FnCtxt<'a, 'tcx>,
277                               m_expr: &'tcx ty::TypeAndMut<'tcx>,
278                               m_cast: &'tcx ty::TypeAndMut<'tcx>)
279                               -> Result<CastKind, CastError>
280     {
281         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
282                m_expr, m_cast);
283         // ptr-ptr cast. vtables must match.
284
285         // Cast to sized is OK
286         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
287             return Ok(CastKind::PtrPtrCast);
288         }
289
290         // sized -> unsized? report invalid cast (don't complain about vtable kinds)
291         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
292             return Err(CastError::IllegalCast);
293         }
294
295         // vtable kinds must match
296         match (unsize_kind(fcx, m_cast.ty), unsize_kind(fcx, m_expr.ty)) {
297             (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
298             _ => Err(CastError::DifferingKinds)
299         }
300     }
301
302     fn check_fptr_ptr_cast<'a>(&self,
303                                fcx: &FnCtxt<'a, 'tcx>,
304                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
305                                -> Result<CastKind, CastError>
306     {
307         // fptr-ptr cast. must be to sized ptr
308
309         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
310             Ok(CastKind::FnPtrPtrCast)
311         } else {
312             Err(CastError::IllegalCast)
313         }
314     }
315
316     fn check_ptr_addr_cast<'a>(&self,
317                                fcx: &FnCtxt<'a, 'tcx>,
318                                m_expr: &'tcx ty::TypeAndMut<'tcx>)
319                                -> Result<CastKind, CastError>
320     {
321         // ptr-addr cast. must be from sized ptr
322
323         if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
324             Ok(CastKind::PtrAddrCast)
325         } else {
326             Err(CastError::NeedViaPtr)
327         }
328     }
329
330     fn check_ref_cast<'a>(&self,
331                           fcx: &FnCtxt<'a, 'tcx>,
332                           m_expr: &'tcx ty::TypeAndMut<'tcx>,
333                           m_cast: &'tcx ty::TypeAndMut<'tcx>)
334                           -> Result<CastKind, CastError>
335     {
336         // array-ptr-cast.
337
338         if m_expr.mutbl == ast::MutImmutable && m_cast.mutbl == ast::MutImmutable {
339             if let ty::TyArray(ety, _) = m_expr.ty.sty {
340                 // Due to the limitations of LLVM global constants,
341                 // region pointers end up pointing at copies of
342                 // vector elements instead of the original values.
343                 // To allow raw pointers to work correctly, we
344                 // need to special-case obtaining a raw pointer
345                 // from a region pointer to a vector.
346
347                 // this will report a type mismatch if needed
348                 demand::eqtype(fcx, self.span, ety, m_cast.ty);
349                 return Ok(CastKind::ArrayPtrCast);
350             }
351         }
352
353         Err(CastError::IllegalCast)
354     }
355
356     fn check_addr_ptr_cast<'a>(&self,
357                                fcx: &FnCtxt<'a, 'tcx>,
358                                m_cast: &'tcx ty::TypeAndMut<'tcx>)
359                                -> Result<CastKind, CastError>
360     {
361         // ptr-addr cast. pointer must be thin.
362         if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
363            Ok(CastKind::AddrPtrCast)
364         } else {
365            Err(CastError::IllegalCast)
366         }
367     }
368
369     fn try_coercion_cast<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
370         if let Ok(()) = coercion::mk_assignty(fcx,
371                                               &self.expr,
372                                               self.expr_ty,
373                                               self.cast_ty) {
374             true
375         } else {
376             false
377         }
378     }
379
380 }