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