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