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