]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/cast.rs
Rollup merge of #103339 - Rageking8:fix-some-typos, r=fee1-dead
[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 }
64
65 /// The kind of pointer and associated metadata (thin, length or vtable) - we
66 /// only allow casts between fat pointers if their metadata have the same
67 /// kind.
68 #[derive(Copy, Clone, PartialEq, Eq)]
69 enum PointerKind<'tcx> {
70     /// No metadata attached, ie pointer to sized type or foreign type
71     Thin,
72     /// A trait object
73     VTable(Option<DefId>),
74     /// Slice
75     Length,
76     /// The unsize info of this projection
77     OfProjection(&'tcx ty::ProjectionTy<'tcx>),
78     /// The unsize info of this opaque ty
79     OfOpaque(DefId, SubstsRef<'tcx>),
80     /// The unsize info of this parameter
81     OfParam(&'tcx ty::ParamTy),
82 }
83
84 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
85     /// Returns the kind of unsize information of t, or None
86     /// if t is unknown.
87     fn pointer_kind(
88         &self,
89         t: Ty<'tcx>,
90         span: Span,
91     ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
92         debug!("pointer_kind({:?}, {:?})", t, span);
93
94         let t = self.resolve_vars_if_possible(t);
95
96         if let Some(reported) = t.error_reported() {
97             return Err(reported);
98         }
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(ref pi) => Some(PointerKind::OfProjection(pi)),
123             ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
124             ty::Param(ref 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     ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
214         let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
215         let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
216
217         // For better error messages, check for some obviously unsized
218         // cases now. We do a more thorough check at the end, once
219         // inference is more completely known.
220         match cast_ty.kind() {
221             ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
222                 let reported = check.report_cast_to_unsized_type(fcx);
223                 Err(reported)
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 Some(reported) =
615             self.cast_ty.error_reported().or_else(|| self.expr_ty.error_reported())
616         {
617             return reported;
618         }
619
620         let tstr = fcx.ty_to_string(self.cast_ty);
621         let mut err = type_error_struct!(
622             fcx.tcx.sess,
623             self.span,
624             self.expr_ty,
625             E0620,
626             "cast to unsized type: `{}` as `{}`",
627             fcx.resolve_vars_if_possible(self.expr_ty),
628             tstr
629         );
630         match self.expr_ty.kind() {
631             ty::Ref(_, _, mt) => {
632                 let mtstr = mt.prefix_str();
633                 if self.cast_ty.is_trait() {
634                     match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
635                         Ok(s) => {
636                             err.span_suggestion(
637                                 self.cast_span,
638                                 "try casting to a reference instead",
639                                 format!("&{}{}", mtstr, s),
640                                 Applicability::MachineApplicable,
641                             );
642                         }
643                         Err(_) => {
644                             let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
645                             err.span_help(self.cast_span, msg);
646                         }
647                     }
648                 } else {
649                     let msg =
650                         &format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
651                     err.span_help(self.span, msg);
652                 }
653             }
654             ty::Adt(def, ..) if def.is_box() => {
655                 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
656                     Ok(s) => {
657                         err.span_suggestion(
658                             self.cast_span,
659                             "you can cast to a `Box` instead",
660                             format!("Box<{s}>"),
661                             Applicability::MachineApplicable,
662                         );
663                     }
664                     Err(_) => {
665                         err.span_help(
666                             self.cast_span,
667                             &format!("you might have meant `Box<{tstr}>`"),
668                         );
669                     }
670                 }
671             }
672             _ => {
673                 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
674             }
675         }
676         err.emit()
677     }
678
679     fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
680         let t_cast = self.cast_ty;
681         let t_expr = self.expr_ty;
682         let type_asc_or =
683             if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
684         let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
685             ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
686         } else {
687             ("", lint::builtin::TRIVIAL_CASTS)
688         };
689         fcx.tcx.struct_span_lint_hir(
690             lint,
691             self.expr.hir_id,
692             self.span,
693             DelayDm(|| {
694                 format!(
695                     "trivial {}cast: `{}` as `{}`",
696                     adjective,
697                     fcx.ty_to_string(t_expr),
698                     fcx.ty_to_string(t_cast)
699                 )
700             }),
701             |lint| {
702                 lint.help(format!(
703                     "cast can be replaced by coercion; this might \
704                      require {type_asc_or}a temporary variable"
705                 ))
706             },
707         );
708     }
709
710     #[instrument(skip(fcx), level = "debug")]
711     pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
712         self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
713         self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
714
715         debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
716
717         if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
718             && !self.cast_ty.has_infer_types()
719         {
720             self.report_cast_to_unsized_type(fcx);
721         } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
722             // No sense in giving duplicate error messages
723         } else {
724             match self.try_coercion_cast(fcx) {
725                 Ok(()) => {
726                     self.trivial_cast_lint(fcx);
727                     debug!(" -> CoercionCast");
728                     fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
729                 }
730                 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
731                     self.report_object_unsafe_cast(&fcx, did);
732                 }
733                 Err(_) => {
734                     match self.do_check(fcx) {
735                         Ok(k) => {
736                             debug!(" -> {:?}", k);
737                         }
738                         Err(e) => self.report_cast_error(fcx, e),
739                     };
740                 }
741             };
742         }
743     }
744
745     fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
746         let violations = fcx.tcx.object_safety_violations(did);
747         let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
748         err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
749         err.emit();
750     }
751
752     /// Checks a cast, and report an error if one exists. In some cases, this
753     /// can return Ok and create type errors in the fcx rather than returning
754     /// directly. coercion-cast is handled in check instead of here.
755     pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
756         use rustc_middle::ty::cast::CastTy::*;
757         use rustc_middle::ty::cast::IntTy::*;
758
759         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
760         {
761             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
762             // Function item types may need to be reified before casts.
763             (None, Some(t_cast)) => {
764                 match *self.expr_ty.kind() {
765                     ty::FnDef(..) => {
766                         // Attempt a coercion to a fn pointer type.
767                         let f = fcx.normalize_associated_types_in(
768                             self.expr_span,
769                             self.expr_ty.fn_sig(fcx.tcx),
770                         );
771                         let res = fcx.try_coerce(
772                             self.expr,
773                             self.expr_ty,
774                             fcx.tcx.mk_fn_ptr(f),
775                             AllowTwoPhase::No,
776                             None,
777                         );
778                         if let Err(TypeError::IntrinsicCast) = res {
779                             return Err(CastError::IllegalCast);
780                         }
781                         if res.is_err() {
782                             return Err(CastError::NonScalar);
783                         }
784                         (FnPtr, t_cast)
785                     }
786                     // Special case some errors for references, and check for
787                     // array-ptr-casts. `Ref` is not a CastTy because the cast
788                     // is split into a coercion to a pointer type, followed by
789                     // a cast.
790                     ty::Ref(_, inner_ty, mutbl) => {
791                         return match t_cast {
792                             Int(_) | Float => match *inner_ty.kind() {
793                                 ty::Int(_)
794                                 | ty::Uint(_)
795                                 | ty::Float(_)
796                                 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
797                                     Err(CastError::NeedDeref)
798                                 }
799                                 _ => Err(CastError::NeedViaPtr),
800                             },
801                             // array-ptr-cast
802                             Ptr(mt) => {
803                                 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
804                             }
805                             _ => Err(CastError::NonScalar),
806                         };
807                     }
808                     _ => return Err(CastError::NonScalar),
809                 }
810             }
811             _ => return Err(CastError::NonScalar),
812         };
813
814         if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
815             if adt_def.did().krate != LOCAL_CRATE {
816                 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
817                     return Err(CastError::ForeignNonExhaustiveAdt);
818                 }
819             }
820         }
821
822         match (t_from, t_cast) {
823             // These types have invariants! can't cast into them.
824             (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
825
826             // * -> Bool
827             (_, Int(Bool)) => Err(CastError::CastToBool),
828
829             // * -> Char
830             (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
831             (_, Int(Char)) => Err(CastError::CastToChar),
832
833             // prim -> float,ptr
834             (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
835
836             (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
837                 Err(CastError::IllegalCast)
838             }
839
840             // ptr -> *
841             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
842
843             // ptr-addr-cast
844             (Ptr(m_expr), Int(t_c)) => {
845                 self.lossy_provenance_ptr2int_lint(fcx, t_c);
846                 self.check_ptr_addr_cast(fcx, m_expr)
847             }
848             (FnPtr, Int(_)) => {
849                 // FIXME(#95489): there should eventually be a lint for these casts
850                 Ok(CastKind::FnPtrAddrCast)
851             }
852             // addr-ptr-cast
853             (Int(_), Ptr(mt)) => {
854                 self.fuzzy_provenance_int2ptr_lint(fcx);
855                 self.check_addr_ptr_cast(fcx, mt)
856             }
857             // fn-ptr-cast
858             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
859
860             // prim -> prim
861             (Int(CEnum), Int(_)) => {
862                 self.cenum_impl_drop_lint(fcx);
863                 Ok(CastKind::EnumCast)
864             }
865             (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
866
867             (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
868
869             (_, DynStar) | (DynStar, _) => bug!("should be handled by `try_coerce`"),
870         }
871     }
872
873     fn check_ptr_ptr_cast(
874         &self,
875         fcx: &FnCtxt<'a, 'tcx>,
876         m_expr: ty::TypeAndMut<'tcx>,
877         m_cast: ty::TypeAndMut<'tcx>,
878     ) -> Result<CastKind, CastError> {
879         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
880         // ptr-ptr cast. vtables must match.
881
882         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
883         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
884
885         let Some(cast_kind) = cast_kind else {
886             // We can't cast if target pointer kind is unknown
887             return Err(CastError::UnknownCastPtrKind);
888         };
889
890         // Cast to thin pointer is OK
891         if cast_kind == PointerKind::Thin {
892             return Ok(CastKind::PtrPtrCast);
893         }
894
895         let Some(expr_kind) = expr_kind else {
896             // We can't cast to fat pointer if source pointer kind is unknown
897             return Err(CastError::UnknownExprPtrKind);
898         };
899
900         // thin -> fat? report invalid cast (don't complain about vtable kinds)
901         if expr_kind == PointerKind::Thin {
902             return Err(CastError::SizedUnsizedCast);
903         }
904
905         // vtable kinds must match
906         if cast_kind == expr_kind {
907             Ok(CastKind::PtrPtrCast)
908         } else {
909             Err(CastError::DifferingKinds)
910         }
911     }
912
913     fn check_fptr_ptr_cast(
914         &self,
915         fcx: &FnCtxt<'a, 'tcx>,
916         m_cast: ty::TypeAndMut<'tcx>,
917     ) -> Result<CastKind, CastError> {
918         // fptr-ptr cast. must be to thin ptr
919
920         match fcx.pointer_kind(m_cast.ty, self.span)? {
921             None => Err(CastError::UnknownCastPtrKind),
922             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
923             _ => Err(CastError::IllegalCast),
924         }
925     }
926
927     fn check_ptr_addr_cast(
928         &self,
929         fcx: &FnCtxt<'a, 'tcx>,
930         m_expr: ty::TypeAndMut<'tcx>,
931     ) -> Result<CastKind, CastError> {
932         // ptr-addr cast. must be from thin ptr
933
934         match fcx.pointer_kind(m_expr.ty, self.span)? {
935             None => Err(CastError::UnknownExprPtrKind),
936             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
937             _ => Err(CastError::NeedViaThinPtr),
938         }
939     }
940
941     fn check_ref_cast(
942         &self,
943         fcx: &FnCtxt<'a, 'tcx>,
944         m_expr: ty::TypeAndMut<'tcx>,
945         m_cast: ty::TypeAndMut<'tcx>,
946     ) -> Result<CastKind, CastError> {
947         // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
948         if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
949             if let ty::Array(ety, _) = m_expr.ty.kind() {
950                 // Due to the limitations of LLVM global constants,
951                 // region pointers end up pointing at copies of
952                 // vector elements instead of the original values.
953                 // To allow raw pointers to work correctly, we
954                 // need to special-case obtaining a raw pointer
955                 // from a region pointer to a vector.
956
957                 // Coerce to a raw pointer so that we generate AddressOf in MIR.
958                 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
959                 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
960                     .unwrap_or_else(|_| {
961                         bug!(
962                         "could not cast from reference to array to pointer to array ({:?} to {:?})",
963                         self.expr_ty,
964                         array_ptr_type,
965                     )
966                     });
967
968                 // this will report a type mismatch if needed
969                 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
970                 return Ok(CastKind::ArrayPtrCast);
971             }
972         }
973
974         Err(CastError::IllegalCast)
975     }
976
977     fn check_addr_ptr_cast(
978         &self,
979         fcx: &FnCtxt<'a, 'tcx>,
980         m_cast: TypeAndMut<'tcx>,
981     ) -> Result<CastKind, CastError> {
982         // ptr-addr cast. pointer must be thin.
983         match fcx.pointer_kind(m_cast.ty, self.span)? {
984             None => Err(CastError::UnknownCastPtrKind),
985             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
986             Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
987             Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
988             Some(
989                 PointerKind::OfProjection(_)
990                 | PointerKind::OfOpaque(_, _)
991                 | PointerKind::OfParam(_),
992             ) => Err(CastError::IntToFatCast(None)),
993         }
994     }
995
996     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
997         match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
998             Ok(_) => Ok(()),
999             Err(err) => Err(err),
1000         }
1001     }
1002
1003     fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1004         if let ty::Adt(d, _) = self.expr_ty.kind()
1005             && d.has_dtor(fcx.tcx)
1006         {
1007             fcx.tcx.struct_span_lint_hir(
1008                 lint::builtin::CENUM_IMPL_DROP_CAST,
1009                 self.expr.hir_id,
1010                 self.span,
1011                 DelayDm(|| format!(
1012                     "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1013                     self.expr_ty, self.cast_ty
1014                 )),
1015                 |lint| {
1016                     lint
1017                 },
1018             );
1019         }
1020     }
1021
1022     fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1023         fcx.tcx.struct_span_lint_hir(
1024             lint::builtin::LOSSY_PROVENANCE_CASTS,
1025             self.expr.hir_id,
1026             self.span,
1027             DelayDm(|| format!(
1028                     "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1029                     self.expr_ty, self.cast_ty
1030                 )),
1031             |lint| {
1032                 let msg = "use `.addr()` to obtain the address of a pointer";
1033
1034                 let expr_prec = self.expr.precedence().order();
1035                 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1036
1037                 let scalar_cast = match t_c {
1038                     ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1039                     _ => format!(" as {}", self.cast_ty),
1040                 };
1041
1042                 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1043
1044                 if needs_parens {
1045                     let suggestions = vec![
1046                         (self.expr_span.shrink_to_lo(), String::from("(")),
1047                         (cast_span, format!(").addr(){scalar_cast}")),
1048                     ];
1049
1050                     lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1051                 } else {
1052                     lint.span_suggestion(
1053                         cast_span,
1054                         msg,
1055                         format!(".addr(){scalar_cast}"),
1056                         Applicability::MaybeIncorrect,
1057                     );
1058                 }
1059
1060                 lint.help(
1061                     "if you can't comply with strict provenance and need to expose the pointer \
1062                     provenance you can use `.expose_addr()` instead"
1063                 );
1064
1065                 lint
1066             },
1067         );
1068     }
1069
1070     fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1071         fcx.tcx.struct_span_lint_hir(
1072             lint::builtin::FUZZY_PROVENANCE_CASTS,
1073             self.expr.hir_id,
1074             self.span,
1075             DelayDm(|| format!(
1076                 "strict provenance disallows casting integer `{}` to pointer `{}`",
1077                 self.expr_ty, self.cast_ty
1078             )),
1079             |lint| {
1080                 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1081                 let suggestions = vec![
1082                     (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1083                     (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1084                 ];
1085
1086                 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1087                 lint.help(
1088                     "if you can't comply with strict provenance and don't have a pointer with \
1089                     the correct provenance you can use `std::ptr::from_exposed_addr()` instead"
1090                  );
1091
1092                 lint
1093             },
1094         );
1095     }
1096 }