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