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