]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/cast.rs
Fix font color for help button in ayu and dark themes
[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 crate::hir::def_id::DefId;
34 use crate::type_error_struct;
35 use rustc_ast as ast;
36 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
37 use rustc_hir as hir;
38 use rustc_hir::lang_items;
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                 if let ty::Ref(reg, _, mutbl) = self.cast_ty.kind {
352                     if fcx
353                         .try_coerce(
354                             self.expr,
355                             fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
356                             self.cast_ty,
357                             AllowTwoPhase::No,
358                         )
359                         .is_ok()
360                     {
361                         sugg = Some(format!("&{}", mutbl.prefix_str()));
362                     }
363                 }
364                 if let Some(sugg) = sugg {
365                     err.span_label(self.span, "invalid cast");
366                     err.span_suggestion_verbose(
367                         self.expr.span.shrink_to_lo(),
368                         "borrow the value for the cast to be valid",
369                         sugg,
370                         Applicability::MachineApplicable,
371                     );
372                 } else if !matches!(
373                     self.cast_ty.kind,
374                     ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
375                 ) {
376                     let mut label = true;
377                     // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
378                     if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
379                         if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::from_trait) {
380                             let ty = fcx.resolve_vars_if_possible(&self.cast_ty);
381                             // Erase regions to avoid panic in `prove_value` when calling
382                             // `type_implements_trait`.
383                             let ty = fcx.tcx.erase_regions(&ty);
384                             let expr_ty = fcx.resolve_vars_if_possible(&self.expr_ty);
385                             let expr_ty = fcx.tcx.erase_regions(&expr_ty);
386                             let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
387                             // Check for infer types because cases like `Option<{integer}>` would
388                             // panic otherwise.
389                             if !expr_ty.has_infer_types()
390                                 && !ty.has_infer_types()
391                                 && fcx.tcx.type_implements_trait((
392                                     from_trait,
393                                     ty,
394                                     ty_params,
395                                     fcx.param_env,
396                                 ))
397                             {
398                                 label = false;
399                                 err.span_suggestion(
400                                     self.span,
401                                     "consider using the `From` trait instead",
402                                     format!("{}::from({})", self.cast_ty, snippet),
403                                     Applicability::MaybeIncorrect,
404                                 );
405                             }
406                         }
407                     }
408                     let msg = "an `as` expression can only be used to convert between primitive \
409                                types or to coerce to a specific trait object";
410                     if label {
411                         err.span_label(self.span, msg);
412                     } else {
413                         err.note(msg);
414                     }
415                 } else {
416                     err.span_label(self.span, "invalid cast");
417                 }
418                 err.emit();
419             }
420             CastError::SizedUnsizedCast => {
421                 use crate::structured_errors::{SizedUnsizedCastError, StructuredDiagnostic};
422                 SizedUnsizedCastError::new(
423                     &fcx.tcx.sess,
424                     self.span,
425                     self.expr_ty,
426                     fcx.ty_to_string(self.cast_ty),
427                 )
428                 .diagnostic()
429                 .emit();
430             }
431             CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
432                 let unknown_cast_to = match e {
433                     CastError::UnknownCastPtrKind => true,
434                     CastError::UnknownExprPtrKind => false,
435                     _ => bug!(),
436                 };
437                 let mut err = struct_span_err!(
438                     fcx.tcx.sess,
439                     if unknown_cast_to { self.cast_span } else { self.span },
440                     E0641,
441                     "cannot cast {} a pointer of an unknown kind",
442                     if unknown_cast_to { "to" } else { "from" }
443                 );
444                 if unknown_cast_to {
445                     err.span_label(self.cast_span, "needs more type information");
446                     err.note(
447                         "the type information given here is insufficient to check whether \
448                         the pointer cast is valid",
449                     );
450                 } else {
451                     err.span_label(
452                         self.span,
453                         "the type information given here is insufficient to check whether \
454                         the pointer cast is valid",
455                     );
456                 }
457                 err.emit();
458             }
459         }
460     }
461
462     fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
463         if self.cast_ty.references_error() || self.expr_ty.references_error() {
464             return;
465         }
466
467         let tstr = fcx.ty_to_string(self.cast_ty);
468         let mut err = type_error_struct!(
469             fcx.tcx.sess,
470             self.span,
471             self.expr_ty,
472             E0620,
473             "cast to unsized type: `{}` as `{}`",
474             fcx.resolve_vars_if_possible(&self.expr_ty),
475             tstr
476         );
477         match self.expr_ty.kind {
478             ty::Ref(_, _, mt) => {
479                 let mtstr = mt.prefix_str();
480                 if self.cast_ty.is_trait() {
481                     match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
482                         Ok(s) => {
483                             err.span_suggestion(
484                                 self.cast_span,
485                                 "try casting to a reference instead",
486                                 format!("&{}{}", mtstr, s),
487                                 Applicability::MachineApplicable,
488                             );
489                         }
490                         Err(_) => {
491                             let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
492                             err.span_help(self.cast_span, msg);
493                         }
494                     }
495                 } else {
496                     let msg = &format!(
497                         "consider using an implicit coercion to `&{}{}` instead",
498                         mtstr, tstr
499                     );
500                     err.span_help(self.span, msg);
501                 }
502             }
503             ty::Adt(def, ..) if def.is_box() => {
504                 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
505                     Ok(s) => {
506                         err.span_suggestion(
507                             self.cast_span,
508                             "you can cast to a `Box` instead",
509                             format!("Box<{}>", s),
510                             Applicability::MachineApplicable,
511                         );
512                     }
513                     Err(_) => {
514                         err.span_help(
515                             self.cast_span,
516                             &format!("you might have meant `Box<{}>`", tstr),
517                         );
518                     }
519                 }
520             }
521             _ => {
522                 err.span_help(self.expr.span, "consider using a box or reference as appropriate");
523             }
524         }
525         err.emit();
526     }
527
528     fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
529         let t_cast = self.cast_ty;
530         let t_expr = self.expr_ty;
531         let type_asc_or =
532             if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
533         let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
534             ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
535         } else {
536             ("", lint::builtin::TRIVIAL_CASTS)
537         };
538         fcx.tcx.struct_span_lint_hir(lint, self.expr.hir_id, self.span, |err| {
539             err.build(&format!(
540                 "trivial {}cast: `{}` as `{}`",
541                 adjective,
542                 fcx.ty_to_string(t_expr),
543                 fcx.ty_to_string(t_cast)
544             ))
545             .help(&format!(
546                 "cast can be replaced by coercion; this might \
547                                    require {}a temporary variable",
548                 type_asc_or
549             ))
550             .emit();
551         });
552     }
553
554     pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
555         self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
556         self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
557
558         debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
559
560         if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
561             self.report_cast_to_unsized_type(fcx);
562         } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
563             // No sense in giving duplicate error messages
564         } else {
565             match self.try_coercion_cast(fcx) {
566                 Ok(()) => {
567                     self.trivial_cast_lint(fcx);
568                     debug!(" -> CoercionCast");
569                     fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
570                 }
571                 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
572                     self.report_object_unsafe_cast(&fcx, did);
573                 }
574                 Err(_) => {
575                     match self.do_check(fcx) {
576                         Ok(k) => {
577                             debug!(" -> {:?}", k);
578                         }
579                         Err(e) => self.report_cast_error(fcx, e),
580                     };
581                 }
582             };
583         }
584     }
585
586     fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
587         let violations = fcx.tcx.object_safety_violations(did);
588         let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
589         err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
590         err.emit();
591     }
592
593     /// Checks a cast, and report an error if one exists. In some cases, this
594     /// can return Ok and create type errors in the fcx rather than returning
595     /// directly. coercion-cast is handled in check instead of here.
596     pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
597         use rustc_middle::ty::cast::CastTy::*;
598         use rustc_middle::ty::cast::IntTy::*;
599
600         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
601         {
602             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
603             // Function item types may need to be reified before casts.
604             (None, Some(t_cast)) => {
605                 match self.expr_ty.kind {
606                     ty::FnDef(..) => {
607                         // Attempt a coercion to a fn pointer type.
608                         let f = fcx.normalize_associated_types_in(
609                             self.expr.span,
610                             &self.expr_ty.fn_sig(fcx.tcx),
611                         );
612                         let res = fcx.try_coerce(
613                             self.expr,
614                             self.expr_ty,
615                             fcx.tcx.mk_fn_ptr(f),
616                             AllowTwoPhase::No,
617                         );
618                         if let Err(TypeError::IntrinsicCast) = res {
619                             return Err(CastError::IllegalCast);
620                         }
621                         if res.is_err() {
622                             return Err(CastError::NonScalar);
623                         }
624                         (FnPtr, t_cast)
625                     }
626                     // Special case some errors for references, and check for
627                     // array-ptr-casts. `Ref` is not a CastTy because the cast
628                     // is split into a coercion to a pointer type, followed by
629                     // a cast.
630                     ty::Ref(_, inner_ty, mutbl) => {
631                         return match t_cast {
632                             Int(_) | Float => match inner_ty.kind {
633                                 ty::Int(_)
634                                 | ty::Uint(_)
635                                 | ty::Float(_)
636                                 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
637                                     Err(CastError::NeedDeref)
638                                 }
639                                 _ => Err(CastError::NeedViaPtr),
640                             },
641                             // array-ptr-cast
642                             Ptr(mt) => {
643                                 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
644                             }
645                             _ => Err(CastError::NonScalar),
646                         };
647                     }
648                     _ => return Err(CastError::NonScalar),
649                 }
650             }
651             _ => return Err(CastError::NonScalar),
652         };
653
654         match (t_from, t_cast) {
655             // These types have invariants! can't cast into them.
656             (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
657
658             // * -> Bool
659             (_, Int(Bool)) => Err(CastError::CastToBool),
660
661             // * -> Char
662             (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
663             (_, Int(Char)) => Err(CastError::CastToChar),
664
665             // prim -> float,ptr
666             (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
667
668             (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
669                 Err(CastError::IllegalCast)
670             }
671
672             // ptr -> *
673             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
674             (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
675             (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
676
677             // * -> ptr
678             (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
679             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
680
681             // prim -> prim
682             (Int(CEnum), Int(_)) => {
683                 self.cenum_impl_drop_lint(fcx);
684                 Ok(CastKind::EnumCast)
685             }
686             (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
687
688             (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
689         }
690     }
691
692     fn check_ptr_ptr_cast(
693         &self,
694         fcx: &FnCtxt<'a, 'tcx>,
695         m_expr: ty::TypeAndMut<'tcx>,
696         m_cast: ty::TypeAndMut<'tcx>,
697     ) -> Result<CastKind, CastError> {
698         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
699         // ptr-ptr cast. vtables must match.
700
701         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
702         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
703
704         let cast_kind = match cast_kind {
705             // We can't cast if target pointer kind is unknown
706             None => return Err(CastError::UnknownCastPtrKind),
707             Some(cast_kind) => cast_kind,
708         };
709
710         // Cast to thin pointer is OK
711         if cast_kind == PointerKind::Thin {
712             return Ok(CastKind::PtrPtrCast);
713         }
714
715         let expr_kind = match expr_kind {
716             // We can't cast to fat pointer if source pointer kind is unknown
717             None => return Err(CastError::UnknownExprPtrKind),
718             Some(expr_kind) => expr_kind,
719         };
720
721         // thin -> fat? report invalid cast (don't complain about vtable kinds)
722         if expr_kind == PointerKind::Thin {
723             return Err(CastError::SizedUnsizedCast);
724         }
725
726         // vtable kinds must match
727         if cast_kind == expr_kind {
728             Ok(CastKind::PtrPtrCast)
729         } else {
730             Err(CastError::DifferingKinds)
731         }
732     }
733
734     fn check_fptr_ptr_cast(
735         &self,
736         fcx: &FnCtxt<'a, 'tcx>,
737         m_cast: ty::TypeAndMut<'tcx>,
738     ) -> Result<CastKind, CastError> {
739         // fptr-ptr cast. must be to thin ptr
740
741         match fcx.pointer_kind(m_cast.ty, self.span)? {
742             None => Err(CastError::UnknownCastPtrKind),
743             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
744             _ => Err(CastError::IllegalCast),
745         }
746     }
747
748     fn check_ptr_addr_cast(
749         &self,
750         fcx: &FnCtxt<'a, 'tcx>,
751         m_expr: ty::TypeAndMut<'tcx>,
752     ) -> Result<CastKind, CastError> {
753         // ptr-addr cast. must be from thin ptr
754
755         match fcx.pointer_kind(m_expr.ty, self.span)? {
756             None => Err(CastError::UnknownExprPtrKind),
757             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
758             _ => Err(CastError::NeedViaThinPtr),
759         }
760     }
761
762     fn check_ref_cast(
763         &self,
764         fcx: &FnCtxt<'a, 'tcx>,
765         m_expr: ty::TypeAndMut<'tcx>,
766         m_cast: ty::TypeAndMut<'tcx>,
767     ) -> Result<CastKind, CastError> {
768         // array-ptr-cast.
769
770         if m_expr.mutbl == hir::Mutability::Not && m_cast.mutbl == hir::Mutability::Not {
771             if let ty::Array(ety, _) = m_expr.ty.kind {
772                 // Due to the limitations of LLVM global constants,
773                 // region pointers end up pointing at copies of
774                 // vector elements instead of the original values.
775                 // To allow raw pointers to work correctly, we
776                 // need to special-case obtaining a raw pointer
777                 // from a region pointer to a vector.
778
779                 // Coerce to a raw pointer so that we generate AddressOf in MIR.
780                 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
781                 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No)
782                     .unwrap_or_else(|_| {
783                         bug!(
784                         "could not cast from reference to array to pointer to array ({:?} to {:?})",
785                         self.expr_ty,
786                         array_ptr_type,
787                     )
788                     });
789
790                 // this will report a type mismatch if needed
791                 fcx.demand_eqtype(self.span, ety, m_cast.ty);
792                 return Ok(CastKind::ArrayPtrCast);
793             }
794         }
795
796         Err(CastError::IllegalCast)
797     }
798
799     fn check_addr_ptr_cast(
800         &self,
801         fcx: &FnCtxt<'a, 'tcx>,
802         m_cast: TypeAndMut<'tcx>,
803     ) -> Result<CastKind, CastError> {
804         // ptr-addr cast. pointer must be thin.
805         match fcx.pointer_kind(m_cast.ty, self.span)? {
806             None => Err(CastError::UnknownCastPtrKind),
807             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
808             _ => Err(CastError::IllegalCast),
809         }
810     }
811
812     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
813         match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No) {
814             Ok(_) => Ok(()),
815             Err(err) => Err(err),
816         }
817     }
818
819     fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
820         if let ty::Adt(d, _) = self.expr_ty.kind {
821             if d.has_dtor(fcx.tcx) {
822                 fcx.tcx.struct_span_lint_hir(
823                     lint::builtin::CENUM_IMPL_DROP_CAST,
824                     self.expr.hir_id,
825                     self.span,
826                     |err| {
827                         err.build(&format!(
828                             "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
829                             self.expr_ty, self.cast_ty
830                         ))
831                         .emit();
832                     },
833                 );
834             }
835         }
836     }
837 }
838
839 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
840     fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
841         let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None);
842         traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)
843     }
844 }