Skip to main content

rustc_hir_typeck/
coercion.rs

1//! # Type Coercion
2//!
3//! Under certain circumstances we will coerce from one type to another,
4//! for example by auto-borrowing. This occurs in situations where the
5//! compiler has a firm 'expected type' that was supplied from the user,
6//! and where the actual type is similar to that expected type in purpose
7//! but not in representation (so actual subtyping is inappropriate).
8//!
9//! ## Reborrowing
10//!
11//! Note that if we are expecting a reference, we will *reborrow*
12//! even if the argument provided was already a reference. This is
13//! useful for freezing mut things (that is, when the expected type is &T
14//! but you have &mut T) and also for avoiding the linearity
15//! of mut things (when the expected is &mut T and you have &mut T). See
16//! the various `tests/ui/coerce/*.rs` tests for
17//! examples of where this is useful.
18//!
19//! ## Subtle note
20//!
21//! When inferring the generic arguments of functions, the argument
22//! order is relevant, which can lead to the following edge case:
23//!
24//! ```ignore (illustrative)
25//! fn foo<T>(a: T, b: T) {
26//!     // ...
27//! }
28//!
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
32//!
33//! foo(&mut 7i32, &7i32);
34//! // This does not compile, as we first infer `T` to be `&mut i32`
35//! // and are then unable to coerce `&7i32` to `&mut i32`.
36//! ```
37
38use std::ops::{ControlFlow, Deref};
39
40use rustc_errors::codes::*;
41use rustc_errors::{Applicability, Diag, struct_span_code_err};
42use rustc_hir::attrs::InlineAttr;
43use rustc_hir::def_id::{DefId, LocalDefId};
44use rustc_hir::{self as hir, LangItem};
45use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
46use rustc_infer::infer::relate::RelateResult;
47use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
48use rustc_infer::traits::{
49    MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
50};
51use rustc_middle::span_bug;
52use rustc_middle::ty::adjustment::{
53    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
54    PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
58use rustc_span::{BytePos, DUMMY_SP, Span};
59use rustc_trait_selection::infer::InferCtxtExt as _;
60use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
61use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
62use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
63use rustc_trait_selection::traits::{
64    self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
65};
66use smallvec::{SmallVec, smallvec};
67use tracing::{debug, instrument};
68
69use crate::FnCtxt;
70use crate::errors::SuggestBoxingForReturnImplTrait;
71
72struct Coerce<'a, 'tcx> {
73    fcx: &'a FnCtxt<'a, 'tcx>,
74    cause: ObligationCause<'tcx>,
75    use_lub: bool,
76    /// Determines whether or not allow_two_phase_borrow is set on any
77    /// autoref adjustments we create while coercing. We don't want to
78    /// allow deref coercions to create two-phase borrows, at least initially,
79    /// but we do need two-phase borrows for function argument reborrows.
80    /// See #47489 and #48598
81    /// See docs on the "AllowTwoPhase" type for a more detailed discussion
82    allow_two_phase: AllowTwoPhase,
83    /// Whether we allow `NeverToAny` coercions. This is unsound if we're
84    /// coercing a place expression without it counting as a read in the MIR.
85    /// This is a side-effect of HIR not really having a great distinction
86    /// between places and values.
87    coerce_never: bool,
88}
89
90impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
91    type Target = FnCtxt<'a, 'tcx>;
92    fn deref(&self) -> &Self::Target {
93        self.fcx
94    }
95}
96
97type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
98
99/// Coercing a mutable reference to an immutable works, while
100/// coercing `&T` to `&mut T` should be forbidden.
101fn coerce_mutbls<'tcx>(
102    from_mutbl: hir::Mutability,
103    to_mutbl: hir::Mutability,
104) -> RelateResult<'tcx, ()> {
105    if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
106}
107
108/// This always returns `Ok(...)`.
109fn success<'tcx>(
110    adj: Vec<Adjustment<'tcx>>,
111    target: Ty<'tcx>,
112    obligations: PredicateObligations<'tcx>,
113) -> CoerceResult<'tcx> {
114    Ok(InferOk { value: (adj, target), obligations })
115}
116
117/// Whether to force a leak check to occur in `Coerce::unify_raw`.
118/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
119///
120/// FIXME: We may want to change type relations to always leak-check
121/// after exiting a binder, at which point we will always do so and
122/// no longer need to handle this explicitly
123enum ForceLeakCheck {
124    Yes,
125    No,
126}
127
128impl<'f, 'tcx> Coerce<'f, 'tcx> {
129    fn new(
130        fcx: &'f FnCtxt<'f, 'tcx>,
131        cause: ObligationCause<'tcx>,
132        allow_two_phase: AllowTwoPhase,
133        coerce_never: bool,
134    ) -> Self {
135        Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
136    }
137
138    fn unify_raw(
139        &self,
140        a: Ty<'tcx>,
141        b: Ty<'tcx>,
142        leak_check: ForceLeakCheck,
143    ) -> InferResult<'tcx, Ty<'tcx>> {
144        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:144",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(144u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
                                                    a, b, self.use_lub) as &dyn Value))])
            });
    } else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
145        self.commit_if_ok(|snapshot| {
146            let outer_universe = self.infcx.universe();
147
148            let at = self.at(&self.cause, self.fcx.param_env);
149
150            let res = if self.use_lub {
151                at.lub(b, a)
152            } else {
153                at.sup(DefineOpaqueTypes::Yes, b, a)
154                    .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
155            };
156
157            // In the new solver, lazy norm may allow us to shallowly equate
158            // more types, but we emit possibly impossible-to-satisfy obligations.
159            // Filter these cases out to make sure our coercion is more accurate.
160            let res = match res {
161                Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
162                    let ocx = ObligationCtxt::new(self);
163                    ocx.register_obligations(obligations);
164                    if ocx.try_evaluate_obligations().is_empty() {
165                        Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
166                    } else {
167                        Err(TypeError::Mismatch)
168                    }
169                }
170                res => res,
171            };
172
173            // We leak check here mostly because lub operations are
174            // kind of scuffed around binders. Instead of computing an actual
175            // lub'd binder we instead:
176            // - Equate the binders
177            // - Return the lhs of the lub operation
178            //
179            // This may lead to incomplete type inference for the resulting type
180            // of a `match` or `if .. else`, etc. This is a backwards compat
181            // hazard for if/when we start handling `lub` more correctly.
182            //
183            // In order to actually ensure that equating the binders *does*
184            // result in equal binders, and that the lhs is actually a supertype
185            // of the rhs, we must perform a leak check here.
186            if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
    ForceLeakCheck::Yes => true,
    _ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
187                self.leak_check(outer_universe, Some(snapshot))?;
188            }
189
190            res
191        })
192    }
193
194    /// Unify two types (using sub or lub).
195    fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
196        self.unify_raw(a, b, leak_check)
197            .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
198    }
199
200    /// Unify two types (using sub or lub) and produce a specific coercion.
201    fn unify_and(
202        &self,
203        a: Ty<'tcx>,
204        b: Ty<'tcx>,
205        adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
206        final_adjustment: Adjust,
207        leak_check: ForceLeakCheck,
208    ) -> CoerceResult<'tcx> {
209        self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
210            success(
211                adjustments
212                    .into_iter()
213                    .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
214                    .collect(),
215                ty,
216                obligations,
217            )
218        })
219    }
220
221    x;#[instrument(skip(self), ret)]
222    fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
223        // First, remove any resolved type variables (at the top level, at least):
224        let a = self.shallow_resolve(a);
225        let b = self.shallow_resolve(b);
226        debug!("Coerce.tys({:?} => {:?})", a, b);
227
228        // Coercing from `!` to any type is allowed:
229        if a.is_never() {
230            if self.coerce_never {
231                return success(
232                    vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
233                    b,
234                    PredicateObligations::new(),
235                );
236            } else {
237                // Otherwise the only coercion we can do is unification.
238                return self.unify(a, b, ForceLeakCheck::No);
239            }
240        }
241
242        // Coercing *from* an unresolved inference variable means that
243        // we have no information about the source type. This will always
244        // ultimately fall back to some form of subtyping.
245        if a.is_ty_var() {
246            return self.coerce_from_inference_variable(a, b);
247        }
248
249        // Consider coercing the subtype to a DST
250        //
251        // NOTE: this is wrapped in a `commit_if_ok` because it creates
252        // a "spurious" type variable, and we don't want to have that
253        // type variable in memory if the coercion fails.
254        let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
255        match unsize {
256            Ok(_) => {
257                debug!("coerce: unsize successful");
258                return unsize;
259            }
260            Err(error) => {
261                debug!(?error, "coerce: unsize failed");
262            }
263        }
264
265        // Examine the target type and consider type-specific coercions, such
266        // as auto-borrowing, coercing pointer mutability, or pin-ergonomics.
267        match *b.kind() {
268            ty::RawPtr(_, b_mutbl) => {
269                return self.coerce_to_raw_ptr(a, b, b_mutbl);
270            }
271            ty::Ref(r_b, _, mutbl_b) => {
272                return self.coerce_to_ref(a, b, r_b, mutbl_b);
273            }
274            ty::Adt(pin, _)
275                if self.tcx.features().pin_ergonomics()
276                    && self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) =>
277            {
278                let pin_coerce = self.commit_if_ok(|_| self.coerce_to_pin_ref(a, b));
279                if pin_coerce.is_ok() {
280                    return pin_coerce;
281                }
282            }
283            _ => {}
284        }
285
286        match *a.kind() {
287            ty::FnDef(..) => {
288                // Function items are coercible to any closure
289                // type; function pointers are not (that would
290                // require double indirection).
291                // Additionally, we permit coercion of function
292                // items to drop the unsafe qualifier.
293                self.coerce_from_fn_item(a, b)
294            }
295            ty::FnPtr(a_sig_tys, a_hdr) => {
296                // We permit coercion of fn pointers to drop the
297                // unsafe qualifier.
298                self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
299            }
300            ty::Closure(..) => {
301                // Non-capturing closures are coercible to
302                // function pointers or unsafe function pointers.
303                // It cannot convert closures that require unsafe.
304                self.coerce_closure_to_fn(a, b)
305            }
306            _ => {
307                // Otherwise, just use unification rules.
308                self.unify(a, b, ForceLeakCheck::No)
309            }
310        }
311    }
312
313    /// Coercing *from* an inference variable. In this case, we have no information
314    /// about the source type, so we can't really do a true coercion and we always
315    /// fall back to subtyping (`unify_and`).
316    fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
317        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:317",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(317u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
                                                    a, b) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
318        if true {
    if !(a.is_ty_var() && self.shallow_resolve(a) == a) {
        ::core::panicking::panic("assertion failed: a.is_ty_var() && self.shallow_resolve(a) == a")
    };
};debug_assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
319        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
320
321        if b.is_ty_var() {
322            let mut obligations = PredicateObligations::with_capacity(2);
323            let mut push_coerce_obligation = |a, b| {
324                obligations.push(Obligation::new(
325                    self.tcx(),
326                    self.cause.clone(),
327                    self.param_env,
328                    ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
329                ));
330            };
331
332            let target_ty = if self.use_lub {
333                // When computing the lub, we create a new target
334                // and coerce both `a` and `b` to it.
335                let target_ty = self.next_ty_var(self.cause.span);
336                push_coerce_obligation(a, target_ty);
337                push_coerce_obligation(b, target_ty);
338                target_ty
339            } else {
340                // When subtyping, we don't need to create a new target
341                // as we only coerce `a` to `b`.
342                push_coerce_obligation(a, b);
343                b
344            };
345
346            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:346",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(346u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
                                                    target_ty, obligations) as &dyn Value))])
            });
    } else { ; }
};debug!(
347                "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
348                target_ty, obligations
349            );
350            success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
351        } else {
352            // One unresolved type variable: just apply subtyping, we may be able
353            // to do something useful.
354            self.unify(a, b, ForceLeakCheck::No)
355        }
356    }
357
358    /// Handles coercing some arbitrary type `a` to some reference (`b`). This
359    /// handles a few cases:
360    /// - Introducing reborrows to give more flexible lifetimes
361    /// - Deref coercions to allow `&T` to coerce to `&T::Target`
362    /// - Coercing mutable references to immutable references
363    /// These coercions can be freely intermixed, for example we are able to
364    /// coerce `&mut T` to `&mut T::Target`.
365    fn coerce_to_ref(
366        &self,
367        a: Ty<'tcx>,
368        b: Ty<'tcx>,
369        r_b: ty::Region<'tcx>,
370        mutbl_b: hir::Mutability,
371    ) -> CoerceResult<'tcx> {
372        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:372",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(372u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
                                                    a, b) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
373        if true {
    if !(self.shallow_resolve(a) == a) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
    };
};debug_assert!(self.shallow_resolve(a) == a);
374        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
375
376        let (r_a, mt_a) = match *a.kind() {
377            ty::Ref(r_a, ty, mutbl) => {
378                coerce_mutbls(mutbl, mutbl_b)?;
379                (r_a, ty::TypeAndMut { ty, mutbl })
380            }
381            _ => return self.unify(a, b, ForceLeakCheck::No),
382        };
383
384        // Look at each step in the `Deref` chain and check if
385        // any of the autoref'd `Target` types unify with the
386        // coercion target.
387        //
388        // For example when coercing from `&mut Vec<T>` to `&M [T]` we
389        // have three deref steps:
390        // 1. `&mut Vec<T>`, skip autoref
391        // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
392        //     - `&M Vec<T>` does not unify with `&M [T]`
393        // 3. `[T]`, autoref'd ty: `&M [T]`
394        //     - `&M [T]` does unify with `&M [T]`
395        let mut first_error = None;
396        let mut r_borrow_var = None;
397        let mut autoderef = self.autoderef(self.cause.span, a);
398        let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
399            if autoderefs == 0 {
400                // Don't autoref the first step as otherwise we'd allow
401                // coercing `&T` to `&&T`.
402                return None;
403            }
404
405            // The logic here really shouldn't exist. We don't care about free
406            // lifetimes during HIR typeck. Unfortunately later parts of this
407            // function rely on structural identity of the autoref'd deref'd ty.
408            //
409            // This means that what region we use here actually impacts whether
410            // we emit a reborrow coercion or not which can affect diagnostics
411            // and capture analysis (which in turn affects borrowck).
412            let r = if !self.use_lub {
413                r_b
414            } else if autoderefs == 1 {
415                r_a
416            } else {
417                if r_borrow_var.is_none() {
418                    // create var lazily, at most once
419                    let coercion = RegionVariableOrigin::Coercion(self.cause.span);
420                    let r = self.next_region_var(coercion);
421                    r_borrow_var = Some(r);
422                }
423                r_borrow_var.unwrap()
424            };
425
426            let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
427
428            // Note that we unify the autoref'd `Target` type with `b` rather than
429            // the `Target` type with the pointee of `b`. This is necessary
430            // to properly account for the differing variances of the pointees
431            // of `&` vs `&mut` references.
432            match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
433                Ok(ok) => Some(ok),
434                Err(err) => {
435                    if first_error.is_none() {
436                        first_error = Some(err);
437                    }
438                    None
439                }
440            }
441        });
442
443        // Extract type or return an error. We return the first error
444        // we got, which should be from relating the "base" type
445        // (e.g., in example above, the failure from relating `Vec<T>`
446        // to the target type), since that should be the least
447        // confusing.
448        let Some(InferOk { value: coerced_a, mut obligations }) = found else {
449            if let Some(first_error) = first_error {
450                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:450",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(450u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
                                                    first_error) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
451                return Err(first_error);
452            } else {
453                // This may happen in the new trait solver since autoderef requires
454                // the pointee to be structurally normalizable, or else it'll just bail.
455                // So when we have a type like `&<not well formed>`, then we get no
456                // autoderef steps (even though there should be at least one). That means
457                // we get no type mismatches, since the loop above just exits early.
458                return Err(TypeError::Mismatch);
459            }
460        };
461
462        if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
463            // As a special case, if we would produce `&'a *x`, that's
464            // a total no-op. We end up with the type `&'a T` just as
465            // we started with. In that case, just skip it altogether.
466            //
467            // Unfortunately, this can actually effect capture analysis
468            // which in turn means this effects borrow checking. This can
469            // also effect diagnostics.
470            // FIXME(BoxyUwU): we should always emit reborrow coercions
471            //
472            // Note that for `&mut`, we DO want to reborrow --
473            // otherwise, this would be a move, which might be an
474            // error. For example `foo(self.x)` where `self` and
475            // `self.x` both have `&mut `type would be a move of
476            // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
477            // which is a borrow.
478            if !mutbl_b.is_not() {
    ::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
479            return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
480        }
481
482        let InferOk { value: mut adjustments, obligations: o } =
483            self.adjust_steps_as_infer_ok(&autoderef);
484        obligations.extend(o);
485        obligations.extend(autoderef.into_obligations());
486
487        if !#[allow(non_exhaustive_omitted_patterns)] match coerced_a.kind() {
            ty::Ref(..) => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("expected a ref type, got {0:?}",
                coerced_a));
    }
};assert!(
488            matches!(coerced_a.kind(), ty::Ref(..)),
489            "expected a ref type, got {:?}",
490            coerced_a
491        );
492
493        // Now apply the autoref
494        let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
495        adjustments
496            .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
497
498        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:498",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(498u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
                                                    coerced_a, adjustments) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
499
500        success(adjustments, coerced_a, obligations)
501    }
502
503    /// Performs [unsized coercion] by emulating a fulfillment loop on a
504    /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
505    /// are successfully selected.
506    ///
507    /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
508    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("coerce_unsized",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(508u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&["source", "target"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:510",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(510u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&["source", "target"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&source) as
                                                        &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&target) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if true {
                if !(self.shallow_resolve(source) == source) {
                    ::core::panicking::panic("assertion failed: self.shallow_resolve(source) == source")
                };
            };
            if true {
                if !(self.shallow_resolve(target) == target) {
                    ::core::panicking::panic("assertion failed: self.shallow_resolve(target) == target")
                };
            };
            if source.is_ty_var() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:518",
                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                        ::tracing_core::__macro_support::Option::Some(518u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return Err(TypeError::Mismatch);
            }
            if target.is_ty_var() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:522",
                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                        ::tracing_core::__macro_support::Option::Some(522u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return Err(TypeError::Mismatch);
            }
            match target.kind() {
                ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
                    | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Str |
                    ty::Array(_, _) | ty::Slice(_) | ty::FnDef(_, _) |
                    ty::FnPtr(_, _) | ty::Dynamic(_, _) | ty::Closure(_, _) |
                    ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) |
                    ty::CoroutineWitness(_, _) | ty::Never | ty::Tuple(_) =>
                    return Err(TypeError::Mismatch),
                _ => {}
            }
            if let ty::Ref(_, source_pointee, ty::Mutability::Not) =
                                *source.kind() && source_pointee.is_str() &&
                        let ty::Ref(_, target_pointee, ty::Mutability::Not) =
                            *target.kind() && target_pointee.is_str() {
                return Err(TypeError::Mismatch);
            }
            let traits =
                (self.tcx.lang_items().unsize_trait(),
                    self.tcx.lang_items().coerce_unsized_trait());
            let (Some(unsize_did), Some(coerce_unsized_did)) =
                traits else {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:576",
                                            "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                            ::tracing_core::__macro_support::Option::Some(576u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return Err(TypeError::Mismatch);
                };
            let reborrow =
                match (source.kind(), target.kind()) {
                    (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
                        coerce_mutbls(mutbl_a, mutbl_b)?;
                        let coercion =
                            RegionVariableOrigin::Coercion(self.cause.span);
                        let r_borrow = self.next_region_var(coercion);
                        let mutbl =
                            AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
                        Some((Adjustment {
                                    kind: Adjust::Deref(DerefAdjustKind::Builtin),
                                    target: ty_a,
                                },
                                Adjustment {
                                    kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
                                    target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
                                }))
                    }
                    (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
                        coerce_mutbls(mt_a, mt_b)?;
                        Some((Adjustment {
                                    kind: Adjust::Deref(DerefAdjustKind::Builtin),
                                    target: ty_a,
                                },
                                Adjustment {
                                    kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
                                    target: Ty::new_ptr(self.tcx, ty_a, mt_b),
                                }))
                    }
                    _ => None,
                };
            let coerce_source =
                reborrow.as_ref().map_or(source, |(_, r)| r.target);
            let coerce_target = self.next_ty_var(self.cause.span);
            let mut coercion =
                self.unify_and(coerce_target, target,
                        reborrow.into_iter().flat_map(|(deref, autoref)|
                                [deref, autoref]), Adjust::Pointer(PointerCoercion::Unsize),
                        ForceLeakCheck::No)?;
            let cause =
                self.cause(self.cause.span,
                    ObligationCauseCode::Coercion { source, target });
            let pred =
                ty::TraitRef::new(self.tcx, coerce_unsized_did,
                    [coerce_source, coerce_target]);
            let obligation =
                Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
            if self.next_trait_solver() {
                coercion.obligations.push(obligation);
                if self.infcx.visit_proof_tree(Goal::new(self.tcx,
                                self.param_env, pred),
                            &mut CoerceVisitor {
                                    fcx: self.fcx,
                                    span: self.cause.span,
                                }).is_break() {
                    return Err(TypeError::Mismatch);
                }
            } else {
                self.coerce_unsized_old_solver(obligation, &mut coercion,
                        coerce_unsized_did, unsize_did)?;
            }
            Ok(coercion)
        }
    }
}#[instrument(skip(self), level = "debug")]
509    fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
510        debug!(?source, ?target);
511        debug_assert!(self.shallow_resolve(source) == source);
512        debug_assert!(self.shallow_resolve(target) == target);
513
514        // We don't apply any coercions incase either the source or target
515        // aren't sufficiently well known but tend to instead just equate
516        // them both.
517        if source.is_ty_var() {
518            debug!("coerce_unsized: source is a TyVar, bailing out");
519            return Err(TypeError::Mismatch);
520        }
521        if target.is_ty_var() {
522            debug!("coerce_unsized: target is a TyVar, bailing out");
523            return Err(TypeError::Mismatch);
524        }
525
526        // This is an optimization because coercion is one of the most common
527        // operations that we do in typeck, since it happens at every assignment
528        // and call arg (among other positions).
529        //
530        // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
531        // That's because these are built-in types for which a core-provided impl
532        // doesn't exist, and for which a user-written impl is invalid.
533        //
534        // This is technically incomplete when users write impossible bounds like
535        // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
536        // and coercion is allowed to be incomplete. The only case where this matters
537        // is impossible bounds.
538        //
539        // Note that some of these types implement `LHS: Unsize<RHS>`, but they
540        // do not implement *`CoerceUnsized`* which is the root obligation of the
541        // check below.
542        match target.kind() {
543            ty::Bool
544            | ty::Char
545            | ty::Int(_)
546            | ty::Uint(_)
547            | ty::Float(_)
548            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
549            | ty::Str
550            | ty::Array(_, _)
551            | ty::Slice(_)
552            | ty::FnDef(_, _)
553            | ty::FnPtr(_, _)
554            | ty::Dynamic(_, _)
555            | ty::Closure(_, _)
556            | ty::CoroutineClosure(_, _)
557            | ty::Coroutine(_, _)
558            | ty::CoroutineWitness(_, _)
559            | ty::Never
560            | ty::Tuple(_) => return Err(TypeError::Mismatch),
561            _ => {}
562        }
563        // `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
564        // so we fast path bail out here
565        if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
566            && source_pointee.is_str()
567            && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
568            && target_pointee.is_str()
569        {
570            return Err(TypeError::Mismatch);
571        }
572
573        let traits =
574            (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
575        let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
576            debug!("missing Unsize or CoerceUnsized traits");
577            return Err(TypeError::Mismatch);
578        };
579
580        // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
581        // a DST unless we have to. This currently comes out in the wash since
582        // we can't unify [T] with U. But to properly support DST, we need to allow
583        // that, at which point we will need extra checks on the target here.
584
585        // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
586        let reborrow = match (source.kind(), target.kind()) {
587            (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
588                coerce_mutbls(mutbl_a, mutbl_b)?;
589
590                let coercion = RegionVariableOrigin::Coercion(self.cause.span);
591                let r_borrow = self.next_region_var(coercion);
592
593                // We don't allow two-phase borrows here, at least for initial
594                // implementation. If it happens that this coercion is a function argument,
595                // the reborrow in coerce_borrowed_ptr will pick it up.
596                let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
597
598                Some((
599                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
600                    Adjustment {
601                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
602                        target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
603                    },
604                ))
605            }
606            (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
607                coerce_mutbls(mt_a, mt_b)?;
608
609                Some((
610                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
611                    Adjustment {
612                        kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
613                        target: Ty::new_ptr(self.tcx, ty_a, mt_b),
614                    },
615                ))
616            }
617            _ => None,
618        };
619        let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
620
621        // Setup either a subtyping or a LUB relationship between
622        // the `CoerceUnsized` target type and the expected type.
623        // We only have the latter, so we use an inference variable
624        // for the former and let type inference do the rest.
625        let coerce_target = self.next_ty_var(self.cause.span);
626
627        let mut coercion = self.unify_and(
628            coerce_target,
629            target,
630            reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
631            Adjust::Pointer(PointerCoercion::Unsize),
632            ForceLeakCheck::No,
633        )?;
634
635        // Create an obligation for `Source: CoerceUnsized<Target>`.
636        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
637        let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
638        let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
639
640        if self.next_trait_solver() {
641            coercion.obligations.push(obligation);
642
643            if self
644                .infcx
645                .visit_proof_tree(
646                    Goal::new(self.tcx, self.param_env, pred),
647                    &mut CoerceVisitor { fcx: self.fcx, span: self.cause.span },
648                )
649                .is_break()
650            {
651                return Err(TypeError::Mismatch);
652            }
653        } else {
654            self.coerce_unsized_old_solver(
655                obligation,
656                &mut coercion,
657                coerce_unsized_did,
658                unsize_did,
659            )?;
660        }
661
662        Ok(coercion)
663    }
664
665    fn coerce_unsized_old_solver(
666        &self,
667        obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
668        coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
669        coerce_unsized_did: DefId,
670        unsize_did: DefId,
671    ) -> Result<(), TypeError<'tcx>> {
672        let mut selcx = traits::SelectionContext::new(self);
673        // Use a FIFO queue for this custom fulfillment procedure.
674        //
675        // A Vec (or SmallVec) is not a natural choice for a queue. However,
676        // this code path is hot, and this queue usually has a max length of 1
677        // and almost never more than 3. By using a SmallVec we avoid an
678        // allocation, at the (very small) cost of (occasionally) having to
679        // shift subsequent elements down when removing the front element.
680        let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(obligation);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([obligation])))
    }
}smallvec![obligation];
681
682        // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
683        // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
684        // inference might unify those two inner type variables later.
685        let traits = [coerce_unsized_did, unsize_did];
686        while !queue.is_empty() {
687            let obligation = queue.remove(0);
688            let trait_pred = match obligation.predicate.kind().no_bound_vars() {
689                Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
690                    if traits.contains(&trait_pred.def_id()) =>
691                {
692                    self.resolve_vars_if_possible(trait_pred)
693                }
694                // Eagerly process alias-relate obligations in new trait solver,
695                // since these can be emitted in the process of solving trait goals,
696                // but we need to constrain vars before processing goals mentioning
697                // them.
698                Some(ty::PredicateKind::AliasRelate(..)) => {
699                    let ocx = ObligationCtxt::new(self);
700                    ocx.register_obligation(obligation);
701                    if !ocx.try_evaluate_obligations().is_empty() {
702                        return Err(TypeError::Mismatch);
703                    }
704                    coercion.obligations.extend(ocx.into_pending_obligations());
705                    continue;
706                }
707                _ => {
708                    coercion.obligations.push(obligation);
709                    continue;
710                }
711            };
712            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:712",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(712u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
                                                    trait_pred) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
713            match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
714                // Uncertain or unimplemented.
715                Ok(None) => {
716                    if trait_pred.def_id() == unsize_did {
717                        let self_ty = trait_pred.self_ty();
718                        let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
719                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:719",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(719u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
                                                    trait_pred) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
720                        match (self_ty.kind(), unsize_ty.kind()) {
721                            (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
722                                if self.type_var_is_sized(v) =>
723                            {
724                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:724",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(724u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
                                                    v) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
725                                coercion.obligations.push(obligation);
726                                // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
727                                // for unsizing.
728                            }
729                            _ => {
730                                // Some other case for `$0: Unsize<Something>`. Note that we
731                                // hit this case even if `Something` is a sized type, so just
732                                // don't do the coercion.
733                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:733",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(733u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized: ambiguous unsize");
734                                return Err(TypeError::Mismatch);
735                            }
736                        }
737                    } else {
738                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:738",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(738u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized: early return - ambiguous");
739                        return Err(TypeError::Mismatch);
740                    }
741                }
742                Err(SelectionError::Unimplemented) => {
743                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:743",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(743u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
744                    return Err(TypeError::Mismatch);
745                }
746
747                Err(SelectionError::TraitDynIncompatible(_)) => {
748                    // Dyn compatibility errors in coercion will *always* be due to the
749                    // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
750                    // written in source somewhere (otherwise we will never have lowered
751                    // the dyn trait from HIR to middle).
752                    //
753                    // There's no reason to emit yet another dyn compatibility error,
754                    // especially since the span will differ slightly and thus not be
755                    // deduplicated at all!
756                    self.fcx.set_tainted_by_errors(
757                        self.fcx
758                            .dcx()
759                            .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
760                    );
761                }
762                Err(err) => {
763                    let guar = self.err_ctxt().report_selection_error(
764                        obligation.clone(),
765                        &obligation,
766                        &err,
767                    );
768                    self.fcx.set_tainted_by_errors(guar);
769                    // Treat this like an obligation and follow through
770                    // with the unsizing - the lack of a coercion should
771                    // be silent, as it causes a type mismatch later.
772                }
773                Ok(Some(ImplSource::UserDefined(impl_source))) => {
774                    queue.extend(impl_source.nested);
775                    // Certain incoherent `CoerceUnsized` implementations may cause ICEs,
776                    // so check the impl's validity. Taint the body so that we don't try
777                    // to evaluate these invalid coercions in CTFE. We only need to do this
778                    // for local impls, since upstream impls should be valid.
779                    if impl_source.impl_def_id.is_local()
780                        && let Err(guar) =
781                            self.tcx.ensure_ok().coerce_unsized_info(impl_source.impl_def_id)
782                    {
783                        self.fcx.set_tainted_by_errors(guar);
784                    }
785                }
786                Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
787            }
788        }
789
790        Ok(())
791    }
792
793    /// Applies reborrowing for `Pin`
794    ///
795    /// We currently only support reborrowing `Pin<&mut T>` as `Pin<&mut T>`. This is accomplished
796    /// by inserting a call to `Pin::as_mut` during MIR building.
797    ///
798    /// In the future we might want to support other reborrowing coercions, such as:
799    /// - `Pin<&mut T>` as `Pin<&T>`
800    /// - `Pin<&T>` as `Pin<&T>`
801    /// - `Pin<Box<T>>` as `Pin<&T>`
802    /// - `Pin<Box<T>>` as `Pin<&mut T>`
803    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("coerce_to_pin_ref",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(803u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&["a", "b"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !(self.shallow_resolve(a) == a) {
                    ::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
                };
            };
            if true {
                if !(self.shallow_resolve(b) == b) {
                    ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
                };
            };
            let extract_pin_mut =
                |ty: Ty<'tcx>|
                    {
                        let (pin, ty) =
                            match ty.kind() {
                                ty::Adt(pin, args) if
                                    self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
                                    (*pin, args[0].expect_ty())
                                }
                                _ => {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:819",
                                                            "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(819u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("can\'t reborrow {0:?} as pinned",
                                                                                        ty) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    return Err(TypeError::Mismatch);
                                }
                            };
                        match ty.kind() {
                            ty::Ref(region, ty, mutbl) =>
                                Ok((pin, *region, *ty, *mutbl)),
                            _ => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:827",
                                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(827u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!("can\'t reborrow pin of inner type {0:?}",
                                                                                    ty) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                Err(TypeError::Mismatch)
                            }
                        }
                    };
            let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
            let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
            coerce_mutbls(mut_a, mut_b)?;
            let a =
                Ty::new_adt(self.tcx, pin,
                    self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty,
                                            mut_b).into()]));
            self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b),
                ForceLeakCheck::No)
        }
    }
}#[instrument(skip(self), level = "trace")]
804    fn coerce_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
805        debug_assert!(self.shallow_resolve(a) == a);
806        debug_assert!(self.shallow_resolve(b) == b);
807
808        // We need to make sure the two types are compatible for coercion.
809        // Then we will build a ReborrowPin adjustment and return that as an InferOk.
810
811        // Right now we can only reborrow if this is a `Pin<&mut T>`.
812        let extract_pin_mut = |ty: Ty<'tcx>| {
813            // Get the T out of Pin<T>
814            let (pin, ty) = match ty.kind() {
815                ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
816                    (*pin, args[0].expect_ty())
817                }
818                _ => {
819                    debug!("can't reborrow {:?} as pinned", ty);
820                    return Err(TypeError::Mismatch);
821                }
822            };
823            // Make sure the T is something we understand (just `&mut U` for now)
824            match ty.kind() {
825                ty::Ref(region, ty, mutbl) => Ok((pin, *region, *ty, *mutbl)),
826                _ => {
827                    debug!("can't reborrow pin of inner type {:?}", ty);
828                    Err(TypeError::Mismatch)
829                }
830            }
831        };
832
833        let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
834        let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
835
836        coerce_mutbls(mut_a, mut_b)?;
837
838        // update a with b's mutability since we'll be coercing mutability
839        let a = Ty::new_adt(
840            self.tcx,
841            pin,
842            self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty, mut_b).into()]),
843        );
844
845        // To complete the reborrow, we need to make sure we can unify the inner types, and if so we
846        // add the adjustments.
847        self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b), ForceLeakCheck::No)
848    }
849
850    fn coerce_from_fn_pointer(
851        &self,
852        a: Ty<'tcx>,
853        a_sig: ty::PolyFnSig<'tcx>,
854        b: Ty<'tcx>,
855    ) -> CoerceResult<'tcx> {
856        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:856",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(856u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message", "a_sig",
                                        "b"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&a_sig) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&b) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
857        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
858
859        match b.kind() {
860            ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety.is_unsafe() => {
861                let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
862                let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
863                self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
864            }
865            _ => self.unify(a, b, ForceLeakCheck::Yes),
866        }
867    }
868
869    fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
870        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:870",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(870u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
                                                    a, b) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
871        if true {
    if !(self.shallow_resolve(a) == a) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
    };
};debug_assert!(self.shallow_resolve(a) == a);
872        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
873
874        match b.kind() {
875            ty::FnPtr(_, b_hdr) => {
876                let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety))?;
877
878                let InferOk { value: a_sig, mut obligations } =
879                    self.at(&self.cause, self.param_env).normalize(a_sig);
880                let a = Ty::new_fn_ptr(self.tcx, a_sig);
881
882                let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety));
883                let InferOk { value, obligations: o2 } =
884                    self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
885
886                obligations.extend(o2);
887                Ok(InferOk { value, obligations })
888            }
889            _ => self.unify(a, b, ForceLeakCheck::No),
890        }
891    }
892
893    /// Attempts to coerce from a closure to a function pointer. Fails
894    /// if the closure has any upvars.
895    fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
896        if true {
    if !(self.shallow_resolve(a) == a) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
    };
};debug_assert!(self.shallow_resolve(a) == a);
897        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
898
899        match b.kind() {
900            ty::FnPtr(_, hdr) => {
901                let safety = hdr.safety;
902                let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
903                let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety), terr)?;
904                let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
905                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:905",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(905u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
                                                    a, b, pointer_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
906
907                let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
908                self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
909            }
910            _ => self.unify(a, b, ForceLeakCheck::No),
911        }
912    }
913
914    fn coerce_to_raw_ptr(
915        &self,
916        a: Ty<'tcx>,
917        b: Ty<'tcx>,
918        mutbl_b: hir::Mutability,
919    ) -> CoerceResult<'tcx> {
920        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:920",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(920u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
                                                    a, b) as &dyn Value))])
            });
    } else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
921        if true {
    if !(self.shallow_resolve(a) == a) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
    };
};debug_assert!(self.shallow_resolve(a) == a);
922        if true {
    if !(self.shallow_resolve(b) == b) {
        ::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
    };
};debug_assert!(self.shallow_resolve(b) == b);
923
924        let (is_ref, mt_a) = match *a.kind() {
925            ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
926            ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
927            _ => return self.unify(a, b, ForceLeakCheck::No),
928        };
929        coerce_mutbls(mt_a.mutbl, mutbl_b)?;
930
931        // Check that the types which they point at are compatible.
932        let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
933        // Although references and raw ptrs have the same
934        // representation, we still register an Adjust::DerefRef so that
935        // regionck knows that the region for `a` must be valid here.
936        if is_ref {
937            self.unify_and(
938                a_raw,
939                b,
940                [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
941                Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
942                ForceLeakCheck::No,
943            )
944        } else if mt_a.mutbl != mutbl_b {
945            self.unify_and(
946                a_raw,
947                b,
948                [],
949                Adjust::Pointer(PointerCoercion::MutToConstPointer),
950                ForceLeakCheck::No,
951            )
952        } else {
953            self.unify(a_raw, b, ForceLeakCheck::No)
954        }
955    }
956}
957
958impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
959    /// Attempt to coerce an expression to a type, and return the
960    /// adjusted type of the expression, if successful.
961    /// Adjustments are only recorded if the coercion succeeded.
962    /// The expressions *must not* have any preexisting adjustments.
963    pub(crate) fn coerce(
964        &self,
965        expr: &'tcx hir::Expr<'tcx>,
966        expr_ty: Ty<'tcx>,
967        mut target: Ty<'tcx>,
968        allow_two_phase: AllowTwoPhase,
969        cause: Option<ObligationCause<'tcx>>,
970    ) -> RelateResult<'tcx, Ty<'tcx>> {
971        let source = self.try_structurally_resolve_type(expr.span, expr_ty);
972        if self.next_trait_solver() {
973            target = self.try_structurally_resolve_type(
974                cause.as_ref().map_or(expr.span, |cause| cause.span),
975                target,
976            );
977        }
978        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:978",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(978u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
                                                    expr, source, target) as &dyn Value))])
            });
    } else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
979
980        let cause =
981            cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
982        let coerce = Coerce::new(
983            self,
984            cause,
985            allow_two_phase,
986            self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
987        );
988        let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
989
990        let (adjustments, _) = self.register_infer_ok_obligations(ok);
991        self.apply_adjustments(expr, adjustments);
992        Ok(if let Err(guar) = expr_ty.error_reported() {
993            Ty::new_error(self.tcx, guar)
994        } else {
995            target
996        })
997    }
998
999    /// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1000    /// and may return false positives if types are not yet fully constrained by inference.
1001    ///
1002    /// Returns false if the coercion is not possible, or if the coercion creates any
1003    /// sub-obligations that result in errors.
1004    ///
1005    /// This should only be used for diagnostics.
1006    pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1007        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1008        // We don't ever need two-phase here since we throw out the result of the coercion.
1009        // We also just always set `coerce_never` to true, since this is a heuristic.
1010        let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1011        self.probe(|_| {
1012            // Make sure to structurally resolve the types, since we use
1013            // the `TyKind`s heavily in coercion.
1014            let ocx = ObligationCtxt::new(self);
1015            let structurally_resolve = |ty| {
1016                let ty = self.shallow_resolve(ty);
1017                if self.next_trait_solver()
1018                    && let ty::Alias(..) = ty.kind()
1019                {
1020                    ocx.structurally_normalize_ty(&cause, self.param_env, ty)
1021                } else {
1022                    Ok(ty)
1023                }
1024            };
1025            let Ok(expr_ty) = structurally_resolve(expr_ty) else {
1026                return false;
1027            };
1028            let Ok(target_ty) = structurally_resolve(target_ty) else {
1029                return false;
1030            };
1031
1032            let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1033                return false;
1034            };
1035            ocx.register_obligations(ok.obligations);
1036            ocx.try_evaluate_obligations().is_empty()
1037        })
1038    }
1039
1040    /// Given a type and a target type, this function will calculate and return
1041    /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1042    /// it's not possible, return `None`.
1043    pub(crate) fn deref_steps_for_suggestion(
1044        &self,
1045        expr_ty: Ty<'tcx>,
1046        target: Ty<'tcx>,
1047    ) -> Option<usize> {
1048        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1049        // We don't ever need two-phase here since we throw out the result of the coercion.
1050        let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1051        coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1052            self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1053        })
1054    }
1055
1056    /// Given a type, this function will calculate and return the type given
1057    /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1058    ///
1059    /// This function is for diagnostics only, since it does not register
1060    /// trait or region sub-obligations. (presumably we could, but it's not
1061    /// particularly important for diagnostics...)
1062    pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1063        self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1064            self.infcx
1065                .type_implements_trait(
1066                    self.tcx.lang_items().deref_mut_trait()?,
1067                    [expr_ty],
1068                    self.param_env,
1069                )
1070                .may_apply()
1071                .then_some(deref_ty)
1072        })
1073    }
1074
1075    x;#[instrument(level = "debug", skip(self), ret)]
1076    fn sig_for_coerce_lub(
1077        &self,
1078        ty: Ty<'tcx>,
1079        closure_upvars_terr: TypeError<'tcx>,
1080    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1081        match ty.kind() {
1082            ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1083            ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1084            _ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1085        }
1086    }
1087
1088    fn sig_for_fn_def_coercion(
1089        &self,
1090        fndef: Ty<'tcx>,
1091        expected_safety: Option<hir::Safety>,
1092    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1093        let tcx = self.tcx;
1094
1095        let &ty::FnDef(def_id, _) = fndef.kind() else {
1096            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`sig_for_fn_def_coercion` called with non-fndef: {0:?}",
                fndef)));
};unreachable!("`sig_for_fn_def_coercion` called with non-fndef: {:?}", fndef);
1097        };
1098
1099        // Intrinsics are not coercible to function pointers
1100        if tcx.intrinsic(def_id).is_some() {
1101            return Err(TypeError::IntrinsicCast);
1102        }
1103
1104        let fn_attrs = tcx.codegen_fn_attrs(def_id);
1105        if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
    InlineAttr::Force { .. } => true,
    _ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1106            return Err(TypeError::ForceInlineCast);
1107        }
1108
1109        let sig = fndef.fn_sig(tcx);
1110        let sig = if fn_attrs.safe_target_features {
1111            // Allow the coercion if the current function has all the features that would be
1112            // needed to call the coercee safely.
1113            match tcx.adjust_target_feature_sig(def_id, sig, self.body_id.into()) {
1114                Some(adjusted_sig) => adjusted_sig,
1115                None if #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
    Some(hir::Safety::Safe) => true,
    _ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1116                    return Err(TypeError::TargetFeatureCast(def_id));
1117                }
1118                None => sig,
1119            }
1120        } else {
1121            sig
1122        };
1123
1124        if sig.safety().is_safe() && #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
    Some(hir::Safety::Unsafe) => true,
    _ => false,
}matches!(expected_safety, Some(hir::Safety::Unsafe)) {
1125            Ok(tcx.safe_to_unsafe_sig(sig))
1126        } else {
1127            Ok(sig)
1128        }
1129    }
1130
1131    fn sig_for_closure_coercion(
1132        &self,
1133        closure: Ty<'tcx>,
1134        expected_safety: Option<hir::Safety>,
1135        closure_upvars_terr: TypeError<'tcx>,
1136    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1137        let tcx = self.tcx;
1138
1139        let ty::Closure(closure_def, closure_args) = closure.kind() else {
1140            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`sig_for_closure_coercion` called with non closure ty: {0:?}",
                closure)));
};unreachable!("`sig_for_closure_coercion` called with non closure ty: {:?}", closure);
1141        };
1142
1143        // At this point we haven't done capture analysis, which means
1144        // that the ClosureArgs just contains an inference variable instead
1145        // of tuple of captured types.
1146        //
1147        // All we care here is if any variable is being captured and not the exact paths,
1148        // so we check `upvars_mentioned` for root variables being captured.
1149        if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1150            return Err(closure_upvars_terr);
1151        }
1152
1153        // We coerce the closure, which has fn type
1154        //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
1155        // to
1156        //     `fn(arg0,arg1,...) -> _`
1157        // or
1158        //     `unsafe fn(arg0,arg1,...) -> _`
1159        let closure_sig = closure_args.as_closure().sig();
1160        Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1161    }
1162
1163    /// Given some expressions, their known unified type and another expression,
1164    /// tries to unify the types, potentially inserting coercions on any of the
1165    /// provided expressions and returns their LUB (aka "common supertype").
1166    ///
1167    /// This is really an internal helper. From outside the coercion
1168    /// module, you should instantiate a `CoerceMany` instance.
1169    fn try_find_coercion_lub(
1170        &self,
1171        cause: &ObligationCause<'tcx>,
1172        exprs: &[&'tcx hir::Expr<'tcx>],
1173        prev_ty: Ty<'tcx>,
1174        new: &hir::Expr<'_>,
1175        new_ty: Ty<'tcx>,
1176    ) -> RelateResult<'tcx, Ty<'tcx>> {
1177        let prev_ty = self.try_structurally_resolve_type(cause.span, prev_ty);
1178        let new_ty = self.try_structurally_resolve_type(new.span, new_ty);
1179        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1179",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1179u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub({0:?}, {1:?}, exprs={2:?} exprs)",
                                                    prev_ty, new_ty, exprs.len()) as &dyn Value))])
            });
    } else { ; }
};debug!(
1180            "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1181            prev_ty,
1182            new_ty,
1183            exprs.len()
1184        );
1185
1186        // Fast Path: don't go through the coercion logic if we're coercing
1187        // a type to itself. This is unfortunately quite perf relevant so
1188        // we do it even though it may mask bugs in the coercion logic.
1189        if prev_ty == new_ty {
1190            return Ok(prev_ty);
1191        }
1192
1193        let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1194        let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1195            // Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1196            // if they can just be lubbed.
1197            //
1198            // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1199            // we would erroneously coerce closures to fnptrs when attempting to
1200            // coerce a closure to itself.
1201            (ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1202                let lubbed_ty = self.commit_if_ok(|snapshot| {
1203                    let outer_universe = self.infcx.universe();
1204
1205                    // We need to eagerly handle nested obligations due to lazy norm.
1206                    let result = if self.next_trait_solver() {
1207                        let ocx = ObligationCtxt::new(self);
1208                        let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1209                        if ocx.try_evaluate_obligations().is_empty() {
1210                            Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1211                        } else {
1212                            Err(TypeError::Mismatch)
1213                        }
1214                    } else {
1215                        self.at(cause, self.param_env).lub(prev_ty, new_ty)
1216                    };
1217
1218                    self.leak_check(outer_universe, Some(snapshot))?;
1219                    result
1220                });
1221
1222                match lubbed_ty {
1223                    Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1224                    Err(_) => {
1225                        let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1226                        let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1227                        Some((a_sig, b_sig))
1228                    }
1229                }
1230            }
1231
1232            (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1233                let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1234                let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1235                Some((a_sig, b_sig))
1236            }
1237            // ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1238            // call using `lub` which is what will happen on the normal path.
1239            (ty::FnPtr(..), ty::FnPtr(..)) => None,
1240            _ => None,
1241        };
1242
1243        if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1244            // Allow coercing safe sigs to unsafe sigs
1245            if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1246                a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1247            } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1248                b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1249            };
1250
1251            // The signature must match.
1252            let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1253            let sig = self
1254                .at(cause, self.param_env)
1255                .lub(a_sig, b_sig)
1256                .map(|ok| self.register_infer_ok_obligations(ok))?;
1257
1258            // Reify both sides and return the reified fn pointer type.
1259            let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1260            let prev_adjustment = match prev_ty.kind() {
1261                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1262                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1263                _ => ::rustc_middle::util::bug::span_bug_fmt(cause.span,
    format_args!("should not try to coerce a {0} to a fn pointer", prev_ty))span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1264            };
1265            let next_adjustment = match new_ty.kind() {
1266                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1267                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1268                _ => ::rustc_middle::util::bug::span_bug_fmt(new.span,
    format_args!("should not try to coerce a {0} to a fn pointer", new_ty))span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1269            };
1270            for expr in exprs.iter() {
1271                self.apply_adjustments(
1272                    expr,
1273                    <[_]>::into_vec(::alloc::boxed::box_new([Adjustment {
                    kind: prev_adjustment.clone(),
                    target: fn_ptr,
                }]))vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1274                );
1275            }
1276            self.apply_adjustments(new, <[_]>::into_vec(::alloc::boxed::box_new([Adjustment {
                    kind: next_adjustment,
                    target: fn_ptr,
                }]))vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1277            return Ok(fn_ptr);
1278        }
1279
1280        // Configure a Coerce instance to compute the LUB.
1281        // We don't allow two-phase borrows on any autorefs this creates since we
1282        // probably aren't processing function arguments here and even if we were,
1283        // they're going to get autorefed again anyway and we can apply 2-phase borrows
1284        // at that time.
1285        //
1286        // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1287        // operate on values and not places, so a never coercion is valid.
1288        let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1289        coerce.use_lub = true;
1290
1291        // First try to coerce the new expression to the type of the previous ones,
1292        // but only if the new expression has no coercion already applied to it.
1293        let mut first_error = None;
1294        if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1295            let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1296            match result {
1297                Ok(ok) => {
1298                    let (adjustments, target) = self.register_infer_ok_obligations(ok);
1299                    self.apply_adjustments(new, adjustments);
1300                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1300",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1300u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce from new type {0:?} to previous type {1:?} ({2:?})",
                                                    new_ty, prev_ty, target) as &dyn Value))])
            });
    } else { ; }
};debug!(
1301                        "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1302                        new_ty, prev_ty, target
1303                    );
1304                    return Ok(target);
1305                }
1306                Err(e) => first_error = Some(e),
1307            }
1308        }
1309
1310        let ok = self
1311            .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1312            // Avoid giving strange errors on failed attempts.
1313            .map_err(|e| first_error.unwrap_or(e))?;
1314
1315        let (adjustments, target) = self.register_infer_ok_obligations(ok);
1316        for expr in exprs {
1317            self.apply_adjustments(expr, adjustments.clone());
1318        }
1319        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1319",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1319u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce previous type {0:?} to new type {1:?} ({2:?})",
                                                    prev_ty, new_ty, target) as &dyn Value))])
            });
    } else { ; }
};debug!(
1320            "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1321            prev_ty, new_ty, target
1322        );
1323        Ok(target)
1324    }
1325}
1326
1327/// Check whether `ty` can be coerced to `output_ty`.
1328/// Used from clippy.
1329pub fn can_coerce<'tcx>(
1330    tcx: TyCtxt<'tcx>,
1331    param_env: ty::ParamEnv<'tcx>,
1332    body_id: LocalDefId,
1333    ty: Ty<'tcx>,
1334    output_ty: Ty<'tcx>,
1335) -> bool {
1336    let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1337    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1338    fn_ctxt.may_coerce(ty, output_ty)
1339}
1340
1341/// CoerceMany encapsulates the pattern you should use when you have
1342/// many expressions that are all getting coerced to a common
1343/// type. This arises, for example, when you have a match (the result
1344/// of each arm is coerced to a common type). It also arises in less
1345/// obvious places, such as when you have many `break foo` expressions
1346/// that target the same loop, or the various `return` expressions in
1347/// a function.
1348///
1349/// The basic protocol is as follows:
1350///
1351/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1352///   This will also serve as the "starting LUB". The expectation is
1353///   that this type is something which all of the expressions *must*
1354///   be coercible to. Use a fresh type variable if needed.
1355/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1356///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1357///     unit. This happens for example if you have a `break` with no expression,
1358///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1359///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1360///     from you so that you don't have to worry your pretty head about it.
1361///     But if an error is reported, the final type will be `err`.
1362///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1363///     previously coerced expressions.
1364/// - When all done, invoke `complete()`. This will return the LUB of
1365///   all your expressions.
1366///   - WARNING: I don't believe this final type is guaranteed to be
1367///     related to your initial `expected_ty` in any particular way,
1368///     although it will typically be a subtype, so you should check it.
1369///     Check the note below for more details.
1370///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1371///     previously coerced expressions.
1372///
1373/// Example:
1374///
1375/// ```ignore (illustrative)
1376/// let mut coerce = CoerceMany::new(expected_ty);
1377/// for expr in exprs {
1378///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1379///     coerce.coerce(fcx, &cause, expr, expr_ty);
1380/// }
1381/// let final_ty = coerce.complete(fcx);
1382/// ```
1383///
1384/// NOTE: Why does the `expected_ty` participate in the LUB?
1385/// When coercing, each branch should use the following expectations for type inference:
1386/// - The branch can be coerced to the expected type of the match/if/whatever.
1387/// - The branch can be coercion lub'd with the types of the previous branches.
1388/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1389/// but adding and using this feels very challenging.
1390/// What we instead do is to use the expected type of the match/if/whatever as
1391/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1392/// "types from previous branches" as the coercion target, which can contains both expectations.
1393///
1394/// Two concerns with this approach:
1395/// - We may have incompatible `final_ty` if that lub is different from the expected
1396///   type of the match. However, in this case coercing the final type of the
1397///   `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1398/// - We may constrain the `expected_ty` too early. For some branches with
1399///   type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1400///   `(a lub b) lub expected_ty`. They should be the same type. However,
1401///   `a lub expected_ty` may constrain inference variables in `expected_ty`.
1402///   In this case the difference does matter and we get actually incorrect results.
1403/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1404/// the expected type of the match when computing the types of its branches.
1405pub(crate) struct CoerceMany<'tcx> {
1406    expected_ty: Ty<'tcx>,
1407    final_ty: Option<Ty<'tcx>>,
1408    expressions: Vec<&'tcx hir::Expr<'tcx>>,
1409}
1410
1411impl<'tcx> CoerceMany<'tcx> {
1412    /// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1413    /// coercion sites is known before hand, consider `with_capacity()` instead
1414    /// to avoid allocation.
1415    pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1416        Self::with_capacity(expected_ty, 1)
1417    }
1418
1419    /// Creates a `CoerceMany` with a given capacity.
1420    pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1421        CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1422    }
1423
1424    /// Returns the "expected type" with which this coercion was
1425    /// constructed. This represents the "downward propagated" type
1426    /// that was given to us at the start of typing whatever construct
1427    /// we are typing (e.g., the match expression).
1428    ///
1429    /// Typically, this is used as the expected type when
1430    /// type-checking each of the alternative expressions whose types
1431    /// we are trying to merge.
1432    pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1433        self.expected_ty
1434    }
1435
1436    /// Returns the current "merged type", representing our best-guess
1437    /// at the LUB of the expressions we've seen so far (if any). This
1438    /// isn't *final* until you call `self.complete()`, which will return
1439    /// the merged type.
1440    pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1441        self.final_ty.unwrap_or(self.expected_ty)
1442    }
1443
1444    /// Indicates that the value generated by `expression`, which is
1445    /// of type `expression_ty`, is one of the possibilities that we
1446    /// could coerce from. This will record `expression`, and later
1447    /// calls to `coerce` may come back and add adjustments and things
1448    /// if necessary.
1449    pub(crate) fn coerce<'a>(
1450        &mut self,
1451        fcx: &FnCtxt<'a, 'tcx>,
1452        cause: &ObligationCause<'tcx>,
1453        expression: &'tcx hir::Expr<'tcx>,
1454        expression_ty: Ty<'tcx>,
1455    ) {
1456        self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1457    }
1458
1459    /// Indicates that one of the inputs is a "forced unit". This
1460    /// occurs in a case like `if foo { ... };`, where the missing else
1461    /// generates a "forced unit". Another example is a `loop { break;
1462    /// }`, where the `break` has no argument expression. We treat
1463    /// these cases slightly differently for error-reporting
1464    /// purposes. Note that these tend to correspond to cases where
1465    /// the `()` expression is implicit in the source, and hence we do
1466    /// not take an expression argument.
1467    ///
1468    /// The `augment_error` gives you a chance to extend the error
1469    /// message, in case any results (e.g., we use this to suggest
1470    /// removing a `;`).
1471    pub(crate) fn coerce_forced_unit<'a>(
1472        &mut self,
1473        fcx: &FnCtxt<'a, 'tcx>,
1474        cause: &ObligationCause<'tcx>,
1475        augment_error: impl FnOnce(&mut Diag<'_>),
1476        label_unit_as_expected: bool,
1477    ) {
1478        self.coerce_inner(
1479            fcx,
1480            cause,
1481            None,
1482            fcx.tcx.types.unit,
1483            augment_error,
1484            label_unit_as_expected,
1485        )
1486    }
1487
1488    /// The inner coercion "engine". If `expression` is `None`, this
1489    /// is a forced-unit case, and hence `expression_ty` must be
1490    /// `Nil`.
1491    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("coerce_inner",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1491u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&["cause",
                                                    "expression", "expression_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if expression_ty.is_ty_var() {
                expression_ty = fcx.infcx.shallow_resolve(expression_ty);
            }
            if let Err(guar) =
                    (expression_ty, self.merged_ty()).error_reported() {
                self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
                return;
            }
            let (expected, found) =
                if label_expression_as_expected {
                    (expression_ty, self.merged_ty())
                } else { (self.merged_ty(), expression_ty) };
            let result =
                if let Some(expression) = expression {
                    if self.expressions.is_empty() {
                        fcx.coerce(expression, expression_ty, self.expected_ty,
                            AllowTwoPhase::No, Some(cause.clone()))
                    } else {
                        fcx.try_find_coercion_lub(cause, &self.expressions,
                            self.merged_ty(), expression, expression_ty)
                    }
                } else {
                    if !expression_ty.is_unit() {
                        {
                            ::core::panicking::panic_fmt(format_args!("if let hack without unit type"));
                        }
                    };
                    fcx.at(cause,
                                fcx.param_env).eq(DefineOpaqueTypes::Yes, expected,
                            found).map(|infer_ok|
                            {
                                fcx.register_infer_ok_obligations(infer_ok);
                                expression_ty
                            })
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1582",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1582u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&["result"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&result) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            match result {
                Ok(v) => {
                    self.final_ty = Some(v);
                    if let Some(e) = expression { self.expressions.push(e); }
                }
                Err(coercion_error) => {
                    fcx.set_tainted_by_errors(fcx.dcx().span_delayed_bug(cause.span,
                            "coercion error but no error emitted"));
                    let (expected, found) =
                        fcx.resolve_vars_if_possible((expected, found));
                    let mut err;
                    let mut unsized_return = false;
                    match *cause.code() {
                        ObligationCauseCode::ReturnNoExpression => {
                            err =
                                {
                                    fcx.dcx().struct_span_err(cause.span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("`return;` in a function whose return type is not `()`"))
                                                })).with_code(E0069)
                                };
                            if let Some(value) =
                                    fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found) {
                                err.span_suggestion_verbose(cause.span.shrink_to_hi(),
                                    "give the `return` a value of the expected type",
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!(" {0}", value))
                                        }), Applicability::HasPlaceholders);
                            }
                            err.span_label(cause.span, "return type is not `()`");
                        }
                        ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
                            err =
                                self.report_return_mismatched_types(cause, expected, found,
                                    coercion_error, fcx, blk_id, expression);
                            unsized_return = self.is_return_ty_definitely_unsized(fcx);
                        }
                        ObligationCauseCode::ReturnValue(return_expr_id) => {
                            err =
                                self.report_return_mismatched_types(cause, expected, found,
                                    coercion_error, fcx, return_expr_id, expression);
                            unsized_return = self.is_return_ty_definitely_unsized(fcx);
                        }
                        ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
                            arm_span,
                            arm_ty,
                            prior_arm_ty,
                            ref prior_non_diverging_arms,
                            tail_defines_return_position_impl_trait: Some(rpit_def_id),
                            .. }) => {
                            err =
                                fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
                                    expected, found, coercion_error);
                            if prior_non_diverging_arms.len() > 0 {
                                self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
                                    &mut err, rpit_def_id, arm_ty, prior_arm_ty,
                                    prior_non_diverging_arms.iter().chain(std::iter::once(&arm_span)).copied());
                            }
                        }
                        ObligationCauseCode::IfExpression {
                            expr_id,
                            tail_defines_return_position_impl_trait: Some(rpit_def_id) }
                            => {
                            let hir::Node::Expr(hir::Expr {
                                    kind: hir::ExprKind::If(_, then_expr, Some(else_expr)), ..
                                    }) =
                                fcx.tcx.hir_node(expr_id) else {
                                    ::core::panicking::panic("internal error: entered unreachable code");
                                };
                            err =
                                fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
                                    expected, found, coercion_error);
                            let then_span =
                                fcx.find_block_span_from_hir_id(then_expr.hir_id);
                            let else_span =
                                fcx.find_block_span_from_hir_id(else_expr.hir_id);
                            if then_span != then_expr.span &&
                                    else_span != else_expr.span {
                                let then_ty =
                                    fcx.typeck_results.borrow().expr_ty(then_expr);
                                let else_ty =
                                    fcx.typeck_results.borrow().expr_ty(else_expr);
                                self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
                                    &mut err, rpit_def_id, then_ty, else_ty,
                                    [then_span, else_span].into_iter());
                            }
                        }
                        _ => {
                            err =
                                fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
                                    expected, found, coercion_error);
                        }
                    }
                    augment_error(&mut err);
                    if let Some(expr) = expression {
                        if let hir::ExprKind::Loop(_, _, loop_src @
                                (hir::LoopSource::While | hir::LoopSource::ForLoop), _) =
                                expr.kind {
                            let loop_type =
                                if loop_src == hir::LoopSource::While {
                                    "`while` loops"
                                } else { "`for` loops" };
                            err.note(::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0} evaluate to unit type `()`",
                                                loop_type))
                                    }));
                        }
                        fcx.emit_coerce_suggestions(&mut err, expr, found, expected,
                            None, Some(coercion_error));
                    }
                    let reported = err.emit_unless_delay(unsized_return);
                    self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
                }
            }
        }
    }
}#[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
1492    pub(crate) fn coerce_inner<'a>(
1493        &mut self,
1494        fcx: &FnCtxt<'a, 'tcx>,
1495        cause: &ObligationCause<'tcx>,
1496        expression: Option<&'tcx hir::Expr<'tcx>>,
1497        mut expression_ty: Ty<'tcx>,
1498        augment_error: impl FnOnce(&mut Diag<'_>),
1499        label_expression_as_expected: bool,
1500    ) {
1501        // Incorporate whatever type inference information we have
1502        // until now; in principle we might also want to process
1503        // pending obligations, but doing so should only improve
1504        // compatibility (hopefully that is true) by helping us
1505        // uncover never types better.
1506        if expression_ty.is_ty_var() {
1507            expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1508        }
1509
1510        // If we see any error types, just propagate that error
1511        // upwards.
1512        if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1513            self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1514            return;
1515        }
1516
1517        let (expected, found) = if label_expression_as_expected {
1518            // In the case where this is a "forced unit", like
1519            // `break`, we want to call the `()` "expected"
1520            // since it is implied by the syntax.
1521            // (Note: not all force-units work this way.)"
1522            (expression_ty, self.merged_ty())
1523        } else {
1524            // Otherwise, the "expected" type for error
1525            // reporting is the current unification type,
1526            // which is basically the LUB of the expressions
1527            // we've seen so far (combined with the expected
1528            // type)
1529            (self.merged_ty(), expression_ty)
1530        };
1531
1532        // Handle the actual type unification etc.
1533        let result = if let Some(expression) = expression {
1534            if self.expressions.is_empty() {
1535                // Special-case the first expression we are coercing.
1536                // To be honest, I'm not entirely sure why we do this.
1537                // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1538                fcx.coerce(
1539                    expression,
1540                    expression_ty,
1541                    self.expected_ty,
1542                    AllowTwoPhase::No,
1543                    Some(cause.clone()),
1544                )
1545            } else {
1546                fcx.try_find_coercion_lub(
1547                    cause,
1548                    &self.expressions,
1549                    self.merged_ty(),
1550                    expression,
1551                    expression_ty,
1552                )
1553            }
1554        } else {
1555            // this is a hack for cases where we default to `()` because
1556            // the expression etc has been omitted from the source. An
1557            // example is an `if let` without an else:
1558            //
1559            //     if let Some(x) = ... { }
1560            //
1561            // we wind up with a second match arm that is like `_ =>
1562            // ()`. That is the case we are considering here. We take
1563            // a different path to get the right "expected, found"
1564            // message and so forth (and because we know that
1565            // `expression_ty` will be unit).
1566            //
1567            // Another example is `break` with no argument expression.
1568            assert!(expression_ty.is_unit(), "if let hack without unit type");
1569            fcx.at(cause, fcx.param_env)
1570                .eq(
1571                    // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1572                    DefineOpaqueTypes::Yes,
1573                    expected,
1574                    found,
1575                )
1576                .map(|infer_ok| {
1577                    fcx.register_infer_ok_obligations(infer_ok);
1578                    expression_ty
1579                })
1580        };
1581
1582        debug!(?result);
1583        match result {
1584            Ok(v) => {
1585                self.final_ty = Some(v);
1586                if let Some(e) = expression {
1587                    self.expressions.push(e);
1588                }
1589            }
1590            Err(coercion_error) => {
1591                // Mark that we've failed to coerce the types here to suppress
1592                // any superfluous errors we might encounter while trying to
1593                // emit or provide suggestions on how to fix the initial error.
1594                fcx.set_tainted_by_errors(
1595                    fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1596                );
1597                let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1598
1599                let mut err;
1600                let mut unsized_return = false;
1601                match *cause.code() {
1602                    ObligationCauseCode::ReturnNoExpression => {
1603                        err = struct_span_code_err!(
1604                            fcx.dcx(),
1605                            cause.span,
1606                            E0069,
1607                            "`return;` in a function whose return type is not `()`"
1608                        );
1609                        if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1610                        {
1611                            err.span_suggestion_verbose(
1612                                cause.span.shrink_to_hi(),
1613                                "give the `return` a value of the expected type",
1614                                format!(" {value}"),
1615                                Applicability::HasPlaceholders,
1616                            );
1617                        }
1618                        err.span_label(cause.span, "return type is not `()`");
1619                    }
1620                    ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1621                        err = self.report_return_mismatched_types(
1622                            cause,
1623                            expected,
1624                            found,
1625                            coercion_error,
1626                            fcx,
1627                            blk_id,
1628                            expression,
1629                        );
1630                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1631                    }
1632                    ObligationCauseCode::ReturnValue(return_expr_id) => {
1633                        err = self.report_return_mismatched_types(
1634                            cause,
1635                            expected,
1636                            found,
1637                            coercion_error,
1638                            fcx,
1639                            return_expr_id,
1640                            expression,
1641                        );
1642                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1643                    }
1644                    ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1645                        arm_span,
1646                        arm_ty,
1647                        prior_arm_ty,
1648                        ref prior_non_diverging_arms,
1649                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1650                        ..
1651                    }) => {
1652                        err = fcx.err_ctxt().report_mismatched_types(
1653                            cause,
1654                            fcx.param_env,
1655                            expected,
1656                            found,
1657                            coercion_error,
1658                        );
1659                        // Check that we're actually in the second or later arm
1660                        if prior_non_diverging_arms.len() > 0 {
1661                            self.suggest_boxing_tail_for_return_position_impl_trait(
1662                                fcx,
1663                                &mut err,
1664                                rpit_def_id,
1665                                arm_ty,
1666                                prior_arm_ty,
1667                                prior_non_diverging_arms
1668                                    .iter()
1669                                    .chain(std::iter::once(&arm_span))
1670                                    .copied(),
1671                            );
1672                        }
1673                    }
1674                    ObligationCauseCode::IfExpression {
1675                        expr_id,
1676                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1677                    } => {
1678                        let hir::Node::Expr(hir::Expr {
1679                            kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1680                            ..
1681                        }) = fcx.tcx.hir_node(expr_id)
1682                        else {
1683                            unreachable!();
1684                        };
1685                        err = fcx.err_ctxt().report_mismatched_types(
1686                            cause,
1687                            fcx.param_env,
1688                            expected,
1689                            found,
1690                            coercion_error,
1691                        );
1692                        let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1693                        let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1694                        // Don't suggest wrapping whole block in `Box::new`.
1695                        if then_span != then_expr.span && else_span != else_expr.span {
1696                            let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1697                            let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1698                            self.suggest_boxing_tail_for_return_position_impl_trait(
1699                                fcx,
1700                                &mut err,
1701                                rpit_def_id,
1702                                then_ty,
1703                                else_ty,
1704                                [then_span, else_span].into_iter(),
1705                            );
1706                        }
1707                    }
1708                    _ => {
1709                        err = fcx.err_ctxt().report_mismatched_types(
1710                            cause,
1711                            fcx.param_env,
1712                            expected,
1713                            found,
1714                            coercion_error,
1715                        );
1716                    }
1717                }
1718
1719                augment_error(&mut err);
1720
1721                if let Some(expr) = expression {
1722                    if let hir::ExprKind::Loop(
1723                        _,
1724                        _,
1725                        loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1726                        _,
1727                    ) = expr.kind
1728                    {
1729                        let loop_type = if loop_src == hir::LoopSource::While {
1730                            "`while` loops"
1731                        } else {
1732                            "`for` loops"
1733                        };
1734
1735                        err.note(format!("{loop_type} evaluate to unit type `()`"));
1736                    }
1737
1738                    fcx.emit_coerce_suggestions(
1739                        &mut err,
1740                        expr,
1741                        found,
1742                        expected,
1743                        None,
1744                        Some(coercion_error),
1745                    );
1746                }
1747
1748                let reported = err.emit_unless_delay(unsized_return);
1749
1750                self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1751            }
1752        }
1753    }
1754
1755    fn suggest_boxing_tail_for_return_position_impl_trait(
1756        &self,
1757        fcx: &FnCtxt<'_, 'tcx>,
1758        err: &mut Diag<'_>,
1759        rpit_def_id: LocalDefId,
1760        a_ty: Ty<'tcx>,
1761        b_ty: Ty<'tcx>,
1762        arm_spans: impl Iterator<Item = Span>,
1763    ) {
1764        let compatible = |ty: Ty<'tcx>| {
1765            fcx.probe(|_| {
1766                let ocx = ObligationCtxt::new(fcx);
1767                ocx.register_obligations(
1768                    fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1769                        let predicate = clause
1770                            .kind()
1771                            .map_bound(|clause| match clause {
1772                                ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1773                                    trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1774                                )),
1775                                ty::ClauseKind::Projection(proj_pred) => {
1776                                    Some(ty::ClauseKind::Projection(
1777                                        proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1778                                    ))
1779                                }
1780                                _ => None,
1781                            })
1782                            .transpose()?;
1783                        Some(Obligation::new(
1784                            fcx.tcx,
1785                            ObligationCause::dummy(),
1786                            fcx.param_env,
1787                            predicate,
1788                        ))
1789                    }),
1790                );
1791                ocx.try_evaluate_obligations().is_empty()
1792            })
1793        };
1794
1795        if !compatible(a_ty) || !compatible(b_ty) {
1796            return;
1797        }
1798
1799        let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1800        err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1801            start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1802            end_sp: rpid_def_span.shrink_to_hi(),
1803        });
1804
1805        let (starts, ends) =
1806            arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1807        err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1808    }
1809
1810    fn report_return_mismatched_types<'infcx>(
1811        &self,
1812        cause: &ObligationCause<'tcx>,
1813        expected: Ty<'tcx>,
1814        found: Ty<'tcx>,
1815        ty_err: TypeError<'tcx>,
1816        fcx: &'infcx FnCtxt<'_, 'tcx>,
1817        block_or_return_id: hir::HirId,
1818        expression: Option<&'tcx hir::Expr<'tcx>>,
1819    ) -> Diag<'infcx> {
1820        let mut err =
1821            fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1822
1823        let due_to_block = #[allow(non_exhaustive_omitted_patterns)] match fcx.tcx.hir_node(block_or_return_id)
    {
    hir::Node::Block(..) => true,
    _ => false,
}matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..));
1824        let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1825        if let Some(expr) = expression
1826            && let hir::Node::Expr(&hir::Expr {
1827                kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1828                ..
1829            }) = parent
1830        {
1831            let needs_block =
1832                !#[allow(non_exhaustive_omitted_patterns)] match fcx.tcx.hir_body(body).value.kind
    {
    hir::ExprKind::Block(..) => true,
    _ => false,
}matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..));
1833            fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1834        }
1835        // Verify that this is a tail expression of a function, otherwise the
1836        // label pointing out the cause for the type coercion will be wrong
1837        // as prior return coercions would not be relevant (#57664).
1838        if let Some(expr) = expression
1839            && due_to_block
1840        {
1841            fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
1842            let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1843                &mut err,
1844                expr,
1845                expected,
1846                found,
1847                block_or_return_id,
1848            );
1849            if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1850                && expected.is_unit()
1851                && !pointing_at_return_type
1852                // If the block is from an external macro or try (`?`) desugaring, then
1853                // do not suggest adding a semicolon, because there's nowhere to put it.
1854                // See issues #81943 and #87051.
1855                // Similarly, if the block is from a loop desugaring, then also do not
1856                // suggest adding a semicolon. See issue #150850.
1857                && cond_expr.span.desugaring_kind().is_none()
1858                && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1859                && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
    _ => false,
}matches!(
1860                    cond_expr.kind,
1861                    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1862                )
1863            {
1864                if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
1865                    cause.code()
1866                    && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
1867                    && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
1868                    && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
1869                    && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
1870                {
1871                    err.span_label(
1872                        cond_expr.span,
1873                        "`if` expressions without `else` arms expect their inner expression to be `()`",
1874                    );
1875                } else {
1876                    err.span_label(cond_expr.span, "expected this to be `()`");
1877                }
1878                if expr.can_have_side_effects() {
1879                    fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1880                }
1881            }
1882        }
1883
1884        // If this is due to an explicit `return`, suggest adding a return type.
1885        if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1886            && !due_to_block
1887        {
1888            fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1889        }
1890
1891        // If this is due to a block, then maybe we forgot a `return`/`break`.
1892        if due_to_block
1893            && let Some(expr) = expression
1894            && let Some(parent_fn_decl) =
1895                fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1896        {
1897            fcx.suggest_missing_break_or_return_expr(
1898                &mut err,
1899                expr,
1900                parent_fn_decl,
1901                expected,
1902                found,
1903                block_or_return_id,
1904                fcx.body_id,
1905            );
1906        }
1907
1908        let ret_coercion_span = fcx.ret_coercion_span.get();
1909
1910        if let Some(sp) = ret_coercion_span
1911            // If the closure has an explicit return type annotation, or if
1912            // the closure's return type has been inferred from outside
1913            // requirements (such as an Fn* trait bound), then a type error
1914            // may occur at the first return expression we see in the closure
1915            // (if it conflicts with the declared return type). Skip adding a
1916            // note in this case, since it would be incorrect.
1917            && let Some(fn_sig) = fcx.body_fn_sig()
1918            && fn_sig.output().is_ty_var()
1919        {
1920            err.span_note(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("return type inferred to be `{0}` here",
                expected))
    })format!("return type inferred to be `{expected}` here"));
1921        }
1922
1923        err
1924    }
1925
1926    /// Checks whether the return type is unsized via an obligation, which makes
1927    /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1928    /// false but technically valid for typeck.
1929    fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1930        if let Some(sig) = fcx.body_fn_sig() {
1931            !fcx.predicate_may_hold(&Obligation::new(
1932                fcx.tcx,
1933                ObligationCause::dummy(),
1934                fcx.param_env,
1935                ty::TraitRef::new(
1936                    fcx.tcx,
1937                    fcx.tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP),
1938                    [sig.output()],
1939                ),
1940            ))
1941        } else {
1942            false
1943        }
1944    }
1945
1946    pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1947        if let Some(final_ty) = self.final_ty {
1948            final_ty
1949        } else {
1950            // If we only had inputs that were of type `!` (or no
1951            // inputs at all), then the final type is `!`.
1952            if !self.expressions.is_empty() {
    ::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
1953            fcx.tcx.types.never
1954        }
1955    }
1956}
1957
1958/// Recursively visit goals to decide whether an unsizing is possible.
1959/// `Break`s when it isn't, and an error should be raised.
1960/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
1961struct CoerceVisitor<'a, 'tcx> {
1962    fcx: &'a FnCtxt<'a, 'tcx>,
1963    span: Span,
1964}
1965
1966impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
1967    type Result = ControlFlow<()>;
1968
1969    fn span(&self) -> Span {
1970        self.span
1971    }
1972
1973    fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
1974        let Some(pred) = goal.goal().predicate.as_trait_clause() else {
1975            return ControlFlow::Continue(());
1976        };
1977
1978        // Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
1979        // Otherwise there's nothing to do.
1980        if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
1981            && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
1982        {
1983            return ControlFlow::Continue(());
1984        }
1985
1986        match goal.result() {
1987            // If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
1988            Ok(Certainty::Yes) => ControlFlow::Continue(()),
1989            Err(NoSolution) => {
1990                // Even if we find no solution, continue recursing if we find a single candidate
1991                // for which we're shallowly certain it holds to get the right error source.
1992                if let [only_candidate] = &goal.candidates()[..]
1993                    && only_candidate.shallow_certainty() == Certainty::Yes
1994                {
1995                    only_candidate.visit_nested_no_probe(self)
1996                } else {
1997                    ControlFlow::Break(())
1998                }
1999            }
2000            Ok(Certainty::Maybe { .. }) => {
2001                // FIXME: structurally normalize?
2002                if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2003                    && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2004                    && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2005                    && self.fcx.type_var_is_sized(vid)
2006                {
2007                    // We get here when trying to unsize a type variable to a `dyn Trait`,
2008                    // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2009                    // If the variable weren't sized, we may not need an unsizing coercion.
2010                    // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2011                    ControlFlow::Continue(())
2012                } else if let Some(cand) = goal.unique_applicable_candidate()
2013                    && cand.shallow_certainty() == Certainty::Yes
2014                {
2015                    cand.visit_nested_no_probe(self)
2016                } else {
2017                    ControlFlow::Break(())
2018                }
2019            }
2020        }
2021    }
2022}