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