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