rustc_hir_typeck/
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
31use rustc_ast::util::parser::ExprPrecedence;
32use rustc_data_structures::fx::FxHashSet;
33use rustc_errors::codes::*;
34use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
35use rustc_hir::def_id::DefId;
36use rustc_hir::{self as hir, ExprKind};
37use rustc_infer::infer::DefineOpaqueTypes;
38use rustc_macros::{TypeFoldable, TypeVisitable};
39use rustc_middle::mir::Mutability;
40use rustc_middle::ty::adjustment::AllowTwoPhase;
41use rustc_middle::ty::cast::{CastKind, CastTy};
42use rustc_middle::ty::error::TypeError;
43use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef, elaborate};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint;
46use rustc_span::{DUMMY_SP, Span, sym};
47use rustc_trait_selection::infer::InferCtxtExt;
48use tracing::{debug, instrument};
49
50use super::FnCtxt;
51use crate::{errors, type_error_struct};
52
53/// Reifies a cast check to be checked once we have full type information for
54/// a function context.
55#[derive(Debug)]
56pub(crate) struct CastCheck<'tcx> {
57    /// The expression whose value is being casted
58    expr: &'tcx hir::Expr<'tcx>,
59    /// The source type for the cast expression
60    expr_ty: Ty<'tcx>,
61    expr_span: Span,
62    /// The target type. That is, the type we are casting to.
63    cast_ty: Ty<'tcx>,
64    cast_span: Span,
65    span: Span,
66}
67
68/// The kind of pointer and associated metadata (thin, length or vtable) - we
69/// only allow casts between wide pointers if their metadata have the same
70/// kind.
71#[derive(Debug, Copy, Clone, PartialEq, Eq, TypeVisitable, TypeFoldable)]
72enum PointerKind<'tcx> {
73    /// No metadata attached, ie pointer to sized type or foreign type
74    Thin,
75    /// A trait object
76    VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
77    /// Slice
78    Length,
79    /// The unsize info of this projection or opaque type
80    OfAlias(ty::AliasTy<'tcx>),
81    /// The unsize info of this parameter
82    OfParam(ty::ParamTy),
83}
84
85impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
86    /// Returns the kind of unsize information of t, or None
87    /// if t is unknown.
88    fn pointer_kind(
89        &self,
90        t: Ty<'tcx>,
91        span: Span,
92    ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
93        debug!("pointer_kind({:?}, {:?})", t, span);
94
95        let t = self.resolve_vars_if_possible(t);
96        t.error_reported()?;
97
98        if self.type_is_sized_modulo_regions(self.param_env, t) {
99            return Ok(Some(PointerKind::Thin));
100        }
101
102        let t = self.try_structurally_resolve_type(span, t);
103
104        Ok(match *t.kind() {
105            ty::Slice(_) | ty::Str => Some(PointerKind::Length),
106            ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty)),
107            ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
108                None => Some(PointerKind::Thin),
109                Some(f) => {
110                    let field_ty = self.field_ty(span, f, args);
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            ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
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::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
125            ty::Param(p) => Some(PointerKind::OfParam(p)),
126            // Insufficient type information.
127            ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
128
129            ty::Bool
130            | ty::Char
131            | ty::Int(..)
132            | ty::Uint(..)
133            | ty::Float(_)
134            | ty::Array(..)
135            | ty::CoroutineWitness(..)
136            | ty::RawPtr(_, _)
137            | ty::Ref(..)
138            | ty::Pat(..)
139            | ty::FnDef(..)
140            | ty::FnPtr(..)
141            | ty::Closure(..)
142            | ty::CoroutineClosure(..)
143            | ty::Coroutine(..)
144            | ty::Adt(..)
145            | ty::Never
146            | ty::Dynamic(_, _, ty::DynStar)
147            | ty::Error(_) => {
148                let guar = self
149                    .dcx()
150                    .span_delayed_bug(span, format!("`{t:?}` should be sized but is not?"));
151                return Err(guar);
152            }
153        })
154    }
155}
156
157#[derive(Debug)]
158enum CastError<'tcx> {
159    ErrorGuaranteed(ErrorGuaranteed),
160
161    CastToBool,
162    CastToChar,
163    DifferingKinds {
164        src_kind: PointerKind<'tcx>,
165        dst_kind: PointerKind<'tcx>,
166    },
167    /// Cast of thin to wide raw ptr (e.g., `*const () as *const [u8]`).
168    SizedUnsizedCast,
169    IllegalCast,
170    NeedDeref,
171    NeedViaPtr,
172    NeedViaThinPtr,
173    NeedViaInt,
174    NonScalar,
175    UnknownExprPtrKind,
176    UnknownCastPtrKind,
177    /// Cast of int to (possibly) wide raw pointer.
178    ///
179    /// Argument is the specific name of the metadata in plain words, such as "a vtable"
180    /// or "a length". If this argument is None, then the metadata is unknown, for example,
181    /// when we're typechecking a type parameter with a ?Sized bound.
182    IntToWideCast(Option<&'static str>),
183    ForeignNonExhaustiveAdt,
184    PtrPtrAddingAutoTrait(Vec<DefId>),
185}
186
187impl From<ErrorGuaranteed> for CastError<'_> {
188    fn from(err: ErrorGuaranteed) -> Self {
189        CastError::ErrorGuaranteed(err)
190    }
191}
192
193fn make_invalid_casting_error<'a, 'tcx>(
194    span: Span,
195    expr_ty: Ty<'tcx>,
196    cast_ty: Ty<'tcx>,
197    fcx: &FnCtxt<'a, 'tcx>,
198) -> Diag<'a> {
199    type_error_struct!(
200        fcx.dcx(),
201        span,
202        expr_ty,
203        E0606,
204        "casting `{}` as `{}` is invalid",
205        fcx.ty_to_string(expr_ty),
206        fcx.ty_to_string(cast_ty)
207    )
208}
209
210/// If a cast from `from_ty` to `to_ty` is valid, returns a `Some` containing the kind
211/// of the cast.
212///
213/// This is a helper used from clippy.
214pub fn check_cast<'tcx>(
215    tcx: TyCtxt<'tcx>,
216    param_env: ty::ParamEnv<'tcx>,
217    e: &'tcx hir::Expr<'tcx>,
218    from_ty: Ty<'tcx>,
219    to_ty: Ty<'tcx>,
220) -> Option<CastKind> {
221    let hir_id = e.hir_id;
222    let local_def_id = hir_id.owner.def_id;
223
224    let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
225    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
226
227    if let Ok(check) = CastCheck::new(
228        &fn_ctxt, e, from_ty, to_ty,
229        // We won't show any errors to the user, so the span is irrelevant here.
230        DUMMY_SP, DUMMY_SP,
231    ) {
232        check.do_check(&fn_ctxt).ok()
233    } else {
234        None
235    }
236}
237
238impl<'a, 'tcx> CastCheck<'tcx> {
239    pub(crate) fn new(
240        fcx: &FnCtxt<'a, 'tcx>,
241        expr: &'tcx hir::Expr<'tcx>,
242        expr_ty: Ty<'tcx>,
243        cast_ty: Ty<'tcx>,
244        cast_span: Span,
245        span: Span,
246    ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
247        let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
248        let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
249
250        // For better error messages, check for some obviously unsized
251        // cases now. We do a more thorough check at the end, once
252        // inference is more completely known.
253        match cast_ty.kind() {
254            ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
255                Err(check.report_cast_to_unsized_type(fcx))
256            }
257            _ => Ok(check),
258        }
259    }
260
261    fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
262        match e {
263            CastError::ErrorGuaranteed(_) => {
264                // an error has already been reported
265            }
266            CastError::NeedDeref => {
267                let mut err =
268                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
269
270                if matches!(self.expr.kind, ExprKind::AddrOf(..)) {
271                    // get just the borrow part of the expression
272                    let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
273                    err.span_suggestion_verbose(
274                        span,
275                        "remove the unneeded borrow",
276                        "",
277                        Applicability::MachineApplicable,
278                    );
279                } else {
280                    err.span_suggestion_verbose(
281                        self.expr_span.shrink_to_lo(),
282                        "dereference the expression",
283                        "*",
284                        Applicability::MachineApplicable,
285                    );
286                }
287
288                err.emit();
289            }
290            CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
291                let mut err =
292                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
293                if self.cast_ty.is_integral() {
294                    err.help(format!("cast through {} first", match e {
295                        CastError::NeedViaPtr => "a raw pointer",
296                        CastError::NeedViaThinPtr => "a thin pointer",
297                        e => unreachable!("control flow means we should never encounter a {e:?}"),
298                    }));
299                }
300
301                self.try_suggest_collection_to_bool(fcx, &mut err);
302
303                err.emit();
304            }
305            CastError::NeedViaInt => {
306                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
307                    .with_help("cast through an integer first")
308                    .emit();
309            }
310            CastError::IllegalCast => {
311                make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
312            }
313            CastError::DifferingKinds { src_kind, dst_kind } => {
314                let mut err =
315                    make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
316
317                match (src_kind, dst_kind) {
318                    (PointerKind::VTable(_), PointerKind::VTable(_)) => {
319                        err.note("the trait objects may have different vtables");
320                    }
321                    (
322                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
323                        PointerKind::OfParam(_)
324                        | PointerKind::OfAlias(_)
325                        | PointerKind::VTable(_)
326                        | PointerKind::Length,
327                    )
328                    | (
329                        PointerKind::VTable(_) | PointerKind::Length,
330                        PointerKind::OfParam(_) | PointerKind::OfAlias(_),
331                    ) => {
332                        err.note("the pointers may have different metadata");
333                    }
334                    (PointerKind::VTable(_), PointerKind::Length)
335                    | (PointerKind::Length, PointerKind::VTable(_)) => {
336                        err.note("the pointers have different metadata");
337                    }
338                    (
339                        PointerKind::Thin,
340                        PointerKind::Thin
341                        | PointerKind::VTable(_)
342                        | PointerKind::Length
343                        | PointerKind::OfParam(_)
344                        | PointerKind::OfAlias(_),
345                    )
346                    | (
347                        PointerKind::VTable(_)
348                        | PointerKind::Length
349                        | PointerKind::OfParam(_)
350                        | PointerKind::OfAlias(_),
351                        PointerKind::Thin,
352                    )
353                    | (PointerKind::Length, PointerKind::Length) => {
354                        span_bug!(self.span, "unexpected cast error: {e:?}")
355                    }
356                }
357
358                err.emit();
359            }
360            CastError::CastToBool => {
361                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
362                let help = if self.expr_ty.is_numeric() {
363                    errors::CannotCastToBoolHelp::Numeric(
364                        self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
365                    )
366                } else {
367                    errors::CannotCastToBoolHelp::Unsupported(self.span)
368                };
369                fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help });
370            }
371            CastError::CastToChar => {
372                let mut err = type_error_struct!(
373                    fcx.dcx(),
374                    self.span,
375                    self.expr_ty,
376                    E0604,
377                    "only `u8` can be cast as `char`, not `{}`",
378                    self.expr_ty
379                );
380                err.span_label(self.span, "invalid cast");
381                if self.expr_ty.is_numeric() {
382                    if self.expr_ty == fcx.tcx.types.u32 {
383                        match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
384                            Ok(snippet) => err.span_suggestion(
385                                self.span,
386                                "try `char::from_u32` instead",
387                                format!("char::from_u32({snippet})"),
388                                Applicability::MachineApplicable,
389                            ),
390
391                            Err(_) => err.span_help(self.span, "try `char::from_u32` instead"),
392                        };
393                    } else if self.expr_ty == fcx.tcx.types.i8 {
394                        err.span_help(self.span, "try casting from `u8` instead");
395                    } else {
396                        err.span_help(self.span, "try `char::from_u32` instead (via a `u32`)");
397                    };
398                }
399                err.emit();
400            }
401            CastError::NonScalar => {
402                let mut err = type_error_struct!(
403                    fcx.dcx(),
404                    self.span,
405                    self.expr_ty,
406                    E0605,
407                    "non-primitive cast: `{}` as `{}`",
408                    self.expr_ty,
409                    fcx.ty_to_string(self.cast_ty)
410                );
411
412                if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
413                    && matches!(self.expr.kind, ExprKind::AddrOf(..))
414                {
415                    err.note(format!(
416                        "casting reference expression `{}` because `&` binds tighter than `as`",
417                        snippet
418                    ));
419                }
420
421                let mut sugg = None;
422                let mut sugg_mutref = false;
423                if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
424                    if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
425                        && fcx.may_coerce(
426                            Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
427                            self.cast_ty,
428                        )
429                    {
430                        sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
431                    } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
432                        && expr_mutbl == Mutability::Not
433                        && mutbl == Mutability::Mut
434                        && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
435                    {
436                        sugg_mutref = true;
437                    }
438
439                    if !sugg_mutref
440                        && sugg == None
441                        && fcx.may_coerce(
442                            Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
443                            self.cast_ty,
444                        )
445                    {
446                        sugg = Some((format!("&{}", mutbl.prefix_str()), false));
447                    }
448                } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
449                    && fcx.may_coerce(
450                        Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
451                        self.cast_ty,
452                    )
453                {
454                    sugg = Some((format!("&{}", mutbl.prefix_str()), false));
455                }
456                if sugg_mutref {
457                    err.span_label(self.span, "invalid cast");
458                    err.span_note(self.expr_span, "this reference is immutable");
459                    err.span_note(self.cast_span, "trying to cast to a mutable reference type");
460                } else if let Some((sugg, remove_cast)) = sugg {
461                    err.span_label(self.span, "invalid cast");
462
463                    let has_parens = fcx
464                        .tcx
465                        .sess
466                        .source_map()
467                        .span_to_snippet(self.expr_span)
468                        .is_ok_and(|snip| snip.starts_with('('));
469
470                    // Very crude check to see whether the expression must be wrapped
471                    // in parentheses for the suggestion to work (issue #89497).
472                    // Can/should be extended in the future.
473                    let needs_parens =
474                        !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
475
476                    let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
477                    if needs_parens {
478                        suggestion[0].1 += "(";
479                        suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
480                    }
481                    if remove_cast {
482                        suggestion.push((
483                            self.expr_span.shrink_to_hi().to(self.cast_span),
484                            String::new(),
485                        ));
486                    }
487
488                    err.multipart_suggestion_verbose(
489                        "consider borrowing the value",
490                        suggestion,
491                        Applicability::MachineApplicable,
492                    );
493                } else if !matches!(
494                    self.cast_ty.kind(),
495                    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
496                ) {
497                    let mut label = true;
498                    // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
499                    if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
500                        && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
501                    {
502                        let ty = fcx.resolve_vars_if_possible(self.cast_ty);
503                        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
504                        if fcx
505                            .infcx
506                            .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
507                            .must_apply_modulo_regions()
508                        {
509                            label = false;
510                            if let ty::Adt(def, args) = self.cast_ty.kind() {
511                                err.span_suggestion_verbose(
512                                    self.span,
513                                    "consider using the `From` trait instead",
514                                    format!(
515                                        "{}::from({})",
516                                        fcx.tcx.value_path_str_with_args(def.did(), args),
517                                        snippet
518                                    ),
519                                    Applicability::MaybeIncorrect,
520                                );
521                            } else {
522                                err.span_suggestion(
523                                    self.span,
524                                    "consider using the `From` trait instead",
525                                    format!("{}::from({})", self.cast_ty, snippet),
526                                    Applicability::MaybeIncorrect,
527                                );
528                            };
529                        }
530                    }
531
532                    let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
533                        && adt.is_enum()
534                        && self.cast_ty.is_numeric()
535                    {
536                        (
537                            "an `as` expression can be used to convert enum types to numeric \
538                             types only if the enum type is unit-only or field-less",
539                            Some(
540                                "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
541                            ),
542                        )
543                    } else {
544                        (
545                            "an `as` expression can only be used to convert between primitive \
546                             types or to coerce to a specific trait object",
547                            None,
548                        )
549                    };
550
551                    if label {
552                        err.span_label(self.span, msg);
553                    } else {
554                        err.note(msg);
555                    }
556
557                    if let Some(note) = note {
558                        err.note(note);
559                    }
560                } else {
561                    err.span_label(self.span, "invalid cast");
562                }
563
564                fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
565                self.try_suggest_collection_to_bool(fcx, &mut err);
566
567                err.emit();
568            }
569            CastError::SizedUnsizedCast => {
570                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
571                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
572                fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
573                    span: self.span,
574                    expr_ty,
575                    cast_ty,
576                    teach: fcx.tcx.sess.teach(E0607),
577                });
578            }
579            CastError::IntToWideCast(known_metadata) => {
580                let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
581                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
582                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
583                let metadata = known_metadata.unwrap_or("type-specific metadata");
584                let known_wide = known_metadata.is_some();
585                let span = self.cast_span;
586                fcx.dcx().emit_err(errors::IntToWide {
587                    span,
588                    metadata,
589                    expr_ty,
590                    cast_ty,
591                    expr_if_nightly,
592                    known_wide,
593                });
594            }
595            CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
596                let unknown_cast_to = match e {
597                    CastError::UnknownCastPtrKind => true,
598                    CastError::UnknownExprPtrKind => false,
599                    e => unreachable!("control flow means we should never encounter a {e:?}"),
600                };
601                let (span, sub) = if unknown_cast_to {
602                    (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
603                } else {
604                    (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
605                };
606                fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
607            }
608            CastError::ForeignNonExhaustiveAdt => {
609                make_invalid_casting_error(
610                    self.span,
611                    self.expr_ty,
612                    self.cast_ty,
613                    fcx,
614                )
615                .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
616                .emit();
617            }
618            CastError::PtrPtrAddingAutoTrait(added) => {
619                fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
620                    span: self.span,
621                    traits_len: added.len(),
622                    traits: {
623                        let mut traits: Vec<_> = added
624                            .into_iter()
625                            .map(|trait_did| fcx.tcx.def_path_str(trait_did))
626                            .collect();
627
628                        traits.sort();
629                        traits.into()
630                    },
631                });
632            }
633        }
634    }
635
636    fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
637        if let Err(err) = self.cast_ty.error_reported() {
638            return err;
639        }
640        if let Err(err) = self.expr_ty.error_reported() {
641            return err;
642        }
643
644        let tstr = fcx.ty_to_string(self.cast_ty);
645        let mut err = type_error_struct!(
646            fcx.dcx(),
647            self.span,
648            self.expr_ty,
649            E0620,
650            "cast to unsized type: `{}` as `{}`",
651            fcx.resolve_vars_if_possible(self.expr_ty),
652            tstr
653        );
654        match self.expr_ty.kind() {
655            ty::Ref(_, _, mt) => {
656                let mtstr = mt.prefix_str();
657                match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
658                    Ok(s) => {
659                        err.span_suggestion(
660                            self.cast_span,
661                            "try casting to a reference instead",
662                            format!("&{mtstr}{s}"),
663                            Applicability::MachineApplicable,
664                        );
665                    }
666                    Err(_) => {
667                        let msg = format!("did you mean `&{mtstr}{tstr}`?");
668                        err.span_help(self.cast_span, msg);
669                    }
670                }
671            }
672            ty::Adt(def, ..) if def.is_box() => {
673                match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
674                    Ok(s) => {
675                        err.span_suggestion(
676                            self.cast_span,
677                            "you can cast to a `Box` instead",
678                            format!("Box<{s}>"),
679                            Applicability::MachineApplicable,
680                        );
681                    }
682                    Err(_) => {
683                        err.span_help(
684                            self.cast_span,
685                            format!("you might have meant `Box<{tstr}>`"),
686                        );
687                    }
688                }
689            }
690            _ => {
691                err.span_help(self.expr_span, "consider using a box or reference as appropriate");
692            }
693        }
694        err.emit()
695    }
696
697    fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
698        let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
699            (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
700        } else {
701            (false, lint::builtin::TRIVIAL_CASTS)
702        };
703        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
704        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
705        fcx.tcx.emit_node_span_lint(
706            lint,
707            self.expr.hir_id,
708            self.span,
709            errors::TrivialCast { numeric, expr_ty, cast_ty },
710        );
711    }
712
713    #[instrument(skip(fcx), level = "debug")]
714    pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
715        self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
716        self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
717
718        debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
719
720        if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
721            && !self.cast_ty.has_infer_types()
722        {
723            self.report_cast_to_unsized_type(fcx);
724        } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
725            // No sense in giving duplicate error messages
726        } else {
727            match self.try_coercion_cast(fcx) {
728                Ok(()) => {
729                    if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
730                        // When casting a raw pointer to another raw pointer, we cannot convert the cast into
731                        // a coercion because the pointee types might only differ in regions, which HIR typeck
732                        // cannot distinguish. This would cause us to erroneously discard a cast which will
733                        // lead to a borrowck error like #113257.
734                        // We still did a coercion above to unify inference variables for `ptr as _` casts.
735                        // This does cause us to miss some trivial casts in the trivial cast lint.
736                        debug!(" -> PointerCast");
737                    } else {
738                        self.trivial_cast_lint(fcx);
739                        debug!(" -> CoercionCast");
740                        fcx.typeck_results
741                            .borrow_mut()
742                            .set_coercion_cast(self.expr.hir_id.local_id);
743                    }
744                }
745                Err(_) => {
746                    match self.do_check(fcx) {
747                        Ok(k) => {
748                            debug!(" -> {:?}", k);
749                        }
750                        Err(e) => self.report_cast_error(fcx, e),
751                    };
752                }
753            };
754        }
755    }
756    /// Checks a cast, and report an error if one exists. In some cases, this
757    /// can return Ok and create type errors in the fcx rather than returning
758    /// directly. coercion-cast is handled in check instead of here.
759    fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
760        use rustc_middle::ty::cast::CastTy::*;
761        use rustc_middle::ty::cast::IntTy::*;
762
763        if self.cast_ty.is_dyn_star() {
764            // This coercion will fail if the feature is not enabled, OR
765            // if the coercion is (currently) illegal (e.g. `dyn* Foo + Send`
766            // to `dyn* Foo`). Report "casting is invalid" rather than
767            // "non-primitive cast".
768            return Err(CastError::IllegalCast);
769        }
770
771        let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
772        {
773            (Some(t_from), Some(t_cast)) => (t_from, t_cast),
774            // Function item types may need to be reified before casts.
775            (None, Some(t_cast)) => {
776                match *self.expr_ty.kind() {
777                    ty::FnDef(..) => {
778                        // Attempt a coercion to a fn pointer type.
779                        let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
780                        let res = fcx.coerce(
781                            self.expr,
782                            self.expr_ty,
783                            Ty::new_fn_ptr(fcx.tcx, f),
784                            AllowTwoPhase::No,
785                            None,
786                        );
787                        if let Err(TypeError::IntrinsicCast) = res {
788                            return Err(CastError::IllegalCast);
789                        }
790                        if res.is_err() {
791                            return Err(CastError::NonScalar);
792                        }
793                        (FnPtr, t_cast)
794                    }
795                    // Special case some errors for references, and check for
796                    // array-ptr-casts. `Ref` is not a CastTy because the cast
797                    // is split into a coercion to a pointer type, followed by
798                    // a cast.
799                    ty::Ref(_, inner_ty, mutbl) => {
800                        return match t_cast {
801                            Int(_) | Float => match *inner_ty.kind() {
802                                ty::Int(_)
803                                | ty::Uint(_)
804                                | ty::Float(_)
805                                | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
806                                    Err(CastError::NeedDeref)
807                                }
808                                _ => Err(CastError::NeedViaPtr),
809                            },
810                            // array-ptr-cast
811                            Ptr(mt) => {
812                                if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
813                                    return Err(CastError::IllegalCast);
814                                }
815                                self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
816                            }
817                            _ => Err(CastError::NonScalar),
818                        };
819                    }
820                    _ => return Err(CastError::NonScalar),
821                }
822            }
823            _ => return Err(CastError::NonScalar),
824        };
825        if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
826            && !adt_def.did().is_local()
827            && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
828        {
829            return Err(CastError::ForeignNonExhaustiveAdt);
830        }
831        match (t_from, t_cast) {
832            // These types have invariants! can't cast into them.
833            (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
834
835            // * -> Bool
836            (_, Int(Bool)) => Err(CastError::CastToBool),
837
838            // * -> Char
839            (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
840            (_, Int(Char)) => Err(CastError::CastToChar),
841
842            // prim -> float,ptr
843            (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
844
845            (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
846                Err(CastError::IllegalCast)
847            }
848
849            // ptr -> ptr
850            (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
851
852            // ptr-addr-cast
853            (Ptr(m_expr), Int(t_c)) => {
854                self.lossy_provenance_ptr2int_lint(fcx, t_c);
855                self.check_ptr_addr_cast(fcx, m_expr)
856            }
857            (FnPtr, Int(_)) => {
858                // FIXME(#95489): there should eventually be a lint for these casts
859                Ok(CastKind::FnPtrAddrCast)
860            }
861            // addr-ptr-cast
862            (Int(_), Ptr(mt)) => {
863                self.fuzzy_provenance_int2ptr_lint(fcx);
864                self.check_addr_ptr_cast(fcx, mt)
865            }
866            // fn-ptr-cast
867            (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
868
869            // prim -> prim
870            (Int(CEnum), Int(_)) => {
871                self.err_if_cenum_impl_drop(fcx);
872                Ok(CastKind::EnumCast)
873            }
874            (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
875
876            (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
877        }
878    }
879
880    fn check_ptr_ptr_cast(
881        &self,
882        fcx: &FnCtxt<'a, 'tcx>,
883        m_src: ty::TypeAndMut<'tcx>,
884        m_dst: ty::TypeAndMut<'tcx>,
885    ) -> Result<CastKind, CastError<'tcx>> {
886        debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
887        // ptr-ptr cast. metadata must match.
888
889        let src_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_src.ty, self.span)?);
890        let dst_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
891
892        // We can't cast if target pointer kind is unknown
893        let Some(dst_kind) = dst_kind else {
894            return Err(CastError::UnknownCastPtrKind);
895        };
896
897        // Cast to thin pointer is OK
898        if dst_kind == PointerKind::Thin {
899            return Ok(CastKind::PtrPtrCast);
900        }
901
902        // We can't cast to wide pointer if source pointer kind is unknown
903        let Some(src_kind) = src_kind else {
904            return Err(CastError::UnknownCastPtrKind);
905        };
906
907        match (src_kind, dst_kind) {
908            // thin -> fat? report invalid cast (don't complain about vtable kinds)
909            (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
910
911            // trait object -> trait object? need to do additional checks
912            (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
913                match (src_tty.principal(), dst_tty.principal()) {
914                    // A<dyn Src<...> + SrcAuto> -> B<dyn Dst<...> + DstAuto>. need to make sure
915                    // - `Src` and `Dst` traits are the same
916                    // - traits have the same generic arguments
917                    // - projections are the same
918                    // - `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`
919                    //
920                    // Note that trait upcasting goes through a different mechanism (`coerce_unsized`)
921                    // and is unaffected by this check.
922                    (Some(src_principal), Some(_)) => {
923                        let tcx = fcx.tcx;
924
925                        // We need to reconstruct trait object types.
926                        // `m_src` and `m_dst` won't work for us here because they will potentially
927                        // contain wrappers, which we do not care about.
928                        //
929                        // e.g. we want to allow `dyn T -> (dyn T,)`, etc.
930                        //
931                        // We also need to skip auto traits to emit an FCW and not an error.
932                        let src_obj = Ty::new_dynamic(
933                            tcx,
934                            tcx.mk_poly_existential_predicates(
935                                &src_tty.without_auto_traits().collect::<Vec<_>>(),
936                            ),
937                            tcx.lifetimes.re_erased,
938                            ty::Dyn,
939                        );
940                        let dst_obj = Ty::new_dynamic(
941                            tcx,
942                            tcx.mk_poly_existential_predicates(
943                                &dst_tty.without_auto_traits().collect::<Vec<_>>(),
944                            ),
945                            tcx.lifetimes.re_erased,
946                            ty::Dyn,
947                        );
948
949                        // `dyn Src = dyn Dst`, this checks for matching traits/generics/projections
950                        // This is `fcx.demand_eqtype`, but inlined to give a better error.
951                        let cause = fcx.misc(self.span);
952                        if fcx
953                            .at(&cause, fcx.param_env)
954                            .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
955                            .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
956                            .is_err()
957                        {
958                            return Err(CastError::DifferingKinds { src_kind, dst_kind });
959                        }
960
961                        // Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`.
962                        // Emit an FCW otherwise.
963                        let src_auto: FxHashSet<_> = src_tty
964                            .auto_traits()
965                            .chain(
966                                elaborate::supertrait_def_ids(tcx, src_principal.def_id())
967                                    .filter(|def_id| tcx.trait_is_auto(*def_id)),
968                            )
969                            .collect();
970
971                        let added = dst_tty
972                            .auto_traits()
973                            .filter(|trait_did| !src_auto.contains(trait_did))
974                            .collect::<Vec<_>>();
975
976                        if !added.is_empty() {
977                            return Err(CastError::PtrPtrAddingAutoTrait(added));
978                        }
979
980                        Ok(CastKind::PtrPtrCast)
981                    }
982
983                    // dyn Auto -> dyn Auto'? ok.
984                    (None, None) => Ok(CastKind::PtrPtrCast),
985
986                    // dyn Trait -> dyn Auto? not ok (for now).
987                    //
988                    // Although dropping the principal is already allowed for unsizing coercions
989                    // (e.g. `*const (dyn Trait + Auto)` to `*const dyn Auto`), dropping it is
990                    // currently **NOT** allowed for (non-coercion) ptr-to-ptr casts (e.g
991                    // `*const Foo` to `*const Bar` where `Foo` has a `dyn Trait + Auto` tail
992                    // and `Bar` has a `dyn Auto` tail), because the underlying MIR operations
993                    // currently work very differently:
994                    //
995                    // * A MIR unsizing coercion on raw pointers to trait objects (`*const dyn Src`
996                    //   to `*const dyn Dst`) is currently equivalent to downcasting the source to
997                    //   the concrete sized type that it was originally unsized from first (via a
998                    //   ptr-to-ptr cast from `*const Src` to `*const T` with `T: Sized`) and then
999                    //   unsizing this thin pointer to the target type (unsizing `*const T` to
1000                    //   `*const Dst`). In particular, this means that the pointer's metadata
1001                    //   (vtable) will semantically change, e.g. for const eval and miri, even
1002                    //   though the vtables will always be merged for codegen.
1003                    //
1004                    // * A MIR ptr-to-ptr cast is currently equivalent to a transmute and does not
1005                    //   change the pointer metadata (vtable) at all.
1006                    //
1007                    // In addition to this potentially surprising difference between coercion and
1008                    // non-coercion casts, casting away the principal with a MIR ptr-to-ptr cast
1009                    // is currently considered undefined behavior:
1010                    //
1011                    // As a validity invariant of pointers to trait objects, we currently require
1012                    // that the principal of the vtable in the pointer metadata exactly matches
1013                    // the principal of the pointee type, where "no principal" is also considered
1014                    // a kind of principal.
1015                    (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1016
1017                    // dyn Auto -> dyn Trait? not ok.
1018                    (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1019                }
1020            }
1021
1022            // fat -> fat? metadata kinds must match
1023            (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1024
1025            (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1026        }
1027    }
1028
1029    fn check_fptr_ptr_cast(
1030        &self,
1031        fcx: &FnCtxt<'a, 'tcx>,
1032        m_cast: ty::TypeAndMut<'tcx>,
1033    ) -> Result<CastKind, CastError<'tcx>> {
1034        // fptr-ptr cast. must be to thin ptr
1035
1036        match fcx.pointer_kind(m_cast.ty, self.span)? {
1037            None => Err(CastError::UnknownCastPtrKind),
1038            Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1039            _ => Err(CastError::IllegalCast),
1040        }
1041    }
1042
1043    fn check_ptr_addr_cast(
1044        &self,
1045        fcx: &FnCtxt<'a, 'tcx>,
1046        m_expr: ty::TypeAndMut<'tcx>,
1047    ) -> Result<CastKind, CastError<'tcx>> {
1048        // ptr-addr cast. must be from thin ptr
1049
1050        match fcx.pointer_kind(m_expr.ty, self.span)? {
1051            None => Err(CastError::UnknownExprPtrKind),
1052            Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1053            _ => Err(CastError::NeedViaThinPtr),
1054        }
1055    }
1056
1057    fn check_ref_cast(
1058        &self,
1059        fcx: &FnCtxt<'a, 'tcx>,
1060        mut m_expr: ty::TypeAndMut<'tcx>,
1061        mut m_cast: ty::TypeAndMut<'tcx>,
1062    ) -> Result<CastKind, CastError<'tcx>> {
1063        // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1064        m_expr.ty = fcx.try_structurally_resolve_type(self.expr_span, m_expr.ty);
1065        m_cast.ty = fcx.try_structurally_resolve_type(self.cast_span, m_cast.ty);
1066
1067        if m_expr.mutbl >= m_cast.mutbl
1068            && let ty::Array(ety, _) = m_expr.ty.kind()
1069            && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1070        {
1071            // Due to historical reasons we allow directly casting references of
1072            // arrays into raw pointers of their element type.
1073
1074            // Coerce to a raw pointer so that we generate RawPtr in MIR.
1075            let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1076            fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1077                .unwrap_or_else(|_| {
1078                    bug!(
1079                        "could not cast from reference to array to pointer to array ({:?} to {:?})",
1080                        self.expr_ty,
1081                        array_ptr_type,
1082                    )
1083                });
1084
1085            // this will report a type mismatch if needed
1086            fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1087            return Ok(CastKind::ArrayPtrCast);
1088        }
1089
1090        Err(CastError::IllegalCast)
1091    }
1092
1093    fn check_addr_ptr_cast(
1094        &self,
1095        fcx: &FnCtxt<'a, 'tcx>,
1096        m_cast: TypeAndMut<'tcx>,
1097    ) -> Result<CastKind, CastError<'tcx>> {
1098        // ptr-addr cast. pointer must be thin.
1099        match fcx.pointer_kind(m_cast.ty, self.span)? {
1100            None => Err(CastError::UnknownCastPtrKind),
1101            Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1102            Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1103            Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1104            Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1105                Err(CastError::IntToWideCast(None))
1106            }
1107        }
1108    }
1109
1110    fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1111        match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1112            Ok(_) => Ok(()),
1113            Err(err) => Err(err),
1114        }
1115    }
1116
1117    fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1118        if let ty::Adt(d, _) = self.expr_ty.kind()
1119            && d.has_dtor(fcx.tcx)
1120        {
1121            let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1122            let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1123
1124            fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1125        }
1126    }
1127
1128    fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1129        let expr_prec = self.expr.precedence();
1130        let needs_parens = expr_prec < ExprPrecedence::Unambiguous;
1131
1132        let needs_cast = !matches!(t_c, ty::cast::IntTy::U(ty::UintTy::Usize));
1133        let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1134        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1135        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1136        let expr_span = self.expr_span.shrink_to_lo();
1137        let sugg = match (needs_parens, needs_cast) {
1138            (true, true) => errors::LossyProvenancePtr2IntSuggestion::NeedsParensCast {
1139                expr_span,
1140                cast_span,
1141                cast_ty,
1142            },
1143            (true, false) => {
1144                errors::LossyProvenancePtr2IntSuggestion::NeedsParens { expr_span, cast_span }
1145            }
1146            (false, true) => {
1147                errors::LossyProvenancePtr2IntSuggestion::NeedsCast { cast_span, cast_ty }
1148            }
1149            (false, false) => errors::LossyProvenancePtr2IntSuggestion::Other { cast_span },
1150        };
1151
1152        let lint = errors::LossyProvenancePtr2Int { expr_ty, cast_ty, sugg };
1153        fcx.tcx.emit_node_span_lint(
1154            lint::builtin::LOSSY_PROVENANCE_CASTS,
1155            self.expr.hir_id,
1156            self.span,
1157            lint,
1158        );
1159    }
1160
1161    fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1162        let sugg = errors::LossyProvenanceInt2PtrSuggestion {
1163            lo: self.expr_span.shrink_to_lo(),
1164            hi: self.expr_span.shrink_to_hi().to(self.cast_span),
1165        };
1166        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1167        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1168        let lint = errors::LossyProvenanceInt2Ptr { expr_ty, cast_ty, sugg };
1169        fcx.tcx.emit_node_span_lint(
1170            lint::builtin::FUZZY_PROVENANCE_CASTS,
1171            self.expr.hir_id,
1172            self.span,
1173            lint,
1174        );
1175    }
1176
1177    /// Attempt to suggest using `.is_empty` when trying to cast from a
1178    /// collection type to a boolean.
1179    fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1180        if self.cast_ty.is_bool() {
1181            let derefed = fcx
1182                .autoderef(self.expr_span, self.expr_ty)
1183                .silence_errors()
1184                .find(|t| matches!(t.0.kind(), ty::Str | ty::Slice(..)));
1185
1186            if let Some((deref_ty, _)) = derefed {
1187                // Give a note about what the expr derefs to.
1188                if deref_ty != self.expr_ty.peel_refs() {
1189                    err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1190                }
1191
1192                // Create a multipart suggestion: add `!` and `.is_empty()` in
1193                // place of the cast.
1194                err.subdiagnostic(errors::UseIsEmpty {
1195                    lo: self.expr_span.shrink_to_lo(),
1196                    hi: self.span.with_lo(self.expr_span.hi()),
1197                    expr_ty: self.expr_ty,
1198                });
1199            }
1200        }
1201    }
1202}