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