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