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