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