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