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