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