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