]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Add some type-alias-impl-trait regression tests
[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::type_error_struct;
36 use crate::util::common::ErrorReported;
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_errors::{struct_span_err, Applicability, DiagnosticBuilder};
48 use rustc_hir as hir;
49 use rustc_span::Span;
50 use syntax::ast;
51
52 /// Reifies a cast check to be checked once we have full type information for
53 /// a function context.
54 pub struct CastCheck<'tcx> {
55     expr: &'tcx hir::Expr<'tcx>,
56     expr_ty: Ty<'tcx>,
57     cast_ty: Ty<'tcx>,
58     cast_span: Span,
59     span: Span,
60 }
61
62 /// The kind of pointer and associated metadata (thin, length or vtable) - we
63 /// only allow casts between fat pointers if their metadata have the same
64 /// kind.
65 #[derive(Copy, Clone, PartialEq, Eq)]
66 enum PointerKind<'tcx> {
67     /// No metadata attached, ie pointer to sized type or foreign type
68     Thin,
69     /// A trait object
70     Vtable(Option<DefId>),
71     /// Slice
72     Length,
73     /// The unsize info of this projection
74     OfProjection(&'tcx ty::ProjectionTy<'tcx>),
75     /// The unsize info of this opaque ty
76     OfOpaque(DefId, SubstsRef<'tcx>),
77     /// The unsize info of this parameter
78     OfParam(&'tcx ty::ParamTy),
79 }
80
81 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
82     /// Returns the kind of unsize information of t, or None
83     /// if t is unknown.
84     fn pointer_kind(
85         &self,
86         t: Ty<'tcx>,
87         span: Span,
88     ) -> Result<Option<PointerKind<'tcx>>, ErrorReported> {
89         debug!("pointer_kind({:?}, {:?})", t, span);
90
91         let t = self.resolve_vars_if_possible(&t);
92
93         if t.references_error() {
94             return Err(ErrorReported);
95         }
96
97         if self.type_is_known_to_be_sized_modulo_regions(t, span) {
98             return Ok(Some(PointerKind::Thin));
99         }
100
101         Ok(match t.kind {
102             ty::Slice(_) | ty::Str => Some(PointerKind::Length),
103             ty::Dynamic(ref tty, ..) => Some(PointerKind::Vtable(tty.principal_def_id())),
104             ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
105                 None => Some(PointerKind::Thin),
106                 Some(f) => {
107                     let field_ty = self.field_ty(span, f, substs);
108                     self.pointer_kind(field_ty, span)?
109                 }
110             },
111             ty::Tuple(fields) => match fields.last() {
112                 None => Some(PointerKind::Thin),
113                 Some(f) => self.pointer_kind(f.expect_ty(), span)?,
114             },
115
116             // Pointers to foreign types are thin, despite being unsized
117             ty::Foreign(..) => Some(PointerKind::Thin),
118             // We should really try to normalize here.
119             ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
120             ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
121             ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
122             ty::Param(ref p) => Some(PointerKind::OfParam(p)),
123             // Insufficient type information.
124             ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
125
126             ty::Bool
127             | ty::Char
128             | ty::Int(..)
129             | ty::Uint(..)
130             | ty::Float(_)
131             | ty::Array(..)
132             | ty::GeneratorWitness(..)
133             | ty::RawPtr(_)
134             | ty::Ref(..)
135             | ty::FnDef(..)
136             | ty::FnPtr(..)
137             | ty::Closure(..)
138             | ty::Generator(..)
139             | ty::Adt(..)
140             | ty::Never
141             | ty::Error => {
142                 self.tcx
143                     .sess
144                     .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
145                 return Err(ErrorReported);
146             }
147         })
148     }
149 }
150
151 #[derive(Copy, Clone)]
152 enum CastError {
153     ErrorReported,
154
155     CastToBool,
156     CastToChar,
157     DifferingKinds,
158     /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
159     SizedUnsizedCast,
160     IllegalCast,
161     NeedDeref,
162     NeedViaPtr,
163     NeedViaThinPtr,
164     NeedViaInt,
165     NonScalar,
166     UnknownExprPtrKind,
167     UnknownCastPtrKind,
168 }
169
170 impl From<ErrorReported> for CastError {
171     fn from(ErrorReported: ErrorReported) -> Self {
172         CastError::ErrorReported
173     }
174 }
175
176 fn make_invalid_casting_error<'a, 'tcx>(
177     sess: &'a Session,
178     span: Span,
179     expr_ty: Ty<'tcx>,
180     cast_ty: Ty<'tcx>,
181     fcx: &FnCtxt<'a, 'tcx>,
182 ) -> DiagnosticBuilder<'a> {
183     type_error_struct!(
184         sess,
185         span,
186         expr_ty,
187         E0606,
188         "casting `{}` as `{}` is invalid",
189         fcx.ty_to_string(expr_ty),
190         fcx.ty_to_string(cast_ty)
191     )
192 }
193
194 impl<'a, 'tcx> CastCheck<'tcx> {
195     pub fn new(
196         fcx: &FnCtxt<'a, 'tcx>,
197         expr: &'tcx hir::Expr<'tcx>,
198         expr_ty: Ty<'tcx>,
199         cast_ty: Ty<'tcx>,
200         cast_span: Span,
201         span: Span,
202     ) -> Result<CastCheck<'tcx>, ErrorReported> {
203         let check = CastCheck { expr, expr_ty, cast_ty, cast_span, span };
204
205         // For better error messages, check for some obviously unsized
206         // cases now. We do a more thorough check at the end, once
207         // inference is more completely known.
208         match cast_ty.kind {
209             ty::Dynamic(..) | ty::Slice(..) => {
210                 check.report_cast_to_unsized_type(fcx);
211                 Err(ErrorReported)
212             }
213             _ => Ok(check),
214         }
215     }
216
217     fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
218         match e {
219             CastError::ErrorReported => {
220                 // an error has already been reported
221             }
222             CastError::NeedDeref => {
223                 let error_span = self.span;
224                 let mut err = make_invalid_casting_error(
225                     fcx.tcx.sess,
226                     self.span,
227                     self.expr_ty,
228                     self.cast_ty,
229                     fcx,
230                 );
231                 let cast_ty = fcx.ty_to_string(self.cast_ty);
232                 err.span_label(
233                     error_span,
234                     format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
235                 );
236                 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
237                     err.span_suggestion(
238                         self.expr.span,
239                         "dereference the expression",
240                         format!("*{}", snippet),
241                         Applicability::MaybeIncorrect,
242                     );
243                 } else {
244                     err.span_help(self.expr.span, "dereference the expression with `*`");
245                 }
246                 err.emit();
247             }
248             CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
249                 let mut err = make_invalid_casting_error(
250                     fcx.tcx.sess,
251                     self.span,
252                     self.expr_ty,
253                     self.cast_ty,
254                     fcx,
255                 );
256                 if self.cast_ty.is_integral() {
257                     err.help(&format!(
258                         "cast through {} first",
259                         match e {
260                             CastError::NeedViaPtr => "a raw pointer",
261                             CastError::NeedViaThinPtr => "a thin pointer",
262                             _ => bug!(),
263                         }
264                     ));
265                 }
266                 err.emit();
267             }
268             CastError::NeedViaInt => {
269                 make_invalid_casting_error(
270                     fcx.tcx.sess,
271                     self.span,
272                     self.expr_ty,
273                     self.cast_ty,
274                     fcx,
275                 )
276                 .help(&format!(
277                     "cast through {} first",
278                     match e {
279                         CastError::NeedViaInt => "an integer",
280                         _ => bug!(),
281                     }
282                 ))
283                 .emit();
284             }
285             CastError::IllegalCast => {
286                 make_invalid_casting_error(
287                     fcx.tcx.sess,
288                     self.span,
289                     self.expr_ty,
290                     self.cast_ty,
291                     fcx,
292                 )
293                 .emit();
294             }
295             CastError::DifferingKinds => {
296                 make_invalid_casting_error(
297                     fcx.tcx.sess,
298                     self.span,
299                     self.expr_ty,
300                     self.cast_ty,
301                     fcx,
302                 )
303                 .note("vtable kinds may not match")
304                 .emit();
305             }
306             CastError::CastToBool => {
307                 let mut err =
308                     struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
309
310                 if self.expr_ty.is_numeric() {
311                     match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
312                         Ok(snippet) => {
313                             err.span_suggestion(
314                                 self.span,
315                                 "compare with zero instead",
316                                 format!("{} != 0", snippet),
317                                 Applicability::MachineApplicable,
318                             );
319                         }
320                         Err(_) => {
321                             err.span_help(self.span, "compare with zero instead");
322                         }
323                     }
324                 } else {
325                     err.span_label(self.span, "unsupported cast");
326                 }
327
328                 err.emit();
329             }
330             CastError::CastToChar => {
331                 type_error_struct!(
332                     fcx.tcx.sess,
333                     self.span,
334                     self.expr_ty,
335                     E0604,
336                     "only `u8` can be cast as `char`, not `{}`",
337                     self.expr_ty
338                 )
339                 .emit();
340             }
341             CastError::NonScalar => {
342                 type_error_struct!(
343                     fcx.tcx.sess,
344                     self.span,
345                     self.expr_ty,
346                     E0605,
347                     "non-primitive cast: `{}` as `{}`",
348                     self.expr_ty,
349                     fcx.ty_to_string(self.cast_ty)
350                 )
351                 .note(
352                     "an `as` expression can only be used to convert between \
353                                          primitive types. Consider using the `From` trait",
354                 )
355                 .emit();
356             }
357             CastError::SizedUnsizedCast => {
358                 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
359                 SizedUnsizedCastError::new(
360                     &fcx.tcx.sess,
361                     self.span,
362                     self.expr_ty,
363                     fcx.ty_to_string(self.cast_ty),
364                 )
365                 .diagnostic()
366                 .emit();
367             }
368             CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
369                 let unknown_cast_to = match e {
370                     CastError::UnknownCastPtrKind => true,
371                     CastError::UnknownExprPtrKind => false,
372                     _ => bug!(),
373                 };
374                 let mut err = struct_span_err!(
375                     fcx.tcx.sess,
376                     self.span,
377                     E0641,
378                     "cannot cast {} a pointer of an unknown kind",
379                     if unknown_cast_to { "to" } else { "from" }
380                 );
381                 err.note(
382                     "the type information given here is insufficient to check whether \
383                           the pointer cast is valid",
384                 );
385                 if unknown_cast_to {
386                     err.span_suggestion_short(
387                         self.cast_span,
388                         "consider giving more type information",
389                         String::new(),
390                         Applicability::Unspecified,
391                     );
392                 }
393                 err.emit();
394             }
395         }
396     }
397
398     fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
399         if self.cast_ty.references_error() || self.expr_ty.references_error() {
400             return;
401         }
402
403         let tstr = fcx.ty_to_string(self.cast_ty);
404         let mut err = type_error_struct!(
405             fcx.tcx.sess,
406             self.span,
407             self.expr_ty,
408             E0620,
409             "cast to unsized type: `{}` as `{}`",
410             fcx.resolve_vars_if_possible(&self.expr_ty),
411             tstr
412         );
413         match self.expr_ty.kind {
414             ty::Ref(_, _, mt) => {
415                 let mtstr = mt.prefix_str();
416                 if self.cast_ty.is_trait() {
417                     match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
418                         Ok(s) => {
419                             err.span_suggestion(
420                                 self.cast_span,
421                                 "try casting to a reference instead",
422                                 format!("&{}{}", mtstr, s),
423                                 Applicability::MachineApplicable,
424                             );
425                         }
426                         Err(_) => {
427                             let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
428                             err.span_help(self.cast_span, msg);
429                         }
430                     }
431                 } else {
432                     let msg = &format!(
433                         "consider using an implicit coercion to `&{}{}` instead",
434                         mtstr, tstr
435                     );
436                     err.span_help(self.span, msg);
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(_) => {
450                         err.span_help(self.cast_span, &format!("did you mean `Box<{}>`?", tstr));
451                     }
452                 }
453             }
454             _ => {
455                 err.span_help(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 }