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