]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Make rustc::traits::error_reporting::{recursive_type_with_infinite_size_error, report...
[rust.git] / src / librustc_typeck / check / cast.rs
1 //! Code for type-checking cast expressions.
2 //!
3 //! A cast `e as U` is valid if one of the following holds:
4 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
5 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
6 //!    pointer_kind(`T`) = pointer_kind(`U_0`); *ptr-ptr-cast*
7 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
8 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
9 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
10 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
11 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
12 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
13 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
14 //! * `e` is a function pointer type and `U` has type `*T`,
15 //!   while `T: Sized`; *fptr-ptr-cast*
16 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
17 //!
18 //! where `&.T` and `*T` are references of either mutability,
19 //! and where pointer_kind(`T`) is the kind of the unsize info
20 //! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or
21 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
22 //!
23 //! Note that lengths are not adjusted when casting raw slices -
24 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
25 //! half of the original memory.
26 //!
27 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
28 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
29 //! `U1` coerces to `U2`).
30
31 use super::FnCtxt;
32
33 use crate::hir::def_id::DefId;
34 use crate::lint;
35 use crate::util::common::ErrorReported;
36 use errors::{Applicability, DiagnosticBuilder};
37 use rustc::middle::lang_items;
38 use rustc::session::Session;
39 use rustc::traits;
40 use rustc::traits::error_reporting::report_object_safety_error;
41 use rustc::ty::adjustment::AllowTwoPhase;
42 use rustc::ty::cast::{CastKind, CastTy};
43 use rustc::ty::error::TypeError;
44 use rustc::ty::subst::SubstsRef;
45 use rustc::ty::{self, Ty, TypeAndMut, TypeFoldable};
46 use rustc_hir as hir;
47 use rustc_span::Span;
48 use syntax::ast;
49
50 use rustc_error_codes::*;
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                             span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
428                         }
429                     }
430                 } else {
431                     span_help!(
432                         err,
433                         self.span,
434                         "consider using an implicit coercion to `&{}{}` instead",
435                         mtstr,
436                         tstr
437                     );
438                 }
439             }
440             ty::Adt(def, ..) if def.is_box() => {
441                 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
442                     Ok(s) => {
443                         err.span_suggestion(
444                             self.cast_span,
445                             "try casting to a `Box` instead",
446                             format!("Box<{}>", s),
447                             Applicability::MachineApplicable,
448                         );
449                     }
450                     Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
451                 }
452             }
453             _ => {
454                 span_help!(err, self.expr.span, "consider using a box or reference as appropriate");
455             }
456         }
457         err.emit();
458     }
459
460     fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
461         let t_cast = self.cast_ty;
462         let t_expr = self.expr_ty;
463         let type_asc_or =
464             if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
465         let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
466             ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
467         } else {
468             ("", lint::builtin::TRIVIAL_CASTS)
469         };
470         let mut err = fcx.tcx.struct_span_lint_hir(
471             lint,
472             self.expr.hir_id,
473             self.span,
474             &format!(
475                 "trivial {}cast: `{}` as `{}`",
476                 adjective,
477                 fcx.ty_to_string(t_expr),
478                 fcx.ty_to_string(t_cast)
479             ),
480         );
481         err.help(&format!(
482             "cast can be replaced by coercion; this might \
483                            require {}a temporary variable",
484             type_asc_or
485         ));
486         err.emit();
487     }
488
489     pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
490         self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
491         self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
492
493         debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
494
495         if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
496             self.report_cast_to_unsized_type(fcx);
497         } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
498             // No sense in giving duplicate error messages
499         } else {
500             match self.try_coercion_cast(fcx) {
501                 Ok(()) => {
502                     self.trivial_cast_lint(fcx);
503                     debug!(" -> CoercionCast");
504                     fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
505                 }
506                 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
507                     self.report_object_unsafe_cast(&fcx, did);
508                 }
509                 Err(_) => {
510                     match self.do_check(fcx) {
511                         Ok(k) => {
512                             debug!(" -> {:?}", k);
513                         }
514                         Err(e) => self.report_cast_error(fcx, e),
515                     };
516                 }
517             };
518         }
519     }
520
521     fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
522         let violations = fcx.tcx.object_safety_violations(did);
523         let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
524         err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
525         err.emit();
526     }
527
528     /// Checks a cast, and report an error if one exists. In some cases, this
529     /// can return Ok and create type errors in the fcx rather than returning
530     /// directly. coercion-cast is handled in check instead of here.
531     fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
532         use rustc::ty::cast::CastTy::*;
533         use rustc::ty::cast::IntTy::*;
534
535         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
536         {
537             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
538             // Function item types may need to be reified before casts.
539             (None, Some(t_cast)) => {
540                 match self.expr_ty.kind {
541                     ty::FnDef(..) => {
542                         // Attempt a coercion to a fn pointer type.
543                         let f = self.expr_ty.fn_sig(fcx.tcx);
544                         let res = fcx.try_coerce(
545                             self.expr,
546                             self.expr_ty,
547                             fcx.tcx.mk_fn_ptr(f),
548                             AllowTwoPhase::No,
549                         );
550                         if let Err(TypeError::IntrinsicCast) = res {
551                             return Err(CastError::IllegalCast);
552                         }
553                         if res.is_err() {
554                             return Err(CastError::NonScalar);
555                         }
556                         (FnPtr, t_cast)
557                     }
558                     // Special case some errors for references, and check for
559                     // array-ptr-casts. `Ref` is not a CastTy because the cast
560                     // is split into a coercion to a pointer type, followed by
561                     // a cast.
562                     ty::Ref(_, inner_ty, mutbl) => {
563                         return match t_cast {
564                             Int(_) | Float => match inner_ty.kind {
565                                 ty::Int(_)
566                                 | ty::Uint(_)
567                                 | ty::Float(_)
568                                 | ty::Infer(ty::InferTy::IntVar(_))
569                                 | ty::Infer(ty::InferTy::FloatVar(_)) => Err(CastError::NeedDeref),
570                                 _ => Err(CastError::NeedViaPtr),
571                             },
572                             // array-ptr-cast
573                             Ptr(mt) => {
574                                 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
575                             }
576                             _ => Err(CastError::NonScalar),
577                         };
578                     }
579                     _ => return Err(CastError::NonScalar),
580                 }
581             }
582             _ => return Err(CastError::NonScalar),
583         };
584
585         match (t_from, t_cast) {
586             // These types have invariants! can't cast into them.
587             (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
588
589             // * -> Bool
590             (_, Int(Bool)) => Err(CastError::CastToBool),
591
592             // * -> Char
593             (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
594             (_, Int(Char)) => Err(CastError::CastToChar),
595
596             // prim -> float,ptr
597             (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float) => {
598                 Err(CastError::NeedViaInt)
599             }
600
601             (Int(Bool), Ptr(_))
602             | (Int(CEnum), Ptr(_))
603             | (Int(Char), Ptr(_))
604             | (Ptr(_), Float)
605             | (FnPtr, Float)
606             | (Float, Ptr(_)) => Err(CastError::IllegalCast),
607
608             // ptr -> *
609             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
610             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
611             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
612
613             // * -> ptr
614             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
615             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
616
617             // prim -> prim
618             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
619             (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
620
621             (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
622                 Ok(CastKind::NumericCast)
623             }
624         }
625     }
626
627     fn check_ptr_ptr_cast(
628         &self,
629         fcx: &FnCtxt<'a, 'tcx>,
630         m_expr: ty::TypeAndMut<'tcx>,
631         m_cast: ty::TypeAndMut<'tcx>,
632     ) -> Result<CastKind, CastError> {
633         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
634         // ptr-ptr cast. vtables must match.
635
636         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
637         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
638
639         let cast_kind = match cast_kind {
640             // We can't cast if target pointer kind is unknown
641             None => return Err(CastError::UnknownCastPtrKind),
642             Some(cast_kind) => cast_kind,
643         };
644
645         // Cast to thin pointer is OK
646         if cast_kind == PointerKind::Thin {
647             return Ok(CastKind::PtrPtrCast);
648         }
649
650         let expr_kind = match expr_kind {
651             // We can't cast to fat pointer if source pointer kind is unknown
652             None => return Err(CastError::UnknownExprPtrKind),
653             Some(expr_kind) => expr_kind,
654         };
655
656         // thin -> fat? report invalid cast (don't complain about vtable kinds)
657         if expr_kind == PointerKind::Thin {
658             return Err(CastError::SizedUnsizedCast);
659         }
660
661         // vtable kinds must match
662         if cast_kind == expr_kind {
663             Ok(CastKind::PtrPtrCast)
664         } else {
665             Err(CastError::DifferingKinds)
666         }
667     }
668
669     fn check_fptr_ptr_cast(
670         &self,
671         fcx: &FnCtxt<'a, 'tcx>,
672         m_cast: ty::TypeAndMut<'tcx>,
673     ) -> Result<CastKind, CastError> {
674         // fptr-ptr cast. must be to thin ptr
675
676         match fcx.pointer_kind(m_cast.ty, self.span)? {
677             None => Err(CastError::UnknownCastPtrKind),
678             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
679             _ => Err(CastError::IllegalCast),
680         }
681     }
682
683     fn check_ptr_addr_cast(
684         &self,
685         fcx: &FnCtxt<'a, 'tcx>,
686         m_expr: ty::TypeAndMut<'tcx>,
687     ) -> Result<CastKind, CastError> {
688         // ptr-addr cast. must be from thin ptr
689
690         match fcx.pointer_kind(m_expr.ty, self.span)? {
691             None => Err(CastError::UnknownExprPtrKind),
692             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
693             _ => Err(CastError::NeedViaThinPtr),
694         }
695     }
696
697     fn check_ref_cast(
698         &self,
699         fcx: &FnCtxt<'a, 'tcx>,
700         m_expr: ty::TypeAndMut<'tcx>,
701         m_cast: ty::TypeAndMut<'tcx>,
702     ) -> Result<CastKind, CastError> {
703         // array-ptr-cast.
704
705         if m_expr.mutbl == hir::Mutability::Not && m_cast.mutbl == hir::Mutability::Not {
706             if let ty::Array(ety, _) = m_expr.ty.kind {
707                 // Due to the limitations of LLVM global constants,
708                 // region pointers end up pointing at copies of
709                 // vector elements instead of the original values.
710                 // To allow raw pointers to work correctly, we
711                 // need to special-case obtaining a raw pointer
712                 // from a region pointer to a vector.
713
714                 // Coerce to a raw pointer so that we generate AddressOf in MIR.
715                 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
716                 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
717                     .unwrap_or_else(|_| bug!(
718                         "could not cast from reference to array to pointer to array ({:?} to {:?})",
719                         self.expr_ty,
720                         array_ptr_type,
721                     ));
722
723                 // this will report a type mismatch if needed
724                 fcx.demand_eqtype(self.span, ety, m_cast.ty);
725                 return Ok(CastKind::ArrayPtrCast);
726             }
727         }
728
729         Err(CastError::IllegalCast)
730     }
731
732     fn check_addr_ptr_cast(
733         &self,
734         fcx: &FnCtxt<'a, 'tcx>,
735         m_cast: TypeAndMut<'tcx>,
736     ) -> Result<CastKind, CastError> {
737         // ptr-addr cast. pointer must be thin.
738         match fcx.pointer_kind(m_cast.ty, self.span)? {
739             None => Err(CastError::UnknownCastPtrKind),
740             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
741             _ => Err(CastError::IllegalCast),
742         }
743     }
744
745     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
746         match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
747             Ok(_) => Ok(()),
748             Err(err) => Err(err),
749         }
750     }
751 }
752
753 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
754     fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
755         let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
756         traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)
757     }
758 }