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