]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Rollup merge of #63872 - marmistrz:readdir, r=jonas-schievink
[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.sty {
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.sty {
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.sty {
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 if self.try_coercion_cast(fcx) {
432             self.trivial_cast_lint(fcx);
433             debug!(" -> CoercionCast");
434             fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
435
436         } else {
437             match self.do_check(fcx) {
438                 Ok(k) => {
439                     debug!(" -> {:?}", k);
440                 }
441                 Err(e) => self.report_cast_error(fcx, e),
442             };
443         }
444     }
445
446     /// Checks a cast, and report an error if one exists. In some cases, this
447     /// can return Ok and create type errors in the fcx rather than returning
448     /// directly. coercion-cast is handled in check instead of here.
449     fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
450         use rustc::ty::cast::IntTy::*;
451         use rustc::ty::cast::CastTy::*;
452
453         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
454                                       CastTy::from_ty(self.cast_ty)) {
455             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
456             // Function item types may need to be reified before casts.
457             (None, Some(t_cast)) => {
458                 if let ty::FnDef(..) = self.expr_ty.sty {
459                     // Attempt a coercion to a fn pointer type.
460                     let f = self.expr_ty.fn_sig(fcx.tcx);
461                     let res = fcx.try_coerce(self.expr,
462                                              self.expr_ty,
463                                              fcx.tcx.mk_fn_ptr(f),
464                                              AllowTwoPhase::No);
465                     if let Err(TypeError::IntrinsicCast) = res {
466                         return Err(CastError::IllegalCast);
467                     }
468                     if res.is_err() {
469                         return Err(CastError::NonScalar);
470                     }
471                     (FnPtr, t_cast)
472                 } else {
473                     return Err(CastError::NonScalar);
474                 }
475             }
476             _ => return Err(CastError::NonScalar),
477         };
478
479         match (t_from, t_cast) {
480             // These types have invariants! can't cast into them.
481             (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
482
483             // * -> Bool
484             (_, Int(Bool)) => Err(CastError::CastToBool),
485
486             // * -> Char
487             (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
488             (_, Int(Char)) => Err(CastError::CastToChar),
489
490             // prim -> float,ptr
491             (Int(Bool), Float) |
492             (Int(CEnum), Float) |
493             (Int(Char), Float) => Err(CastError::NeedViaInt),
494
495             (Int(Bool), Ptr(_)) |
496             (Int(CEnum), Ptr(_)) |
497             (Int(Char), Ptr(_)) |
498             (Ptr(_), Float) |
499             (FnPtr, Float) |
500             (Float, Ptr(_)) => Err(CastError::IllegalCast),
501
502             // ptr -> *
503             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
504             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
505             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
506             (RPtr(p), Int(_)) |
507             (RPtr(p), Float) => {
508                 match p.ty.sty {
509                     ty::Int(_) |
510                     ty::Uint(_) |
511                     ty::Float(_) => {
512                         Err(CastError::NeedDeref)
513                     }
514                     ty::Infer(t) => {
515                         match t {
516                             ty::InferTy::IntVar(_) |
517                             ty::InferTy::FloatVar(_) => Err(CastError::NeedDeref),
518                             _ => Err(CastError::NeedViaPtr),
519                         }
520                     }
521                     _ => Err(CastError::NeedViaPtr),
522                 }
523             }
524             // * -> ptr
525             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
526             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
527             (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
528
529             // prim -> prim
530             (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
531             (Int(Char), Int(_)) |
532             (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
533
534             (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
535                 Ok(CastKind::NumericCast)
536             }
537         }
538     }
539
540     fn check_ptr_ptr_cast(
541         &self,
542         fcx: &FnCtxt<'a, 'tcx>,
543         m_expr: ty::TypeAndMut<'tcx>,
544         m_cast: ty::TypeAndMut<'tcx>,
545     ) -> Result<CastKind, CastError> {
546         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
547         // ptr-ptr cast. vtables must match.
548
549         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
550         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
551
552         let cast_kind = match cast_kind {
553             // We can't cast if target pointer kind is unknown
554             None => return Err(CastError::UnknownCastPtrKind),
555             Some(cast_kind) => cast_kind,
556         };
557
558         // Cast to thin pointer is OK
559         if cast_kind == PointerKind::Thin {
560             return Ok(CastKind::PtrPtrCast);
561         }
562
563         let expr_kind = match expr_kind {
564             // We can't cast to fat pointer if source pointer kind is unknown
565             None => return Err(CastError::UnknownExprPtrKind),
566             Some(expr_kind) => expr_kind,
567         };
568
569         // thin -> fat? report invalid cast (don't complain about vtable kinds)
570         if expr_kind == PointerKind::Thin {
571             return Err(CastError::SizedUnsizedCast);
572         }
573
574         // vtable kinds must match
575         if cast_kind == expr_kind {
576             Ok(CastKind::PtrPtrCast)
577         } else {
578             Err(CastError::DifferingKinds)
579         }
580     }
581
582     fn check_fptr_ptr_cast(
583         &self,
584         fcx: &FnCtxt<'a, 'tcx>,
585         m_cast: ty::TypeAndMut<'tcx>,
586     ) -> Result<CastKind, CastError> {
587         // fptr-ptr cast. must be to thin ptr
588
589         match fcx.pointer_kind(m_cast.ty, self.span)? {
590             None => Err(CastError::UnknownCastPtrKind),
591             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
592             _ => Err(CastError::IllegalCast),
593         }
594     }
595
596     fn check_ptr_addr_cast(
597         &self,
598         fcx: &FnCtxt<'a, 'tcx>,
599         m_expr: ty::TypeAndMut<'tcx>,
600     ) -> Result<CastKind, CastError> {
601         // ptr-addr cast. must be from thin ptr
602
603         match fcx.pointer_kind(m_expr.ty, self.span)? {
604             None => Err(CastError::UnknownExprPtrKind),
605             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
606             _ => Err(CastError::NeedViaThinPtr),
607         }
608     }
609
610     fn check_ref_cast(
611         &self,
612         fcx: &FnCtxt<'a, 'tcx>,
613         m_expr: ty::TypeAndMut<'tcx>,
614         m_cast: ty::TypeAndMut<'tcx>,
615     ) -> Result<CastKind, CastError> {
616         // array-ptr-cast.
617
618         if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
619             if let ty::Array(ety, _) = m_expr.ty.sty {
620                 // Due to the limitations of LLVM global constants,
621                 // region pointers end up pointing at copies of
622                 // vector elements instead of the original values.
623                 // To allow raw pointers to work correctly, we
624                 // need to special-case obtaining a raw pointer
625                 // from a region pointer to a vector.
626
627                 // this will report a type mismatch if needed
628                 fcx.demand_eqtype(self.span, ety, m_cast.ty);
629                 return Ok(CastKind::ArrayPtrCast);
630             }
631         }
632
633         Err(CastError::IllegalCast)
634     }
635
636     fn check_addr_ptr_cast(
637         &self,
638         fcx: &FnCtxt<'a, 'tcx>,
639         m_cast: TypeAndMut<'tcx>,
640     ) -> Result<CastKind, CastError> {
641         // ptr-addr cast. pointer must be thin.
642         match fcx.pointer_kind(m_cast.ty, self.span)? {
643             None => Err(CastError::UnknownCastPtrKind),
644             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
645             _ => Err(CastError::IllegalCast),
646         }
647     }
648
649     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> bool {
650         fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No).is_ok()
651     }
652 }
653
654 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
655     fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
656         let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
657         traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)
658     }
659 }