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                let mut sugg = None;
412                let mut sugg_mutref = false;
413                if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
414                    if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
415                        && fcx.may_coerce(
416                            Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
417                            self.cast_ty,
418                        )
419                    {
420                        sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
421                    } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
422                        && expr_mutbl == Mutability::Not
423                        && mutbl == Mutability::Mut
424                        && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
425                    {
426                        sugg_mutref = true;
427                    }
428
429                    if !sugg_mutref
430                        && sugg == None
431                        && fcx.may_coerce(
432                            Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
433                            self.cast_ty,
434                        )
435                    {
436                        sugg = Some((format!("&{}", mutbl.prefix_str()), false));
437                    }
438                } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
439                    && fcx.may_coerce(
440                        Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
441                        self.cast_ty,
442                    )
443                {
444                    sugg = Some((format!("&{}", mutbl.prefix_str()), false));
445                }
446                if sugg_mutref {
447                    err.span_label(self.span, "invalid cast");
448                    err.span_note(self.expr_span, "this reference is immutable");
449                    err.span_note(self.cast_span, "trying to cast to a mutable reference type");
450                } else if let Some((sugg, remove_cast)) = sugg {
451                    err.span_label(self.span, "invalid cast");
452
453                    let has_parens = fcx
454                        .tcx
455                        .sess
456                        .source_map()
457                        .span_to_snippet(self.expr_span)
458                        .is_ok_and(|snip| snip.starts_with('('));
459
460                    // Very crude check to see whether the expression must be wrapped
461                    // in parentheses for the suggestion to work (issue #89497).
462                    // Can/should be extended in the future.
463                    let needs_parens =
464                        !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
465
466                    let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
467                    if needs_parens {
468                        suggestion[0].1 += "(";
469                        suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
470                    }
471                    if remove_cast {
472                        suggestion.push((
473                            self.expr_span.shrink_to_hi().to(self.cast_span),
474                            String::new(),
475                        ));
476                    }
477
478                    err.multipart_suggestion_verbose(
479                        "consider borrowing the value",
480                        suggestion,
481                        Applicability::MachineApplicable,
482                    );
483                } else if !matches!(
484                    self.cast_ty.kind(),
485                    ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
486                ) {
487                    let mut label = true;
488                    // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
489                    if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
490                        && let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From)
491                    {
492                        let ty = fcx.resolve_vars_if_possible(self.cast_ty);
493                        // Erase regions to avoid panic in `prove_value` when calling
494                        // `type_implements_trait`.
495                        let ty = fcx.tcx.erase_regions(ty);
496                        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
497                        let expr_ty = fcx.tcx.erase_regions(expr_ty);
498                        if fcx
499                            .infcx
500                            .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
501                            .must_apply_modulo_regions()
502                        {
503                            label = false;
504                            if let ty::Adt(def, args) = self.cast_ty.kind() {
505                                err.span_suggestion_verbose(
506                                    self.span,
507                                    "consider using the `From` trait instead",
508                                    format!(
509                                        "{}::from({})",
510                                        fcx.tcx.value_path_str_with_args(def.did(), args),
511                                        snippet
512                                    ),
513                                    Applicability::MaybeIncorrect,
514                                );
515                            } else {
516                                err.span_suggestion(
517                                    self.span,
518                                    "consider using the `From` trait instead",
519                                    format!("{}::from({})", self.cast_ty, snippet),
520                                    Applicability::MaybeIncorrect,
521                                );
522                            };
523                        }
524                    }
525
526                    let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
527                        && adt.is_enum()
528                        && self.cast_ty.is_numeric()
529                    {
530                        (
531                            "an `as` expression can be used to convert enum types to numeric \
532                             types only if the enum type is unit-only or field-less",
533                            Some(
534                                "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
535                            ),
536                        )
537                    } else {
538                        (
539                            "an `as` expression can only be used to convert between primitive \
540                             types or to coerce to a specific trait object",
541                            None,
542                        )
543                    };
544
545                    if label {
546                        err.span_label(self.span, msg);
547                    } else {
548                        err.note(msg);
549                    }
550
551                    if let Some(note) = note {
552                        err.note(note);
553                    }
554                } else {
555                    err.span_label(self.span, "invalid cast");
556                }
557
558                fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
559                self.try_suggest_collection_to_bool(fcx, &mut err);
560
561                err.emit();
562            }
563            CastError::SizedUnsizedCast => {
564                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
565                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
566                fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
567                    span: self.span,
568                    expr_ty,
569                    cast_ty,
570                    teach: fcx.tcx.sess.teach(E0607),
571                });
572            }
573            CastError::IntToWideCast(known_metadata) => {
574                let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
575                let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
576                let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
577                let metadata = known_metadata.unwrap_or("type-specific metadata");
578                let known_wide = known_metadata.is_some();
579                let span = self.cast_span;
580                fcx.dcx().emit_err(errors::IntToWide {
581                    span,
582                    metadata,
583                    expr_ty,
584                    cast_ty,
585                    expr_if_nightly,
586                    known_wide,
587                });
588            }
589            CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
590                let unknown_cast_to = match e {
591                    CastError::UnknownCastPtrKind => true,
592                    CastError::UnknownExprPtrKind => false,
593                    e => unreachable!("control flow means we should never encounter a {e:?}"),
594                };
595                let (span, sub) = if unknown_cast_to {
596                    (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
597                } else {
598                    (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
599                };
600                fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
601            }
602            CastError::ForeignNonExhaustiveAdt => {
603                make_invalid_casting_error(
604                    self.span,
605                    self.expr_ty,
606                    self.cast_ty,
607                    fcx,
608                )
609                .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
610                .emit();
611            }
612            CastError::PtrPtrAddingAutoTrait(added) => {
613                fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
614                    span: self.span,
615                    traits_len: added.len(),
616                    traits: {
617                        let mut traits: Vec<_> = added
618                            .into_iter()
619                            .map(|trait_did| fcx.tcx.def_path_str(trait_did))
620                            .collect();
621
622                        traits.sort();
623                        traits.into()
624                    },
625                });
626            }
627        }
628    }
629
630    fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
631        if let Err(err) = self.cast_ty.error_reported() {
632            return err;
633        }
634        if let Err(err) = self.expr_ty.error_reported() {
635            return err;
636        }
637
638        let tstr = fcx.ty_to_string(self.cast_ty);
639        let mut err = type_error_struct!(
640            fcx.dcx(),
641            self.span,
642            self.expr_ty,
643            E0620,
644            "cast to unsized type: `{}` as `{}`",
645            fcx.resolve_vars_if_possible(self.expr_ty),
646            tstr
647        );
648        match self.expr_ty.kind() {
649            ty::Ref(_, _, mt) => {
650                let mtstr = mt.prefix_str();
651                match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
652                    Ok(s) => {
653                        err.span_suggestion(
654                            self.cast_span,
655                            "try casting to a reference instead",
656                            format!("&{mtstr}{s}"),
657                            Applicability::MachineApplicable,
658                        );
659                    }
660                    Err(_) => {
661                        let msg = format!("did you mean `&{mtstr}{tstr}`?");
662                        err.span_help(self.cast_span, msg);
663                    }
664                }
665            }
666            ty::Adt(def, ..) if def.is_box() => {
667                match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
668                    Ok(s) => {
669                        err.span_suggestion(
670                            self.cast_span,
671                            "you can cast to a `Box` instead",
672                            format!("Box<{s}>"),
673                            Applicability::MachineApplicable,
674                        );
675                    }
676                    Err(_) => {
677                        err.span_help(
678                            self.cast_span,
679                            format!("you might have meant `Box<{tstr}>`"),
680                        );
681                    }
682                }
683            }
684            _ => {
685                err.span_help(self.expr_span, "consider using a box or reference as appropriate");
686            }
687        }
688        err.emit()
689    }
690
691    fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
692        let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
693            (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
694        } else {
695            (false, lint::builtin::TRIVIAL_CASTS)
696        };
697        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
698        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
699        fcx.tcx.emit_node_span_lint(
700            lint,
701            self.expr.hir_id,
702            self.span,
703            errors::TrivialCast { numeric, expr_ty, cast_ty },
704        );
705    }
706
707    #[instrument(skip(fcx), level = "debug")]
708    pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
709        self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
710        self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
711
712        debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
713
714        if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
715            && !self.cast_ty.has_infer_types()
716        {
717            self.report_cast_to_unsized_type(fcx);
718        } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
719            // No sense in giving duplicate error messages
720        } else {
721            match self.try_coercion_cast(fcx) {
722                Ok(()) => {
723                    if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
724                        // When casting a raw pointer to another raw pointer, we cannot convert the cast into
725                        // a coercion because the pointee types might only differ in regions, which HIR typeck
726                        // cannot distinguish. This would cause us to erroneously discard a cast which will
727                        // lead to a borrowck error like #113257.
728                        // We still did a coercion above to unify inference variables for `ptr as _` casts.
729                        // This does cause us to miss some trivial casts in the trivial cast lint.
730                        debug!(" -> PointerCast");
731                    } else {
732                        self.trivial_cast_lint(fcx);
733                        debug!(" -> CoercionCast");
734                        fcx.typeck_results
735                            .borrow_mut()
736                            .set_coercion_cast(self.expr.hir_id.local_id);
737                    }
738                }
739                Err(_) => {
740                    match self.do_check(fcx) {
741                        Ok(k) => {
742                            debug!(" -> {:?}", k);
743                        }
744                        Err(e) => self.report_cast_error(fcx, e),
745                    };
746                }
747            };
748        }
749    }
750    /// Checks a cast, and report an error if one exists. In some cases, this
751    /// can return Ok and create type errors in the fcx rather than returning
752    /// directly. coercion-cast is handled in check instead of here.
753    fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
754        use rustc_middle::ty::cast::CastTy::*;
755        use rustc_middle::ty::cast::IntTy::*;
756
757        if self.cast_ty.is_dyn_star() {
758            // This coercion will fail if the feature is not enabled, OR
759            // if the coercion is (currently) illegal (e.g. `dyn* Foo + Send`
760            // to `dyn* Foo`). Report "casting is invalid" rather than
761            // "non-primitive cast".
762            return Err(CastError::IllegalCast);
763        }
764
765        let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
766        {
767            (Some(t_from), Some(t_cast)) => (t_from, t_cast),
768            // Function item types may need to be reified before casts.
769            (None, Some(t_cast)) => {
770                match *self.expr_ty.kind() {
771                    ty::FnDef(..) => {
772                        // Attempt a coercion to a fn pointer type.
773                        let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
774                        let res = fcx.coerce(
775                            self.expr,
776                            self.expr_ty,
777                            Ty::new_fn_ptr(fcx.tcx, f),
778                            AllowTwoPhase::No,
779                            None,
780                        );
781                        if let Err(TypeError::IntrinsicCast) = res {
782                            return Err(CastError::IllegalCast);
783                        }
784                        if res.is_err() {
785                            return Err(CastError::NonScalar);
786                        }
787                        (FnPtr, t_cast)
788                    }
789                    // Special case some errors for references, and check for
790                    // array-ptr-casts. `Ref` is not a CastTy because the cast
791                    // is split into a coercion to a pointer type, followed by
792                    // a cast.
793                    ty::Ref(_, inner_ty, mutbl) => {
794                        return match t_cast {
795                            Int(_) | Float => match *inner_ty.kind() {
796                                ty::Int(_)
797                                | ty::Uint(_)
798                                | ty::Float(_)
799                                | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
800                                    Err(CastError::NeedDeref)
801                                }
802                                _ => Err(CastError::NeedViaPtr),
803                            },
804                            // array-ptr-cast
805                            Ptr(mt) => {
806                                if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
807                                    return Err(CastError::IllegalCast);
808                                }
809                                self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
810                            }
811                            _ => Err(CastError::NonScalar),
812                        };
813                    }
814                    _ => return Err(CastError::NonScalar),
815                }
816            }
817            _ => return Err(CastError::NonScalar),
818        };
819        if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
820            && !adt_def.did().is_local()
821            && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
822        {
823            return Err(CastError::ForeignNonExhaustiveAdt);
824        }
825        match (t_from, t_cast) {
826            // These types have invariants! can't cast into them.
827            (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
828
829            // * -> Bool
830            (_, Int(Bool)) => Err(CastError::CastToBool),
831
832            // * -> Char
833            (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
834            (_, Int(Char)) => Err(CastError::CastToChar),
835
836            // prim -> float,ptr
837            (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
838
839            (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
840                Err(CastError::IllegalCast)
841            }
842
843            // ptr -> ptr
844            (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
845
846            // ptr-addr-cast
847            (Ptr(m_expr), Int(t_c)) => {
848                self.lossy_provenance_ptr2int_lint(fcx, t_c);
849                self.check_ptr_addr_cast(fcx, m_expr)
850            }
851            (FnPtr, Int(_)) => {
852                // FIXME(#95489): there should eventually be a lint for these casts
853                Ok(CastKind::FnPtrAddrCast)
854            }
855            // addr-ptr-cast
856            (Int(_), Ptr(mt)) => {
857                self.fuzzy_provenance_int2ptr_lint(fcx);
858                self.check_addr_ptr_cast(fcx, mt)
859            }
860            // fn-ptr-cast
861            (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
862
863            // prim -> prim
864            (Int(CEnum), Int(_)) => {
865                self.err_if_cenum_impl_drop(fcx);
866                Ok(CastKind::EnumCast)
867            }
868            (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
869
870            (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
871        }
872    }
873
874    fn check_ptr_ptr_cast(
875        &self,
876        fcx: &FnCtxt<'a, 'tcx>,
877        m_src: ty::TypeAndMut<'tcx>,
878        m_dst: ty::TypeAndMut<'tcx>,
879    ) -> Result<CastKind, CastError<'tcx>> {
880        debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
881        // ptr-ptr cast. metadata must match.
882
883        let src_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_src.ty, self.span)?);
884        let dst_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
885
886        // We can't cast if target pointer kind is unknown
887        let Some(dst_kind) = dst_kind else {
888            return Err(CastError::UnknownCastPtrKind);
889        };
890
891        // Cast to thin pointer is OK
892        if dst_kind == PointerKind::Thin {
893            return Ok(CastKind::PtrPtrCast);
894        }
895
896        // We can't cast to wide pointer if source pointer kind is unknown
897        let Some(src_kind) = src_kind else {
898            return Err(CastError::UnknownCastPtrKind);
899        };
900
901        match (src_kind, dst_kind) {
902            // thin -> fat? report invalid cast (don't complain about vtable kinds)
903            (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
904
905            // trait object -> trait object? need to do additional checks
906            (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
907                match (src_tty.principal(), dst_tty.principal()) {
908                    // A<dyn Src<...> + SrcAuto> -> B<dyn Dst<...> + DstAuto>. need to make sure
909                    // - `Src` and `Dst` traits are the same
910                    // - traits have the same generic arguments
911                    // - projections are the same
912                    // - `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`
913                    //
914                    // Note that trait upcasting goes through a different mechanism (`coerce_unsized`)
915                    // and is unaffected by this check.
916                    (Some(src_principal), Some(_)) => {
917                        let tcx = fcx.tcx;
918
919                        // We need to reconstruct trait object types.
920                        // `m_src` and `m_dst` won't work for us here because they will potentially
921                        // contain wrappers, which we do not care about.
922                        //
923                        // e.g. we want to allow `dyn T -> (dyn T,)`, etc.
924                        //
925                        // We also need to skip auto traits to emit an FCW and not an error.
926                        let src_obj = Ty::new_dynamic(
927                            tcx,
928                            tcx.mk_poly_existential_predicates(
929                                &src_tty.without_auto_traits().collect::<Vec<_>>(),
930                            ),
931                            tcx.lifetimes.re_erased,
932                            ty::Dyn,
933                        );
934                        let dst_obj = Ty::new_dynamic(
935                            tcx,
936                            tcx.mk_poly_existential_predicates(
937                                &dst_tty.without_auto_traits().collect::<Vec<_>>(),
938                            ),
939                            tcx.lifetimes.re_erased,
940                            ty::Dyn,
941                        );
942
943                        // `dyn Src = dyn Dst`, this checks for matching traits/generics/projections
944                        // This is `fcx.demand_eqtype`, but inlined to give a better error.
945                        let cause = fcx.misc(self.span);
946                        if fcx
947                            .at(&cause, fcx.param_env)
948                            .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
949                            .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
950                            .is_err()
951                        {
952                            return Err(CastError::DifferingKinds { src_kind, dst_kind });
953                        }
954
955                        // Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`.
956                        // Emit an FCW otherwise.
957                        let src_auto: FxHashSet<_> = src_tty
958                            .auto_traits()
959                            .chain(
960                                elaborate::supertrait_def_ids(tcx, src_principal.def_id())
961                                    .filter(|def_id| tcx.trait_is_auto(*def_id)),
962                            )
963                            .collect();
964
965                        let added = dst_tty
966                            .auto_traits()
967                            .filter(|trait_did| !src_auto.contains(trait_did))
968                            .collect::<Vec<_>>();
969
970                        if !added.is_empty() {
971                            return Err(CastError::PtrPtrAddingAutoTrait(added));
972                        }
973
974                        Ok(CastKind::PtrPtrCast)
975                    }
976
977                    // dyn Auto -> dyn Auto'? ok.
978                    (None, None) => Ok(CastKind::PtrPtrCast),
979
980                    // dyn Trait -> dyn Auto? not ok (for now).
981                    //
982                    // Although dropping the principal is already allowed for unsizing coercions
983                    // (e.g. `*const (dyn Trait + Auto)` to `*const dyn Auto`), dropping it is
984                    // currently **NOT** allowed for (non-coercion) ptr-to-ptr casts (e.g
985                    // `*const Foo` to `*const Bar` where `Foo` has a `dyn Trait + Auto` tail
986                    // and `Bar` has a `dyn Auto` tail), because the underlying MIR operations
987                    // currently work very differently:
988                    //
989                    // * A MIR unsizing coercion on raw pointers to trait objects (`*const dyn Src`
990                    //   to `*const dyn Dst`) is currently equivalent to downcasting the source to
991                    //   the concrete sized type that it was originally unsized from first (via a
992                    //   ptr-to-ptr cast from `*const Src` to `*const T` with `T: Sized`) and then
993                    //   unsizing this thin pointer to the target type (unsizing `*const T` to
994                    //   `*const Dst`). In particular, this means that the pointer's metadata
995                    //   (vtable) will semantically change, e.g. for const eval and miri, even
996                    //   though the vtables will always be merged for codegen.
997                    //
998                    // * A MIR ptr-to-ptr cast is currently equivalent to a transmute and does not
999                    //   change the pointer metadata (vtable) at all.
1000                    //
1001                    // In addition to this potentially surprising difference between coercion and
1002                    // non-coercion casts, casting away the principal with a MIR ptr-to-ptr cast
1003                    // is currently considered undefined behavior:
1004                    //
1005                    // As a validity invariant of pointers to trait objects, we currently require
1006                    // that the principal of the vtable in the pointer metadata exactly matches
1007                    // the principal of the pointee type, where "no principal" is also considered
1008                    // a kind of principal.
1009                    (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1010
1011                    // dyn Auto -> dyn Trait? not ok.
1012                    (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1013                }
1014            }
1015
1016            // fat -> fat? metadata kinds must match
1017            (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
1018
1019            (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
1020        }
1021    }
1022
1023    fn check_fptr_ptr_cast(
1024        &self,
1025        fcx: &FnCtxt<'a, 'tcx>,
1026        m_cast: ty::TypeAndMut<'tcx>,
1027    ) -> Result<CastKind, CastError<'tcx>> {
1028        // fptr-ptr cast. must be to thin ptr
1029
1030        match fcx.pointer_kind(m_cast.ty, self.span)? {
1031            None => Err(CastError::UnknownCastPtrKind),
1032            Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1033            _ => Err(CastError::IllegalCast),
1034        }
1035    }
1036
1037    fn check_ptr_addr_cast(
1038        &self,
1039        fcx: &FnCtxt<'a, 'tcx>,
1040        m_expr: ty::TypeAndMut<'tcx>,
1041    ) -> Result<CastKind, CastError<'tcx>> {
1042        // ptr-addr cast. must be from thin ptr
1043
1044        match fcx.pointer_kind(m_expr.ty, self.span)? {
1045            None => Err(CastError::UnknownExprPtrKind),
1046            Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1047            _ => Err(CastError::NeedViaThinPtr),
1048        }
1049    }
1050
1051    fn check_ref_cast(
1052        &self,
1053        fcx: &FnCtxt<'a, 'tcx>,
1054        mut m_expr: ty::TypeAndMut<'tcx>,
1055        mut m_cast: ty::TypeAndMut<'tcx>,
1056    ) -> Result<CastKind, CastError<'tcx>> {
1057        // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
1058        m_expr.ty = fcx.try_structurally_resolve_type(self.expr_span, m_expr.ty);
1059        m_cast.ty = fcx.try_structurally_resolve_type(self.cast_span, m_cast.ty);
1060
1061        if m_expr.mutbl >= m_cast.mutbl
1062            && let ty::Array(ety, _) = m_expr.ty.kind()
1063            && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1064        {
1065            // Due to historical reasons we allow directly casting references of
1066            // arrays into raw pointers of their element type.
1067
1068            // Coerce to a raw pointer so that we generate RawPtr in MIR.
1069            let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1070            fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1071                .unwrap_or_else(|_| {
1072                    bug!(
1073                        "could not cast from reference to array to pointer to array ({:?} to {:?})",
1074                        self.expr_ty,
1075                        array_ptr_type,
1076                    )
1077                });
1078
1079            // this will report a type mismatch if needed
1080            fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1081            return Ok(CastKind::ArrayPtrCast);
1082        }
1083
1084        Err(CastError::IllegalCast)
1085    }
1086
1087    fn check_addr_ptr_cast(
1088        &self,
1089        fcx: &FnCtxt<'a, 'tcx>,
1090        m_cast: TypeAndMut<'tcx>,
1091    ) -> Result<CastKind, CastError<'tcx>> {
1092        // ptr-addr cast. pointer must be thin.
1093        match fcx.pointer_kind(m_cast.ty, self.span)? {
1094            None => Err(CastError::UnknownCastPtrKind),
1095            Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1096            Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1097            Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1098            Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1099                Err(CastError::IntToWideCast(None))
1100            }
1101        }
1102    }
1103
1104    fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1105        match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1106            Ok(_) => Ok(()),
1107            Err(err) => Err(err),
1108        }
1109    }
1110
1111    fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1112        if let ty::Adt(d, _) = self.expr_ty.kind()
1113            && d.has_dtor(fcx.tcx)
1114        {
1115            let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1116            let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1117
1118            fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1119        }
1120    }
1121
1122    fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1123        let expr_prec = self.expr.precedence();
1124        let needs_parens = expr_prec < ExprPrecedence::Unambiguous;
1125
1126        let needs_cast = !matches!(t_c, ty::cast::IntTy::U(ty::UintTy::Usize));
1127        let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1128        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1129        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1130        let expr_span = self.expr_span.shrink_to_lo();
1131        let sugg = match (needs_parens, needs_cast) {
1132            (true, true) => errors::LossyProvenancePtr2IntSuggestion::NeedsParensCast {
1133                expr_span,
1134                cast_span,
1135                cast_ty,
1136            },
1137            (true, false) => {
1138                errors::LossyProvenancePtr2IntSuggestion::NeedsParens { expr_span, cast_span }
1139            }
1140            (false, true) => {
1141                errors::LossyProvenancePtr2IntSuggestion::NeedsCast { cast_span, cast_ty }
1142            }
1143            (false, false) => errors::LossyProvenancePtr2IntSuggestion::Other { cast_span },
1144        };
1145
1146        let lint = errors::LossyProvenancePtr2Int { expr_ty, cast_ty, sugg };
1147        fcx.tcx.emit_node_span_lint(
1148            lint::builtin::LOSSY_PROVENANCE_CASTS,
1149            self.expr.hir_id,
1150            self.span,
1151            lint,
1152        );
1153    }
1154
1155    fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1156        let sugg = errors::LossyProvenanceInt2PtrSuggestion {
1157            lo: self.expr_span.shrink_to_lo(),
1158            hi: self.expr_span.shrink_to_hi().to(self.cast_span),
1159        };
1160        let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1161        let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1162        let lint = errors::LossyProvenanceInt2Ptr { expr_ty, cast_ty, sugg };
1163        fcx.tcx.emit_node_span_lint(
1164            lint::builtin::FUZZY_PROVENANCE_CASTS,
1165            self.expr.hir_id,
1166            self.span,
1167            lint,
1168        );
1169    }
1170
1171    /// Attempt to suggest using `.is_empty` when trying to cast from a
1172    /// collection type to a boolean.
1173    fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1174        if self.cast_ty.is_bool() {
1175            let derefed = fcx
1176                .autoderef(self.expr_span, self.expr_ty)
1177                .silence_errors()
1178                .find(|t| matches!(t.0.kind(), ty::Str | ty::Slice(..)));
1179
1180            if let Some((deref_ty, _)) = derefed {
1181                // Give a note about what the expr derefs to.
1182                if deref_ty != self.expr_ty.peel_refs() {
1183                    err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1184                }
1185
1186                // Create a multipart suggestion: add `!` and `.is_empty()` in
1187                // place of the cast.
1188                err.subdiagnostic(errors::UseIsEmpty {
1189                    lo: self.expr_span.shrink_to_lo(),
1190                    hi: self.span.with_lo(self.expr_span.hi()),
1191                    expr_ty: self.expr_ty,
1192                });
1193            }
1194        }
1195    }
1196}