]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/cast.rs
Rollup merge of #98496 - BoxyUwU:instancers_bad_equality, r=lcnr
[rust.git] / compiler / rustc_hir_analysis / 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, DelayDm, 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(
758             lint,
759             self.expr.hir_id,
760             self.span,
761             DelayDm(|| {
762                 format!(
763                     "trivial {}cast: `{}` as `{}`",
764                     adjective,
765                     fcx.ty_to_string(t_expr),
766                     fcx.ty_to_string(t_cast)
767                 )
768             }),
769             |lint| {
770                 lint.help(format!(
771                     "cast can be replaced by coercion; this might \
772                      require {type_asc_or}a temporary variable"
773                 ))
774             },
775         );
776     }
777
778     #[instrument(skip(fcx), level = "debug")]
779     pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
780         self.expr_ty = fcx.structurally_resolved_type(self.expr_span, self.expr_ty);
781         self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
782
783         debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
784
785         if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty, self.span)
786             && !self.cast_ty.has_infer_types()
787         {
788             self.report_cast_to_unsized_type(fcx);
789         } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
790             // No sense in giving duplicate error messages
791         } else {
792             match self.try_coercion_cast(fcx) {
793                 Ok(()) => {
794                     self.trivial_cast_lint(fcx);
795                     debug!(" -> CoercionCast");
796                     fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
797                 }
798                 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
799                     self.report_object_unsafe_cast(&fcx, did);
800                 }
801                 Err(_) => {
802                     match self.do_check(fcx) {
803                         Ok(k) => {
804                             debug!(" -> {:?}", k);
805                         }
806                         Err(e) => self.report_cast_error(fcx, e),
807                     };
808                 }
809             };
810         }
811     }
812
813     fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
814         let violations = fcx.tcx.object_safety_violations(did);
815         let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
816         err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
817         err.emit();
818     }
819
820     /// Checks a cast, and report an error if one exists. In some cases, this
821     /// can return Ok and create type errors in the fcx rather than returning
822     /// directly. coercion-cast is handled in check instead of here.
823     pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
824         use rustc_middle::ty::cast::CastTy::*;
825         use rustc_middle::ty::cast::IntTy::*;
826
827         let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
828         {
829             (Some(t_from), Some(t_cast)) => (t_from, t_cast),
830             // Function item types may need to be reified before casts.
831             (None, Some(t_cast)) => {
832                 match *self.expr_ty.kind() {
833                     ty::FnDef(..) => {
834                         // Attempt a coercion to a fn pointer type.
835                         let f = fcx.normalize_associated_types_in(
836                             self.expr_span,
837                             self.expr_ty.fn_sig(fcx.tcx),
838                         );
839                         let res = fcx.try_coerce(
840                             self.expr,
841                             self.expr_ty,
842                             fcx.tcx.mk_fn_ptr(f),
843                             AllowTwoPhase::No,
844                             None,
845                         );
846                         if let Err(TypeError::IntrinsicCast) = res {
847                             return Err(CastError::IllegalCast);
848                         }
849                         if res.is_err() {
850                             return Err(CastError::NonScalar);
851                         }
852                         (FnPtr, t_cast)
853                     }
854                     // Special case some errors for references, and check for
855                     // array-ptr-casts. `Ref` is not a CastTy because the cast
856                     // is split into a coercion to a pointer type, followed by
857                     // a cast.
858                     ty::Ref(_, inner_ty, mutbl) => {
859                         return match t_cast {
860                             Int(_) | Float => match *inner_ty.kind() {
861                                 ty::Int(_)
862                                 | ty::Uint(_)
863                                 | ty::Float(_)
864                                 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
865                                     Err(CastError::NeedDeref)
866                                 }
867                                 _ => Err(CastError::NeedViaPtr),
868                             },
869                             // array-ptr-cast
870                             Ptr(mt) => {
871                                 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
872                             }
873                             _ => Err(CastError::NonScalar),
874                         };
875                     }
876                     _ => return Err(CastError::NonScalar),
877                 }
878             }
879             _ => return Err(CastError::NonScalar),
880         };
881
882         if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
883             if adt_def.did().krate != LOCAL_CRATE {
884                 if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
885                     return Err(CastError::ForeignNonExhaustiveAdt);
886                 }
887             }
888         }
889
890         match (t_from, t_cast) {
891             // These types have invariants! can't cast into them.
892             (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
893
894             // * -> Bool
895             (_, Int(Bool)) => Err(CastError::CastToBool),
896
897             // * -> Char
898             (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
899             (_, Int(Char)) => Err(CastError::CastToChar),
900
901             // prim -> float,ptr
902             (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
903
904             (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
905                 Err(CastError::IllegalCast)
906             }
907
908             // ptr -> *
909             (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
910
911             // ptr-addr-cast
912             (Ptr(m_expr), Int(t_c)) => {
913                 self.lossy_provenance_ptr2int_lint(fcx, t_c);
914                 self.check_ptr_addr_cast(fcx, m_expr)
915             }
916             (FnPtr, Int(_)) => {
917                 // FIXME(#95489): there should eventually be a lint for these casts
918                 Ok(CastKind::FnPtrAddrCast)
919             }
920             // addr-ptr-cast
921             (Int(_), Ptr(mt)) => {
922                 self.fuzzy_provenance_int2ptr_lint(fcx);
923                 self.check_addr_ptr_cast(fcx, mt)
924             }
925             // fn-ptr-cast
926             (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
927
928             // prim -> prim
929             (Int(CEnum), Int(_)) => {
930                 self.cenum_impl_drop_lint(fcx);
931                 Ok(CastKind::EnumCast)
932             }
933             (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
934
935             (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
936
937             // FIXME(dyn-star): this needs more conditions...
938             (_, DynStar) => Ok(CastKind::DynStarCast),
939
940             // FIXME(dyn-star): do we want to allow dyn* upcasting or other casts?
941             (DynStar, _) => Err(CastError::IllegalCast),
942         }
943     }
944
945     fn check_ptr_ptr_cast(
946         &self,
947         fcx: &FnCtxt<'a, 'tcx>,
948         m_expr: ty::TypeAndMut<'tcx>,
949         m_cast: ty::TypeAndMut<'tcx>,
950     ) -> Result<CastKind, CastError> {
951         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
952         // ptr-ptr cast. vtables must match.
953
954         let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
955         let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
956
957         let Some(cast_kind) = cast_kind else {
958             // We can't cast if target pointer kind is unknown
959             return Err(CastError::UnknownCastPtrKind);
960         };
961
962         // Cast to thin pointer is OK
963         if cast_kind == PointerKind::Thin {
964             return Ok(CastKind::PtrPtrCast);
965         }
966
967         let Some(expr_kind) = expr_kind else {
968             // We can't cast to fat pointer if source pointer kind is unknown
969             return Err(CastError::UnknownExprPtrKind);
970         };
971
972         // thin -> fat? report invalid cast (don't complain about vtable kinds)
973         if expr_kind == PointerKind::Thin {
974             return Err(CastError::SizedUnsizedCast);
975         }
976
977         // vtable kinds must match
978         if cast_kind == expr_kind {
979             Ok(CastKind::PtrPtrCast)
980         } else {
981             Err(CastError::DifferingKinds)
982         }
983     }
984
985     fn check_fptr_ptr_cast(
986         &self,
987         fcx: &FnCtxt<'a, 'tcx>,
988         m_cast: ty::TypeAndMut<'tcx>,
989     ) -> Result<CastKind, CastError> {
990         // fptr-ptr cast. must be to thin ptr
991
992         match fcx.pointer_kind(m_cast.ty, self.span)? {
993             None => Err(CastError::UnknownCastPtrKind),
994             Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
995             _ => Err(CastError::IllegalCast),
996         }
997     }
998
999     fn check_ptr_addr_cast(
1000         &self,
1001         fcx: &FnCtxt<'a, 'tcx>,
1002         m_expr: ty::TypeAndMut<'tcx>,
1003     ) -> Result<CastKind, CastError> {
1004         // ptr-addr cast. must be from thin ptr
1005
1006         match fcx.pointer_kind(m_expr.ty, self.span)? {
1007             None => Err(CastError::UnknownExprPtrKind),
1008             Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1009             _ => Err(CastError::NeedViaThinPtr),
1010         }
1011     }
1012
1013     fn check_ref_cast(
1014         &self,
1015         fcx: &FnCtxt<'a, 'tcx>,
1016         m_expr: ty::TypeAndMut<'tcx>,
1017         m_cast: ty::TypeAndMut<'tcx>,
1018     ) -> Result<CastKind, CastError> {
1019         // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1020         if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
1021             if let ty::Array(ety, _) = m_expr.ty.kind() {
1022                 // Due to the limitations of LLVM global constants,
1023                 // region pointers end up pointing at copies of
1024                 // vector elements instead of the original values.
1025                 // To allow raw pointers to work correctly, we
1026                 // need to special-case obtaining a raw pointer
1027                 // from a region pointer to a vector.
1028
1029                 // Coerce to a raw pointer so that we generate AddressOf in MIR.
1030                 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
1031                 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1032                     .unwrap_or_else(|_| {
1033                         bug!(
1034                         "could not cast from reference to array to pointer to array ({:?} to {:?})",
1035                         self.expr_ty,
1036                         array_ptr_type,
1037                     )
1038                     });
1039
1040                 // this will report a type mismatch if needed
1041                 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1042                 return Ok(CastKind::ArrayPtrCast);
1043             }
1044         }
1045
1046         Err(CastError::IllegalCast)
1047     }
1048
1049     fn check_addr_ptr_cast(
1050         &self,
1051         fcx: &FnCtxt<'a, 'tcx>,
1052         m_cast: TypeAndMut<'tcx>,
1053     ) -> Result<CastKind, CastError> {
1054         // ptr-addr cast. pointer must be thin.
1055         match fcx.pointer_kind(m_cast.ty, self.span)? {
1056             None => Err(CastError::UnknownCastPtrKind),
1057             Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1058             Some(PointerKind::VTable(_)) => Err(CastError::IntToFatCast(Some("a vtable"))),
1059             Some(PointerKind::Length) => Err(CastError::IntToFatCast(Some("a length"))),
1060             Some(
1061                 PointerKind::OfProjection(_)
1062                 | PointerKind::OfOpaque(_, _)
1063                 | PointerKind::OfParam(_),
1064             ) => Err(CastError::IntToFatCast(None)),
1065         }
1066     }
1067
1068     fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1069         match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1070             Ok(_) => Ok(()),
1071             Err(err) => Err(err),
1072         }
1073     }
1074
1075     fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1076         if let ty::Adt(d, _) = self.expr_ty.kind()
1077             && d.has_dtor(fcx.tcx)
1078         {
1079             fcx.tcx.struct_span_lint_hir(
1080                 lint::builtin::CENUM_IMPL_DROP_CAST,
1081                 self.expr.hir_id,
1082                 self.span,
1083                 DelayDm(|| format!(
1084                     "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
1085                     self.expr_ty, self.cast_ty
1086                 )),
1087                 |lint| {
1088                     lint
1089                 },
1090             );
1091         }
1092     }
1093
1094     fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1095         fcx.tcx.struct_span_lint_hir(
1096             lint::builtin::LOSSY_PROVENANCE_CASTS,
1097             self.expr.hir_id,
1098             self.span,
1099             DelayDm(|| format!(
1100                     "under strict provenance it is considered bad style to cast pointer `{}` to integer `{}`",
1101                     self.expr_ty, self.cast_ty
1102                 )),
1103             |lint| {
1104                 let msg = "use `.addr()` to obtain the address of a pointer";
1105
1106                 let expr_prec = self.expr.precedence().order();
1107                 let needs_parens = expr_prec < rustc_ast::util::parser::PREC_POSTFIX;
1108
1109                 let scalar_cast = match t_c {
1110                     ty::cast::IntTy::U(ty::UintTy::Usize) => String::new(),
1111                     _ => format!(" as {}", self.cast_ty),
1112                 };
1113
1114                 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1115
1116                 if needs_parens {
1117                     let suggestions = vec![
1118                         (self.expr_span.shrink_to_lo(), String::from("(")),
1119                         (cast_span, format!(").addr(){scalar_cast}")),
1120                     ];
1121
1122                     lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1123                 } else {
1124                     lint.span_suggestion(
1125                         cast_span,
1126                         msg,
1127                         format!(".addr(){scalar_cast}"),
1128                         Applicability::MaybeIncorrect,
1129                     );
1130                 }
1131
1132                 lint.help(
1133                     "if you can't comply with strict provenance and need to expose the pointer \
1134                     provenance you can use `.expose_addr()` instead"
1135                 );
1136
1137                 lint
1138             },
1139         );
1140     }
1141
1142     fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1143         fcx.tcx.struct_span_lint_hir(
1144             lint::builtin::FUZZY_PROVENANCE_CASTS,
1145             self.expr.hir_id,
1146             self.span,
1147             DelayDm(|| format!(
1148                 "strict provenance disallows casting integer `{}` to pointer `{}`",
1149                 self.expr_ty, self.cast_ty
1150             )),
1151             |lint| {
1152                 let msg = "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address";
1153                 let suggestions = vec![
1154                     (self.expr_span.shrink_to_lo(), String::from("(...).with_addr(")),
1155                     (self.expr_span.shrink_to_hi().to(self.cast_span), String::from(")")),
1156                 ];
1157
1158                 lint.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
1159                 lint.help(
1160                     "if you can't comply with strict provenance and don't have a pointer with \
1161                     the correct provenance you can use `std::ptr::from_exposed_addr()` instead"
1162                  );
1163
1164                 lint
1165             },
1166         );
1167     }
1168 }