]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Enclose type in backticks for "reached the recursion limit while auto-dereferencing...
[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 //!    pointer_kind(`T`) = pointer_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 pointer_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::FnCtxt;
42
43 use errors::{DiagnosticBuilder,Applicability};
44 use hir::def_id::DefId;
45 use lint;
46 use rustc::hir;
47 use rustc::session::Session;
48 use rustc::traits;
49 use rustc::ty::{self, Ty, TypeFoldable, TypeAndMut};
50 use rustc::ty::adjustment::AllowTwoPhase;
51 use rustc::ty::cast::{CastKind, CastTy};
52 use rustc::ty::subst::Substs;
53 use rustc::middle::lang_items;
54 use syntax::ast;
55 use syntax_pos::Span;
56 use util::common::ErrorReported;
57
58 /// Reifies a cast check to be checked once we have full type information for
59 /// a function context.
60 pub struct CastCheck<'tcx> {
61     expr: &'tcx hir::Expr,
62     expr_ty: Ty<'tcx>,
63     cast_ty: Ty<'tcx>,
64     cast_span: Span,
65     span: Span,
66 }
67
68 /// The kind of pointer and associated metadata (thin, length or vtable) - we
69 /// only allow casts between fat pointers if their metadata have the same
70 /// kind.
71 #[derive(Copy, Clone, PartialEq, Eq)]
72 enum PointerKind<'tcx> {
73     /// No metadata attached, ie pointer to sized type or foreign type
74     Thin,
75     /// A trait object
76     Vtable(DefId),
77     /// Slice
78     Length,
79     /// The unsize info of this projection
80     OfProjection(&'tcx ty::ProjectionTy<'tcx>),
81     /// The unsize info of this opaque ty
82     OfOpaque(DefId, &'tcx Substs<'tcx>),
83     /// The unsize info of this parameter
84     OfParam(&'tcx ty::ParamTy),
85 }
86
87 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
88     /// Returns the kind of unsize information of t, or None
89     /// if t is unknown.
90     fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
91         Result<Option<PointerKind<'tcx>>, ErrorReported>
92     {
93         debug!("pointer_kind({:?}, {:?})", t, span);
94
95         let t = self.resolve_type_vars_if_possible(&t);
96
97         if t.references_error() {
98             return Err(ErrorReported);
99         }
100
101         if self.type_is_known_to_be_sized(t, span) {
102             return Ok(Some(PointerKind::Thin));
103         }
104
105         Ok(match t.sty {
106             ty::Slice(_) | ty::Str => Some(PointerKind::Length),
107             ty::Dynamic(ref tty, ..) =>
108                 Some(PointerKind::Vtable(tty.principal().def_id())),
109             ty::Adt(def, substs) if def.is_struct() => {
110                 match def.non_enum_variant().fields.last() {
111                     None => Some(PointerKind::Thin),
112                     Some(f) => {
113                         let field_ty = self.field_ty(span, f, substs);
114                         self.pointer_kind(field_ty, span)?
115                     }
116                 }
117             }
118             ty::Tuple(fields) => match fields.last() {
119                 None => Some(PointerKind::Thin),
120                 Some(f) => self.pointer_kind(f, span)?
121             },
122
123             // Pointers to foreign types are thin, despite being unsized
124             ty::Foreign(..) => Some(PointerKind::Thin),
125             // We should really try to normalize here.
126             ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
127             ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
128             ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
129             ty::Param(ref p) => Some(PointerKind::OfParam(p)),
130             // Insufficient type information.
131             ty::Bound(..) | ty::Infer(_) => None,
132
133             ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
134             ty::Float(_) | ty::Array(..) | ty::GeneratorWitness(..) |
135             ty::RawPtr(_) | ty::Ref(..) | ty::FnDef(..) |
136             ty::FnPtr(..) | ty::Closure(..) | ty::Generator(..) |
137             ty::Adt(..) | ty::Never | ty::Error => {
138                 self.tcx.sess.delay_span_bug(
139                     span, &format!("`{:?}` should be sized but is not?", t));
140                 return Err(ErrorReported);
141             }
142         })
143     }
144 }
145
146 #[derive(Copy, Clone)]
147 enum CastError {
148     ErrorReported,
149
150     CastToBool,
151     CastToChar,
152     DifferingKinds,
153     /// Cast of thin to fat raw ptr (eg. `*const () as *const [u8]`)
154     SizedUnsizedCast,
155     IllegalCast,
156     NeedDeref,
157     NeedViaPtr,
158     NeedViaThinPtr,
159     NeedViaInt,
160     NonScalar,
161     UnknownExprPtrKind,
162     UnknownCastPtrKind,
163 }
164
165 impl From<ErrorReported> for CastError {
166     fn from(ErrorReported: ErrorReported) -> Self {
167         CastError::ErrorReported
168     }
169 }
170
171 fn make_invalid_casting_error<'a, 'gcx, 'tcx>(sess: &'a Session,
172                                               span: Span,
173                                               expr_ty: Ty<'tcx>,
174                                               cast_ty: Ty<'tcx>,
175                                               fcx: &FnCtxt<'a, 'gcx, 'tcx>)
176                                               -> DiagnosticBuilder<'a> {
177     type_error_struct!(sess, span, expr_ty, E0606,
178                        "casting `{}` as `{}` is invalid",
179                        fcx.ty_to_string(expr_ty),
180                        fcx.ty_to_string(cast_ty))
181 }
182
183 impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
184     pub fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>,
185                expr: &'tcx hir::Expr,
186                expr_ty: Ty<'tcx>,
187                cast_ty: Ty<'tcx>,
188                cast_span: Span,
189                span: Span)
190                -> Result<CastCheck<'tcx>, ErrorReported> {
191         let check = CastCheck {
192             expr,
193             expr_ty,
194             cast_ty,
195             cast_span,
196             span,
197         };
198
199         // For better error messages, check for some obviously unsized
200         // cases now. We do a more thorough check at the end, once
201         // inference is more completely known.
202         match cast_ty.sty {
203             ty::Dynamic(..) | ty::Slice(..) => {
204                 check.report_cast_to_unsized_type(fcx);
205                 Err(ErrorReported)
206             }
207             _ => Ok(check),
208         }
209     }
210
211     fn report_cast_error(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, e: CastError) {
212         match e {
213             CastError::ErrorReported => {
214                 // an error has already been reported
215             }
216             CastError::NeedDeref => {
217                 let error_span = self.span;
218                 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
219                                                          self.cast_ty, fcx);
220                 let cast_ty = fcx.ty_to_string(self.cast_ty);
221                 err.span_label(error_span,
222                                format!("cannot cast `{}` as `{}`",
223                                        fcx.ty_to_string(self.expr_ty),
224                                        cast_ty));
225                 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
226                     err.span_help(self.expr.span,
227                         &format!("did you mean `*{}`?", snippet));
228                 }
229                 err.emit();
230             }
231             CastError::NeedViaThinPtr |
232             CastError::NeedViaPtr => {
233                 let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
234                                                          self.cast_ty, fcx);
235                 if self.cast_ty.is_integral() {
236                     err.help(&format!("cast through {} first",
237                                       match e {
238                                           CastError::NeedViaPtr => "a raw pointer",
239                                           CastError::NeedViaThinPtr => "a thin pointer",
240                                           _ => bug!(),
241                                       }));
242                 }
243                 err.emit();
244             }
245             CastError::NeedViaInt => {
246                 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
247                    .help(&format!("cast through {} first",
248                                   match e {
249                                       CastError::NeedViaInt => "an integer",
250                                       _ => bug!(),
251                                   }))
252                    .emit();
253             }
254             CastError::IllegalCast => {
255                 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
256                     .emit();
257             }
258             CastError::DifferingKinds => {
259                 make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty, self.cast_ty, fcx)
260                     .note("vtable kinds may not match")
261                     .emit();
262             }
263             CastError::CastToBool => {
264                 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`")
265                     .span_label(self.span, "unsupported cast")
266                     .help("compare with zero instead")
267                     .emit();
268             }
269             CastError::CastToChar => {
270                 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0604,
271                     "only `u8` can be cast as `char`, not `{}`", self.expr_ty).emit();
272             }
273             CastError::NonScalar => {
274                 type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0605,
275                                    "non-primitive cast: `{}` as `{}`",
276                                    self.expr_ty,
277                                    fcx.ty_to_string(self.cast_ty))
278                                   .note("an `as` expression can only be used to convert between \
279                                          primitive types. Consider using the `From` trait")
280                                   .emit();
281             }
282             CastError::SizedUnsizedCast => {
283                 use structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
284                 SizedUnsizedCastError::new(&fcx.tcx.sess,
285                                            self.span,
286                                            self.expr_ty,
287                                            fcx.ty_to_string(self.cast_ty))
288                     .diagnostic().emit();
289             }
290             CastError::UnknownCastPtrKind |
291             CastError::UnknownExprPtrKind => {
292                 let unknown_cast_to = match e {
293                     CastError::UnknownCastPtrKind => true,
294                     CastError::UnknownExprPtrKind => false,
295                     _ => bug!(),
296                 };
297                 let mut err = struct_span_err!(fcx.tcx.sess, self.span, E0641,
298                                                "cannot cast {} a pointer of an unknown kind",
299                                                if unknown_cast_to { "to" } else { "from" });
300                 err.note("The type information given here is insufficient to check whether \
301                           the pointer cast is valid");
302                 if unknown_cast_to {
303                     err.span_suggestion_short_with_applicability(
304                         self.cast_span,
305                         "consider giving more type information",
306                         String::new(),
307                         Applicability::Unspecified,
308                     );
309                 }
310                 err.emit();
311             }
312         }
313     }
314
315     fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
316         if self.cast_ty.references_error() || self.expr_ty.references_error() {
317             return;
318         }
319
320         let tstr = fcx.ty_to_string(self.cast_ty);
321         let mut err = type_error_struct!(fcx.tcx.sess, self.span, self.expr_ty, E0620,
322                                          "cast to unsized type: `{}` as `{}`",
323                                          fcx.resolve_type_vars_if_possible(&self.expr_ty),
324                                          tstr);
325         match self.expr_ty.sty {
326             ty::Ref(_, _, mt) => {
327                 let mtstr = match mt {
328                     hir::MutMutable => "mut ",
329                     hir::MutImmutable => "",
330                 };
331                 if self.cast_ty.is_trait() {
332                     match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
333                         Ok(s) => {
334                             err.span_suggestion_with_applicability(
335                                 self.cast_span,
336                                 "try casting to a reference instead",
337                                 format!("&{}{}", mtstr, s),
338                                 Applicability::MachineApplicable,
339                             );
340                         }
341                         Err(_) => {
342                             span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
343                         }
344                     }
345                 } else {
346                     span_help!(err,
347                                self.span,
348                                "consider using an implicit coercion to `&{}{}` instead",
349                                mtstr,
350                                tstr);
351                 }
352             }
353             ty::Adt(def, ..) if def.is_box() => {
354                 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
355                     Ok(s) => {
356                         err.span_suggestion_with_applicability(
357                             self.cast_span,
358                             "try casting to a `Box` instead",
359                             format!("Box<{}>", s),
360                             Applicability::MachineApplicable,
361                         );
362                     }
363                     Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
364                 }
365             }
366             _ => {
367                 span_help!(err,
368                            self.expr.span,
369                            "consider using a box or reference as appropriate");
370             }
371         }
372         err.emit();
373     }
374
375     fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
376         let t_cast = self.cast_ty;
377         let t_expr = self.expr_ty;
378         let type_asc_or = if fcx.tcx.features().type_ascription {
379             "type ascription or "
380         } else {
381             ""
382         };
383         let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
384             ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
385         } else {
386             ("", lint::builtin::TRIVIAL_CASTS)
387         };
388         let mut err = fcx.tcx.struct_span_lint_node(
389             lint,
390             self.expr.id,
391             self.span,
392             &format!("trivial {}cast: `{}` as `{}`",
393                      adjective,
394                      fcx.ty_to_string(t_expr),
395                      fcx.ty_to_string(t_cast)));
396         err.help(&format!("cast can be replaced by coercion; this might \
397                            require {}a temporary variable", type_asc_or));
398         err.emit();
399     }
400
401     pub fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
402         self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
403         self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
404
405         debug!("check_cast({}, {:?} as {:?})",
406                self.expr.id,
407                self.expr_ty,
408                self.cast_ty);
409
410         if !fcx.type_is_known_to_be_sized(self.cast_ty, self.span) {
411             self.report_cast_to_unsized_type(fcx);
412         } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
413             // No sense in giving duplicate error messages
414         } else if self.try_coercion_cast(fcx) {
415             self.trivial_cast_lint(fcx);
416             debug!(" -> CoercionCast");
417             fcx.tables.borrow_mut().cast_kinds_mut().insert(self.expr.hir_id,
418                                                             CastKind::CoercionCast);
419         } else {
420             match self.do_check(fcx) {
421                 Ok(k) => {
422                     debug!(" -> {:?}", k);
423                     fcx.tables.borrow_mut().cast_kinds_mut().insert(self.expr.hir_id, k);
424                 }
425                 Err(e) => self.report_cast_error(fcx, e),
426             };
427         }
428     }
429
430     /// Check a cast, and report an error if one exists. In some cases, this
431     /// can return Ok and create type errors in the fcx rather than returning
432     /// directly. coercion-cast is handled in check instead of here.
433     fn do_check(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Result<CastKind, CastError> {
434         use rustc::ty::cast::IntTy::*;
435         use rustc::ty::cast::CastTy::*;
436
437         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
438                                       CastTy::from_ty(self.cast_ty)) {
439             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
440             // Function item types may need to be reified before casts.
441             (None, Some(t_cast)) => {
442                 if let ty::FnDef(..) = self.expr_ty.sty {
443                     // Attempt a coercion to a fn pointer type.
444                     let f = self.expr_ty.fn_sig(fcx.tcx);
445                     let res = fcx.try_coerce(self.expr,
446                                              self.expr_ty,
447                                              fcx.tcx.mk_fn_ptr(f),
448                                              AllowTwoPhase::No);
449                     if res.is_err() {
450                         return Err(CastError::NonScalar);
451                     }
452                     (FnPtr, t_cast)
453                 } else {
454                     return Err(CastError::NonScalar);
455                 }
456             }
457             _ => return Err(CastError::NonScalar),
458         };
459
460         match (t_from, t_cast) {
461             // These types have invariants! can't cast into them.
462             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
463
464             // * -> Bool
465             (_, Int(Bool)) => Err(CastError::CastToBool),
466
467             // * -> Char
468             (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
469             (_, Int(Char)) => Err(CastError::CastToChar),
470
471             // prim -> float,ptr
472             (Int(Bool), Float) |
473             (Int(CEnum), Float) |
474             (Int(Char), Float) => Err(CastError::NeedViaInt),
475
476             (Int(Bool), Ptr(_)) |
477             (Int(CEnum), Ptr(_)) |
478             (Int(Char), Ptr(_)) |
479             (Ptr(_), Float) |
480             (FnPtr, Float) |
481             (Float, Ptr(_)) => Err(CastError::IllegalCast),
482
483             // ptr -> *
484             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
485             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
486             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
487             (RPtr(p), Int(_)) |
488             (RPtr(p), Float) => {
489                 match p.ty.sty {
490                     ty::Int(_) |
491                     ty::Uint(_) |
492                     ty::Float(_) => {
493                         Err(CastError::NeedDeref)
494                     }
495                     ty::Infer(t) => {
496                         match t {
497                             ty::InferTy::IntVar(_) |
498                             ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
499                             _ => Err(CastError::NeedViaPtr),
500                         }
501                     }
502                     _ => Err(CastError::NeedViaPtr),
503                 }
504             }
505             // * -> ptr
506             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
507             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
508             (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
509
510             // prim -> prim
511             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
512             (Int(Char), Int(_)) |
513             (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
514
515             (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
516                 Ok(CastKind::NumericCast)
517             }
518         }
519     }
520
521     fn check_ptr_ptr_cast(&self,
522                           fcx: &FnCtxt<'a, 'gcx, 'tcx>,
523                           m_expr: ty::TypeAndMut<'tcx>,
524                           m_cast: ty::TypeAndMut<'tcx>)
525                           -> Result<CastKind, CastError> {
526         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
527         // ptr-ptr cast. vtables must match.
528
529         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
530         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
531
532         let cast_kind = match cast_kind {
533             // We can't cast if target pointer kind is unknown
534             None => return Err(CastError::UnknownCastPtrKind),
535             Some(cast_kind) => cast_kind,
536         };
537
538         // Cast to thin pointer is OK
539         if cast_kind == PointerKind::Thin {
540             return Ok(CastKind::PtrPtrCast);
541         }
542
543         let expr_kind = match expr_kind {
544             // We can't cast to fat pointer if source pointer kind is unknown
545             None => return Err(CastError::UnknownExprPtrKind),
546             Some(expr_kind) => expr_kind,
547         };
548
549         // thin -> fat? report invalid cast (don't complain about vtable kinds)
550         if expr_kind == PointerKind::Thin {
551             return Err(CastError::SizedUnsizedCast);
552         }
553
554         // vtable kinds must match
555         if cast_kind == expr_kind {
556             Ok(CastKind::PtrPtrCast)
557         } else {
558             Err(CastError::DifferingKinds)
559         }
560     }
561
562     fn check_fptr_ptr_cast(&self,
563                            fcx: &FnCtxt<'a, 'gcx, 'tcx>,
564                            m_cast: ty::TypeAndMut<'tcx>)
565                            -> Result<CastKind, CastError> {
566         // fptr-ptr cast. must be to thin ptr
567
568         match fcx.pointer_kind(m_cast.ty, self.span)? {
569             None => Err(CastError::UnknownCastPtrKind),
570             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
571             _ => Err(CastError::IllegalCast),
572         }
573     }
574
575     fn check_ptr_addr_cast(&self,
576                            fcx: &FnCtxt<'a, 'gcx, 'tcx>,
577                            m_expr: ty::TypeAndMut<'tcx>)
578                            -> Result<CastKind, CastError> {
579         // ptr-addr cast. must be from thin ptr
580
581         match fcx.pointer_kind(m_expr.ty, self.span)? {
582             None => Err(CastError::UnknownExprPtrKind),
583             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
584             _ => Err(CastError::NeedViaThinPtr),
585         }
586     }
587
588     fn check_ref_cast(&self,
589                       fcx: &FnCtxt<'a, 'gcx, 'tcx>,
590                       m_expr: ty::TypeAndMut<'tcx>,
591                       m_cast: ty::TypeAndMut<'tcx>)
592                       -> Result<CastKind, CastError> {
593         // array-ptr-cast.
594
595         if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
596             if let ty::Array(ety, _) = m_expr.ty.sty {
597                 // Due to the limitations of LLVM global constants,
598                 // region pointers end up pointing at copies of
599                 // vector elements instead of the original values.
600                 // To allow raw pointers to work correctly, we
601                 // need to special-case obtaining a raw pointer
602                 // from a region pointer to a vector.
603
604                 // this will report a type mismatch if needed
605                 fcx.demand_eqtype(self.span, ety, m_cast.ty);
606                 return Ok(CastKind::ArrayPtrCast);
607             }
608         }
609
610         Err(CastError::IllegalCast)
611     }
612
613     fn check_addr_ptr_cast(&self,
614                            fcx: &FnCtxt<'a, 'gcx, 'tcx>,
615                            m_cast: TypeAndMut<'tcx>)
616                            -> Result<CastKind, CastError> {
617         // ptr-addr cast. pointer must be thin.
618         match fcx.pointer_kind(m_cast.ty, self.span)? {
619             None => Err(CastError::UnknownCastPtrKind),
620             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
621             _ => Err(CastError::IllegalCast),
622         }
623     }
624
625     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> bool {
626         fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No).is_ok()
627     }
628 }
629
630 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
631     fn type_is_known_to_be_sized(&self, ty: Ty<'tcx>, span: Span) -> bool {
632         let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
633         traits::type_known_to_meet_bound(self, self.param_env, ty, lang_item, span)
634     }
635 }