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