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