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 as hir;
43use rustc_hir::attrs::InlineAttr;
44use rustc_hir::attrs::lang_items::LangItem;
45use rustc_hir::def_id::{DefId, LocalDefId};
46use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
47use rustc_infer::infer::relate::RelateResult;
48use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
49use rustc_infer::traits::{
50    MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
51};
52use rustc_middle::span_bug;
53use rustc_middle::ty::adjustment::{
54    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
55    PointerCoercion,
56};
57use rustc_middle::ty::error::TypeError;
58use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
59use rustc_span::{BytePos, DUMMY_SP, Span};
60use rustc_trait_selection::infer::InferCtxtExt as _;
61use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
62use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
63use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
64use rustc_trait_selection::traits::{
65    self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
66};
67use smallvec::{SmallVec, smallvec};
68use tracing::{debug, instrument};
69
70use crate::FnCtxt;
71use crate::diagnostics::SuggestBoxingForReturnImplTrait;
72
73struct Coerce<'a, 'tcx> {
74    fcx: &'a FnCtxt<'a, 'tcx>,
75    cause: ObligationCause<'tcx>,
76    use_lub: bool,
77    /// Determines whether or not allow_two_phase_borrow is set on any
78    /// autoref adjustments we create while coercing. We don't want to
79    /// allow deref coercions to create two-phase borrows, at least initially,
80    /// but we do need two-phase borrows for function argument reborrows.
81    /// See #47489 and #48598
82    /// See docs on the "AllowTwoPhase" type for a more detailed discussion
83    allow_two_phase: AllowTwoPhase,
84    /// Whether we allow `NeverToAny` coercions. This is unsound if we're
85    /// coercing a place expression without it counting as a read in the MIR.
86    /// This is a side-effect of HIR not really having a great distinction
87    /// between places and values.
88    coerce_never: bool,
89}
90
91impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
92    type Target = FnCtxt<'a, 'tcx>;
93    fn deref(&self) -> &Self::Target {
94        self.fcx
95    }
96}
97
98type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
99
100/// Coercing a mutable reference to an immutable works, while
101/// coercing `&T` to `&mut T` should be forbidden.
102fn coerce_mutbls<'tcx>(
103    from_mutbl: hir::Mutability,
104    to_mutbl: hir::Mutability,
105) -> RelateResult<'tcx, ()> {
106    if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
107}
108
109/// This always returns `Ok(...)`.
110fn success<'tcx>(
111    adj: Vec<Adjustment<'tcx>>,
112    target: Ty<'tcx>,
113    obligations: PredicateObligations<'tcx>,
114) -> CoerceResult<'tcx> {
115    Ok(InferOk { value: (adj, target), obligations })
116}
117
118/// Data extracted from a reference (pinned or not) for coercion to a reference (pinned or not).
119struct CoerceMaybePinnedRef<'tcx> {
120    /// coercion source, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
121    a: Ty<'tcx>,
122    /// coercion target, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
123    b: Ty<'tcx>,
124    /// referent type of the source
125    a_ty: Ty<'tcx>,
126    /// pinnedness of the source
127    a_pin: ty::Pinnedness,
128    /// mutability of the source
129    a_mut: ty::Mutability,
130    /// region of the source
131    a_r: ty::Region<'tcx>,
132    /// pinnedness of the target
133    b_pin: ty::Pinnedness,
134    /// mutability of the target
135    b_mut: ty::Mutability,
136}
137
138/// Whether to force a leak check to occur in `Coerce::unify_raw`.
139/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
140///
141/// FIXME: We may want to change type relations to always leak-check
142/// after exiting a binder, at which point we will always do so and
143/// no longer need to handle this explicitly
144enum ForceLeakCheck {
145    Yes,
146    No,
147}
148
149impl<'f, 'tcx> Coerce<'f, 'tcx> {
150    fn new(
151        fcx: &'f FnCtxt<'f, 'tcx>,
152        cause: ObligationCause<'tcx>,
153        allow_two_phase: AllowTwoPhase,
154        coerce_never: bool,
155    ) -> Self {
156        Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
157    }
158
159    fn unify_raw(
160        &self,
161        a: Ty<'tcx>,
162        b: Ty<'tcx>,
163        leak_check: ForceLeakCheck,
164    ) -> InferResult<'tcx, Ty<'tcx>> {
165        {
    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:165",
                        "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(165u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
                                                    a, b, self.use_lub) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
166        self.commit_if_ok(|snapshot| {
167            let outer_universe = self.infcx.universe();
168
169            let at = self.at(&self.cause, self.fcx.param_env);
170
171            let res = if self.use_lub {
172                at.lub(b, a)
173            } else {
174                at.sup(DefineOpaqueTypes::Yes, b, a)
175                    .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
176            };
177
178            // In the new solver, lazy norm may allow us to shallowly equate
179            // more types, but we emit possibly impossible-to-satisfy obligations.
180            // Filter these cases out to make sure our coercion is more accurate.
181            let res = match res {
182                Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
183                    let ocx = ObligationCtxt::new(self);
184                    ocx.register_obligations(obligations);
185                    if ocx.try_evaluate_obligations().no_errors() {
186                        Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
187                    } else {
188                        Err(TypeError::Mismatch)
189                    }
190                }
191                res => res,
192            };
193
194            // We leak check here mostly because lub operations are
195            // kind of scuffed around binders. Instead of computing an actual
196            // lub'd binder we instead:
197            // - Equate the binders
198            // - Return the lhs of the lub operation
199            //
200            // This may lead to incomplete type inference for the resulting type
201            // of a `match` or `if .. else`, etc. This is a backwards compat
202            // hazard for if/when we start handling `lub` more correctly.
203            //
204            // In order to actually ensure that equating the binders *does*
205            // result in equal binders, and that the lhs is actually a supertype
206            // of the rhs, we must perform a leak check here.
207            if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
    ForceLeakCheck::Yes => true,
    _ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
208                self.leak_check(outer_universe, Some(snapshot))?;
209            }
210
211            res
212        })
213    }
214
215    /// Unify two types (using sub or lub).
216    fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
217        self.unify_raw(a, b, leak_check)
218            .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
219    }
220
221    /// Unify two types (using sub or lub) and produce a specific coercion.
222    fn unify_and(
223        &self,
224        a: Ty<'tcx>,
225        b: Ty<'tcx>,
226        adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
227        final_adjustment: Adjust,
228        leak_check: ForceLeakCheck,
229    ) -> CoerceResult<'tcx> {
230        self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
231            success(
232                adjustments
233                    .into_iter()
234                    .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
235                    .collect(),
236                ty,
237                obligations,
238            )
239        })
240    }
241
242    x;#[instrument(skip(self), ret)]
243    fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
244        // First, remove any resolved type variables (at the top level, at least):
245        let a = self.shallow_resolve(a);
246        let b = self.shallow_resolve(b);
247        debug!("Coerce.tys({:?} => {:?})", a, b);
248
249        // Coercing from `!` to any type is allowed:
250        if a.is_never() {
251            if self.coerce_never {
252                return success(
253                    vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
254                    b,
255                    PredicateObligations::new(),
256                );
257            } else {
258                // Otherwise the only coercion we can do is unification.
259                return self.unify(a, b, ForceLeakCheck::No);
260            }
261        }
262
263        // Coercing *from* an unresolved inference variable means that
264        // we have no information about the source type. This will always
265        // ultimately fall back to some form of subtyping.
266        if a.is_ty_var() {
267            return self.coerce_from_inference_variable(a, b);
268        }
269
270        // Consider coercing the subtype to a DST
271        //
272        // NOTE: this is wrapped in a `commit_if_ok` because it creates
273        // a "spurious" type variable, and we don't want to have that
274        // type variable in memory if the coercion fails.
275        let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
276        match unsize {
277            Ok(_) => {
278                debug!("coerce: unsize successful");
279                return unsize;
280            }
281            Err(error) => {
282                debug!(?error, "coerce: unsize failed");
283            }
284        }
285
286        // Examine the target type and consider type-specific coercions, such
287        // as auto-borrowing, coercing pointer mutability, pin-ergonomics, or
288        // generic reborrow.
289        match *b.kind() {
290            ty::RawPtr(_, b_mutbl) => {
291                return self.coerce_to_raw_ptr(a, b, b_mutbl);
292            }
293            ty::Ref(r_b, _, mutbl_b) => {
294                if let Some(pin_ref_to_ref) = self.maybe_pin_ref_to_ref(a, b) {
295                    return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
296                }
297                return self.coerce_to_ref(a, b, r_b, mutbl_b);
298            }
299            _ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
300                return self.coerce_to_pin_ref(to_pin_ref);
301            }
302            ty::Adt(_, _)
303                if self.tcx.features().reborrow()
304                    && self
305                        .fcx
306                        .infcx
307                        .type_implements_trait(
308                            self.tcx
309                                .lang_items()
310                                .reborrow()
311                                .expect("Unexpectedly using core/std without reborrow"),
312                            [b],
313                            self.fcx.param_env,
314                        )
315                        .must_apply_modulo_regions() =>
316            {
317                let reborrow_coerce = self.commit_if_ok(|_| self.coerce_reborrow(a, b));
318                if reborrow_coerce.is_ok() {
319                    return reborrow_coerce;
320                }
321            }
322            _ => {}
323        }
324
325        match *a.kind() {
326            ty::FnDef(..) => {
327                // Function items are coercible to any closure
328                // type; function pointers are not (that would
329                // require double indirection).
330                // Additionally, we permit coercion of function
331                // items to drop the unsafe qualifier.
332                self.coerce_from_fn_item(a, b)
333            }
334            ty::FnPtr(a_sig_tys, a_hdr) => {
335                // We permit coercion of fn pointers to drop the
336                // unsafe qualifier.
337                self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
338            }
339            ty::Closure(..) => {
340                // Non-capturing closures are coercible to
341                // function pointers or unsafe function pointers.
342                // It cannot convert closures that require unsafe.
343                self.coerce_closure_to_fn(a, b)
344            }
345            ty::Adt(_, _) if self.tcx.features().reborrow() => {
346                let reborrow_coerce = self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
347                if reborrow_coerce.is_ok() {
348                    reborrow_coerce
349                } else {
350                    self.unify(a, b, ForceLeakCheck::No)
351                }
352            }
353            _ => {
354                // Otherwise, just use unification rules.
355                self.unify(a, b, ForceLeakCheck::No)
356            }
357        }
358    }
359
360    /// Coercing *from* an inference variable. In this case, we have no information
361    /// about the source type, so we can't really do a true coercion and we always
362    /// fall back to subtyping (`unify_and`).
363    fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
364        {
    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:364",
                        "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(364u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
365        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);
366        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);
367
368        if b.is_ty_var() {
369            let mut obligations = PredicateObligations::with_capacity(2);
370            let mut push_coerce_obligation = |a, b| {
371                obligations.push(Obligation::new(
372                    self.tcx(),
373                    self.cause.clone(),
374                    self.param_env,
375                    ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
376                ));
377            };
378
379            let target_ty = if self.use_lub {
380                // When computing the lub, we create a new target
381                // and coerce both `a` and `b` to it.
382                let target_ty = self.next_ty_var(self.cause.span);
383                push_coerce_obligation(a, target_ty);
384                push_coerce_obligation(b, target_ty);
385                target_ty
386            } else {
387                // When subtyping, we don't need to create a new target
388                // as we only coerce `a` to `b`.
389                push_coerce_obligation(a, b);
390                b
391            };
392
393            {
    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:393",
                        "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(393u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
                                                    target_ty, obligations) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
394                "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
395                target_ty, obligations
396            );
397            success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
398        } else {
399            // One unresolved type variable: just apply subtyping, we may be able
400            // to do something useful.
401            self.unify(a, b, ForceLeakCheck::No)
402        }
403    }
404
405    /// Handles coercing some arbitrary type `a` to some reference (`b`). This
406    /// handles a few cases:
407    /// - Introducing reborrows to give more flexible lifetimes
408    /// - Deref coercions to allow `&T` to coerce to `&T::Target`
409    /// - Coercing mutable references to immutable references
410    /// These coercions can be freely intermixed, for example we are able to
411    /// coerce `&mut T` to `&mut T::Target`.
412    fn coerce_to_ref(
413        &self,
414        a: Ty<'tcx>,
415        b: Ty<'tcx>,
416        r_b: ty::Region<'tcx>,
417        mutbl_b: hir::Mutability,
418    ) -> CoerceResult<'tcx> {
419        {
    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:419",
                        "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(419u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
420        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);
421        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);
422
423        let (r_a, mt_a) = match *a.kind() {
424            ty::Ref(r_a, ty, mutbl) => {
425                coerce_mutbls(mutbl, mutbl_b)?;
426                (r_a, ty::TypeAndMut { ty, mutbl })
427            }
428            _ => return self.unify(a, b, ForceLeakCheck::No),
429        };
430
431        // Look at each step in the `Deref` chain and check if
432        // any of the autoref'd `Target` types unify with the
433        // coercion target.
434        //
435        // For example when coercing from `&mut Vec<T>` to `&M [T]` we
436        // have three deref steps:
437        // 1. `&mut Vec<T>`, skip autoref
438        // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
439        //     - `&M Vec<T>` does not unify with `&M [T]`
440        // 3. `[T]`, autoref'd ty: `&M [T]`
441        //     - `&M [T]` does unify with `&M [T]`
442        let mut first_error = None;
443        let mut r_borrow_var = None;
444        let mut autoderef = self.autoderef(self.cause.span, a);
445        let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
446            if autoderefs == 0 {
447                // Don't autoref the first step as otherwise we'd allow
448                // coercing `&T` to `&&T`.
449                return None;
450            }
451
452            // The logic here really shouldn't exist. We don't care about free
453            // lifetimes during HIR typeck. Unfortunately later parts of this
454            // function rely on structural identity of the autoref'd deref'd ty.
455            //
456            // This means that what region we use here actually impacts whether
457            // we emit a reborrow coercion or not which can affect diagnostics
458            // and capture analysis (which in turn affects borrowck).
459            let r = if !self.use_lub {
460                r_b
461            } else if autoderefs == 1 {
462                r_a
463            } else {
464                if r_borrow_var.is_none() {
465                    // create var lazily, at most once
466                    let coercion = RegionVariableOrigin::Coercion(self.cause.span);
467                    let r = self.next_region_var(coercion);
468                    r_borrow_var = Some(r);
469                }
470                r_borrow_var.unwrap()
471            };
472
473            let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
474
475            // Note that we unify the autoref'd `Target` type with `b` rather than
476            // the `Target` type with the pointee of `b`. This is necessary
477            // to properly account for the differing variances of the pointees
478            // of `&` vs `&mut` references.
479            match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
480                Ok(ok) => Some(ok),
481                Err(err) => {
482                    if first_error.is_none() {
483                        first_error = Some(err);
484                    }
485                    None
486                }
487            }
488        });
489
490        // Extract type or return an error. We return the first error
491        // we got, which should be from relating the "base" type
492        // (e.g., in example above, the failure from relating `Vec<T>`
493        // to the target type), since that should be the least
494        // confusing.
495        let Some(InferOk { value: coerced_a, mut obligations }) = found else {
496            if let Some(first_error) = first_error {
497                {
    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:497",
                        "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(497u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
                                                    first_error) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
498                return Err(first_error);
499            } else {
500                // This may happen in the new trait solver since autoderef requires
501                // the pointee to be structurally normalizable, or else it'll just bail.
502                // So when we have a type like `&<not well formed>`, then we get no
503                // autoderef steps (even though there should be at least one). That means
504                // we get no type mismatches, since the loop above just exits early.
505                return Err(TypeError::Mismatch);
506            }
507        };
508
509        if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
510            // As a special case, if we would produce `&'a *x`, that's
511            // a total no-op. We end up with the type `&'a T` just as
512            // we started with. In that case, just skip it altogether.
513            //
514            // Unfortunately, this can actually effect capture analysis
515            // which in turn means this effects borrow checking. This can
516            // also effect diagnostics.
517            // FIXME(BoxyUwU): we should always emit reborrow coercions
518            //
519            // Note that for `&mut`, we DO want to reborrow --
520            // otherwise, this would be a move, which might be an
521            // error. For example `foo(self.x)` where `self` and
522            // `self.x` both have `&mut `type would be a move of
523            // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
524            // which is a borrow.
525            if !mutbl_b.is_not() {
    ::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
526            return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
527        }
528
529        let InferOk { value: mut adjustments, obligations: o } =
530            self.adjust_steps_as_infer_ok(&autoderef);
531        obligations.extend(o);
532        obligations.extend(autoderef.into_obligations());
533
534        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!(
535            matches!(coerced_a.kind(), ty::Ref(..)),
536            "expected a ref type, got {:?}",
537            coerced_a
538        );
539
540        // Now apply the autoref
541        let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
542        adjustments
543            .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
544
545        {
    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:545",
                        "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(545u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
                                                    coerced_a, adjustments) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
546
547        success(adjustments, coerced_a, obligations)
548    }
549
550    /// Performs [unsized coercion] by emulating a fulfillment loop on a
551    /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
552    /// are successfully selected.
553    ///
554    /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
555    #[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(555u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn ::tracing::field::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:557",
                                    "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(557u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                        as &dyn ::tracing::field::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:565",
                                        "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(565u32),
                                        ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
                                                            as &dyn ::tracing::field::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:569",
                                        "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(569u32),
                                        ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
                                                            as &dyn ::tracing::field::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:623",
                                            "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(623u32),
                                            ::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};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
                                                                as &dyn ::tracing::field::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.map(|(deref, autoref)|
                                    [deref, autoref]).into_flat_iter(),
                        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,
                                    errored: false,
                                }).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")]
556    fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
557        debug!(?source, ?target);
558        debug_assert!(self.shallow_resolve(source) == source);
559        debug_assert!(self.shallow_resolve(target) == target);
560
561        // We don't apply any coercions incase either the source or target
562        // aren't sufficiently well known but tend to instead just equate
563        // them both.
564        if source.is_ty_var() {
565            debug!("coerce_unsized: source is a TyVar, bailing out");
566            return Err(TypeError::Mismatch);
567        }
568        if target.is_ty_var() {
569            debug!("coerce_unsized: target is a TyVar, bailing out");
570            return Err(TypeError::Mismatch);
571        }
572
573        // This is an optimization because coercion is one of the most common
574        // operations that we do in typeck, since it happens at every assignment
575        // and call arg (among other positions).
576        //
577        // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
578        // That's because these are built-in types for which a core-provided impl
579        // doesn't exist, and for which a user-written impl is invalid.
580        //
581        // This is technically incomplete when users write impossible bounds like
582        // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
583        // and coercion is allowed to be incomplete. The only case where this matters
584        // is impossible bounds.
585        //
586        // Note that some of these types implement `LHS: Unsize<RHS>`, but they
587        // do not implement *`CoerceUnsized`* which is the root obligation of the
588        // check below.
589        match target.kind() {
590            ty::Bool
591            | ty::Char
592            | ty::Int(_)
593            | ty::Uint(_)
594            | ty::Float(_)
595            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
596            | ty::Str
597            | ty::Array(_, _)
598            | ty::Slice(_)
599            | ty::FnDef(_, _)
600            | ty::FnPtr(_, _)
601            | ty::Dynamic(_, _)
602            | ty::Closure(_, _)
603            | ty::CoroutineClosure(_, _)
604            | ty::Coroutine(_, _)
605            | ty::CoroutineWitness(_, _)
606            | ty::Never
607            | ty::Tuple(_) => return Err(TypeError::Mismatch),
608            _ => {}
609        }
610        // `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
611        // so we fast path bail out here
612        if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
613            && source_pointee.is_str()
614            && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
615            && target_pointee.is_str()
616        {
617            return Err(TypeError::Mismatch);
618        }
619
620        let traits =
621            (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
622        let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
623            debug!("missing Unsize or CoerceUnsized traits");
624            return Err(TypeError::Mismatch);
625        };
626
627        // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
628        // a DST unless we have to. This currently comes out in the wash since
629        // we can't unify [T] with U. But to properly support DST, we need to allow
630        // that, at which point we will need extra checks on the target here.
631
632        // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
633        let reborrow = match (source.kind(), target.kind()) {
634            (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
635                coerce_mutbls(mutbl_a, mutbl_b)?;
636
637                let coercion = RegionVariableOrigin::Coercion(self.cause.span);
638                let r_borrow = self.next_region_var(coercion);
639
640                // We don't allow two-phase borrows here, at least for initial
641                // implementation. If it happens that this coercion is a function argument,
642                // the reborrow in coerce_borrowed_ptr will pick it up.
643                let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
644
645                Some((
646                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
647                    Adjustment {
648                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
649                        target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
650                    },
651                ))
652            }
653            (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
654                coerce_mutbls(mt_a, mt_b)?;
655
656                Some((
657                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
658                    Adjustment {
659                        kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
660                        target: Ty::new_ptr(self.tcx, ty_a, mt_b),
661                    },
662                ))
663            }
664            _ => None,
665        };
666        let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
667
668        // Setup either a subtyping or a LUB relationship between
669        // the `CoerceUnsized` target type and the expected type.
670        // We only have the latter, so we use an inference variable
671        // for the former and let type inference do the rest.
672        let coerce_target = self.next_ty_var(self.cause.span);
673
674        let mut coercion = self.unify_and(
675            coerce_target,
676            target,
677            reborrow.map(|(deref, autoref)| [deref, autoref]).into_flat_iter(),
678            Adjust::Pointer(PointerCoercion::Unsize),
679            ForceLeakCheck::No,
680        )?;
681
682        // Create an obligation for `Source: CoerceUnsized<Target>`.
683        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
684        let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
685        let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
686
687        if self.next_trait_solver() {
688            coercion.obligations.push(obligation);
689
690            if self
691                .infcx
692                .visit_proof_tree(
693                    Goal::new(self.tcx, self.param_env, pred),
694                    &mut CoerceVisitor { fcx: self.fcx, span: self.cause.span, errored: false },
695                )
696                .is_break()
697            {
698                return Err(TypeError::Mismatch);
699            }
700        } else {
701            self.coerce_unsized_old_solver(
702                obligation,
703                &mut coercion,
704                coerce_unsized_did,
705                unsize_did,
706            )?;
707        }
708
709        Ok(coercion)
710    }
711
712    fn coerce_unsized_old_solver(
713        &self,
714        obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
715        coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
716        coerce_unsized_did: DefId,
717        unsize_did: DefId,
718    ) -> Result<(), TypeError<'tcx>> {
719        let mut selcx = traits::SelectionContext::new(self);
720        // Use a FIFO queue for this custom fulfillment procedure.
721        //
722        // A Vec (or SmallVec) is not a natural choice for a queue. However,
723        // this code path is hot, and this queue usually has a max length of 1
724        // and almost never more than 3. By using a SmallVec we avoid an
725        // allocation, at the (very small) cost of (occasionally) having to
726        // shift subsequent elements down when removing the front element.
727        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(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [obligation])))
    }
}smallvec![obligation];
728
729        // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
730        // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
731        // inference might unify those two inner type variables later.
732        let traits = [coerce_unsized_did, unsize_did];
733        while !queue.is_empty() {
734            let obligation = queue.remove(0);
735            let trait_pred = match obligation.predicate.kind().no_bound_vars() {
736                Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
737                    if traits.contains(&trait_pred.def_id()) =>
738                {
739                    self.resolve_vars_if_possible(trait_pred)
740                }
741                _ => {
742                    coercion.obligations.push(obligation);
743                    continue;
744                }
745            };
746            {
    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:746",
                        "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(746u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
                                                    trait_pred) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
747            match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
748                // Uncertain or unimplemented.
749                Ok(None) => {
750                    if trait_pred.def_id() == unsize_did {
751                        let self_ty = trait_pred.self_ty();
752                        let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
753                        {
    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:753",
                        "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(753u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
                                                    trait_pred) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
754                        match (self_ty.kind(), unsize_ty.kind()) {
755                            (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
756                                if self.type_var_is_sized(v) =>
757                            {
758                                {
    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:758",
                        "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(758u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
                                                    v) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
759                                coercion.obligations.push(obligation);
760                                // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
761                                // for unsizing.
762                            }
763                            _ => {
764                                // Some other case for `$0: Unsize<Something>`. Note that we
765                                // hit this case even if `Something` is a sized type, so just
766                                // don't do the coercion.
767                                {
    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:767",
                        "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(767u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized: ambiguous unsize");
768                                return Err(TypeError::Mismatch);
769                            }
770                        }
771                    } else {
772                        {
    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:772",
                        "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(772u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized: early return - ambiguous");
773                        return Err(TypeError::Mismatch);
774                    }
775                }
776                Err(SelectionError::Unimplemented) => {
777                    {
    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:777",
                        "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(777u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
778                    return Err(TypeError::Mismatch);
779                }
780
781                Err(SelectionError::TraitDynIncompatible(_)) => {
782                    // Dyn compatibility errors in coercion will *always* be due to the
783                    // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
784                    // written in source somewhere (otherwise we will never have lowered
785                    // the dyn trait from HIR to middle).
786                    //
787                    // There's no reason to emit yet another dyn compatibility error,
788                    // especially since the span will differ slightly and thus not be
789                    // deduplicated at all!
790                    self.fcx.set_tainted_by_errors(
791                        self.fcx
792                            .dcx()
793                            .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
794                    );
795                }
796                Err(err) => {
797                    let guar = self.err_ctxt().report_selection_error(
798                        obligation.clone(),
799                        &obligation,
800                        &err,
801                    );
802                    self.fcx.set_tainted_by_errors(guar);
803                    // Treat this like an obligation and follow through
804                    // with the unsizing - the lack of a coercion should
805                    // be silent, as it causes a type mismatch later.
806                }
807                Ok(Some(ImplSource::UserDefined(impl_source))) => {
808                    queue.extend(impl_source.nested);
809                    // Certain incoherent `CoerceUnsized` implementations may cause ICEs,
810                    // so check the impl's validity. Taint the body so that we don't try
811                    // to evaluate these invalid coercions in CTFE. We only need to do this
812                    // for local impls, since upstream impls should be valid.
813                    if impl_source.impl_def_id.is_local()
814                        && let Err(guar) =
815                            self.tcx.ensure_result().coerce_unsized_info(impl_source.impl_def_id)
816                    {
817                        self.fcx.set_tainted_by_errors(guar);
818                    }
819                }
820                Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
821            }
822        }
823
824        Ok(())
825    }
826
827    /// Create an obligation for `ty: Unpin`, where .
828    fn unpin_obligation(
829        &self,
830        source: Ty<'tcx>,
831        target: Ty<'tcx>,
832        ty: Ty<'tcx>,
833    ) -> PredicateObligation<'tcx> {
834        let pred = ty::TraitRef::new(
835            self.tcx,
836            self.tcx.require_lang_item(LangItem::Unpin, self.cause.span),
837            [ty],
838        );
839        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
840        PredicateObligation::new(self.tcx, cause, self.param_env, pred)
841    }
842
843    /// Checks if the given types are compatible for coercion from a pinned reference to a normal reference.
844    fn maybe_pin_ref_to_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
845        if !self.tcx.features().pin_ergonomics() {
846            return None;
847        }
848        if let Some((a_ty, a_pin @ ty::Pinnedness::Pinned, a_mut, a_r)) = a.maybe_pinned_ref()
849            && let Some((_, b_pin @ ty::Pinnedness::Not, b_mut, _)) = b.maybe_pinned_ref()
850        {
851            return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
852        }
853        {
    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:853",
                        "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(853u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting pinned ref to ref coercion (`{0:?}` -> `{1:?}`)",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("not fitting pinned ref to ref coercion (`{:?}` -> `{:?}`)", a, b);
854        None
855    }
856
857    /// Coerces from a pinned reference to a normal reference.
858    #[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_pin_ref_to_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(858u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_pin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_pin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_mut")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_mut");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_r")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_r");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b_pin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b_pin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b_mut")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b_mut");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
                                                            as &dyn ::tracing::field::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")
                };
            };
            if true {
                if !self.tcx.features().pin_ergonomics() {
                    ::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
                };
            };
            if true {
                {
                    match (&a_pin, &ty::Pinnedness::Pinned) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            if true {
                {
                    match (&b_pin, &ty::Pinnedness::Not) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            coerce_mutbls(a_mut, b_mut)?;
            let unpin_obligation = self.unpin_obligation(a, b, a_ty);
            let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
            let mut coerce =
                self.unify_and(a, b,
                        [Adjustment {
                                    kind: Adjust::Deref(DerefAdjustKind::Pin),
                                    target: a_ty,
                                }],
                        Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut,
                                    self.allow_two_phase))), ForceLeakCheck::No)?;
            coerce.obligations.push(unpin_obligation);
            Ok(coerce)
        }
    }
}#[instrument(skip(self), level = "trace")]
859    fn coerce_pin_ref_to_ref(
860        &self,
861        CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
862            'tcx,
863        >,
864    ) -> CoerceResult<'tcx> {
865        debug_assert!(self.shallow_resolve(a) == a);
866        debug_assert!(self.shallow_resolve(b) == b);
867        debug_assert!(self.tcx.features().pin_ergonomics());
868        debug_assert_eq!(a_pin, ty::Pinnedness::Pinned);
869        debug_assert_eq!(b_pin, ty::Pinnedness::Not);
870
871        coerce_mutbls(a_mut, b_mut)?;
872
873        let unpin_obligation = self.unpin_obligation(a, b, a_ty);
874
875        let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
876        let mut coerce = self.unify_and(
877            a,
878            b,
879            [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Pin), target: a_ty }],
880            Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut, self.allow_two_phase))),
881            ForceLeakCheck::No,
882        )?;
883        coerce.obligations.push(unpin_obligation);
884        Ok(coerce)
885    }
886
887    /// Checks if the given types are compatible for coercion to a pinned reference.
888    fn maybe_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
889        if !self.tcx.features().pin_ergonomics() {
890            return None;
891        }
892        if let Some((a_ty, a_pin, a_mut, a_r)) = a.maybe_pinned_ref()
893            && let Some((_, b_pin @ ty::Pinnedness::Pinned, b_mut, _)) = b.maybe_pinned_ref()
894        {
895            return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
896        }
897        {
    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:897",
                        "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(897u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting ref to pinned ref coercion (`{0:?}` -> `{1:?}`)",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("not fitting ref to pinned ref coercion (`{:?}` -> `{:?}`)", a, b);
898        None
899    }
900
901    /// Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:
902    ///
903    /// Currently we only support the following coercions:
904    /// - Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
905    /// - Reborrowing `Pin<&T>` -> `Pin<&T>`
906    /// - Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
907    /// - Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
908    /// - Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`
909    ///
910    /// In the future we might want to support other reborrowing coercions, such as:
911    /// - `Pin<Box<T>>` as `Pin<&T>`
912    /// - `Pin<Box<T>>` as `Pin<&mut T>`
913    #[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(913u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_pin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_pin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_mut")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_mut");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a_r")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a_r");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b_pin")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b_pin");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b_mut")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b_mut");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
                                                            as &dyn ::tracing::field::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")
                };
            };
            if true {
                if !self.tcx.features().pin_ergonomics() {
                    ::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
                };
            };
            if true {
                {
                    match (&b_pin, &ty::Pinnedness::Pinned) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            let (deref, unpin_obligation) =
                match a_pin {
                    ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
                    ty::Pinnedness::Not => {
                        (DerefAdjustKind::Builtin,
                            Some(self.unpin_obligation(a, b, a_ty)))
                    }
                };
            coerce_mutbls(a_mut, b_mut)?;
            let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
            let mut coerce =
                self.unify_and(a, b,
                        [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
                        Adjust::Borrow(AutoBorrow::Pin(b_mut)),
                        ForceLeakCheck::No)?;
            coerce.obligations.extend(unpin_obligation);
            Ok(coerce)
        }
    }
}#[instrument(skip(self), level = "trace")]
914    fn coerce_to_pin_ref(
915        &self,
916        CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
917            'tcx,
918        >,
919    ) -> CoerceResult<'tcx> {
920        debug_assert!(self.shallow_resolve(a) == a);
921        debug_assert!(self.shallow_resolve(b) == b);
922        debug_assert!(self.tcx.features().pin_ergonomics());
923        debug_assert_eq!(b_pin, ty::Pinnedness::Pinned);
924
925        // We need to deref the reference first before we reborrow it to a pinned reference.
926        let (deref, unpin_obligation) = match a_pin {
927            // no `Unpin` required when reborrowing a pinned reference to a pinned reference
928            ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
929            // `Unpin` required when reborrowing a non-pinned reference to a pinned reference
930            ty::Pinnedness::Not => {
931                (DerefAdjustKind::Builtin, Some(self.unpin_obligation(a, b, a_ty)))
932            }
933        };
934
935        coerce_mutbls(a_mut, b_mut)?;
936
937        // update a with b's mutability since we'll be coercing mutability
938        let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
939
940        // To complete the reborrow, we need to make sure we can unify the inner types, and if so we
941        // add the adjustments.
942        let mut coerce = self.unify_and(
943            a,
944            b,
945            [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
946            Adjust::Borrow(AutoBorrow::Pin(b_mut)),
947            ForceLeakCheck::No,
948        )?;
949
950        coerce.obligations.extend(unpin_obligation);
951        Ok(coerce)
952    }
953
954    /// Applies generic exclusive reborrowing on type implementing `Reborrow`.
955    #[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_reborrow",
                                    "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(955u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::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 (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
                (a.kind(),
                    b.kind()) else { return Err(TypeError::Mismatch); };
            if a_def.did() == b_def.did() {
                self.unify_and(a, b, [],
                    Adjust::GenericReborrow(ty::Mutability::Mut),
                    ForceLeakCheck::No)
            } else { Err(TypeError::Mismatch) }
        }
    }
}#[instrument(skip(self), level = "trace")]
956    fn coerce_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
957        debug_assert!(self.shallow_resolve(a) == a);
958        debug_assert!(self.shallow_resolve(b) == b);
959
960        // We need to make sure the two types are compatible for reborrow.
961        let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
962            return Err(TypeError::Mismatch);
963        };
964        if a_def.did() == b_def.did() {
965            // Reborrow is applicable here
966            self.unify_and(
967                a,
968                b,
969                [],
970                Adjust::GenericReborrow(ty::Mutability::Mut),
971                ForceLeakCheck::No,
972            )
973        } else {
974            // FIXME: CoerceShared check goes here, error for now
975            Err(TypeError::Mismatch)
976        }
977    }
978
979    /// Applies generic exclusive reborrowing on type implementing `Reborrow`.
980    #[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_shared_reborrow",
                                    "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(980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("b")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("b");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::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 (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
                (a.kind(),
                    b.kind()) else { return Err(TypeError::Mismatch); };
            if a_def.did() == b_def.did() { return Err(TypeError::Mismatch); }
            let Some(coerce_shared_trait_did) =
                self.tcx.lang_items().coerce_shared() else {
                    return Err(TypeError::Mismatch);
                };
            let coerce_shared_trait_ref =
                ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
            let obligation =
                traits::Obligation::new(self.tcx, ObligationCause::dummy(),
                    self.param_env, ty::Binder::dummy(coerce_shared_trait_ref));
            let ocx = ObligationCtxt::new(&self.infcx);
            ocx.register_obligation(obligation);
            let errs = ocx.evaluate_obligations_error_on_ambiguity();
            if errs.no_errors() {
                Ok(InferOk {
                        value: (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                    [Adjustment {
                                                kind: Adjust::GenericReborrow(ty::Mutability::Not),
                                                target: b,
                                            }])), b),
                        obligations: ocx.into_pending_obligations(),
                    })
            } else { Err(TypeError::Mismatch) }
        }
    }
}#[instrument(skip(self), level = "trace")]
981    fn coerce_shared_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
982        debug_assert!(self.shallow_resolve(a) == a);
983        debug_assert!(self.shallow_resolve(b) == b);
984
985        // We need to make sure the two types are compatible for reborrow.
986        let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
987            return Err(TypeError::Mismatch);
988        };
989        if a_def.did() == b_def.did() {
990            // CoerceShared cannot be T -> T.
991            return Err(TypeError::Mismatch);
992        }
993        let Some(coerce_shared_trait_did) = self.tcx.lang_items().coerce_shared() else {
994            return Err(TypeError::Mismatch);
995        };
996        let coerce_shared_trait_ref = ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
997        let obligation = traits::Obligation::new(
998            self.tcx,
999            ObligationCause::dummy(),
1000            self.param_env,
1001            ty::Binder::dummy(coerce_shared_trait_ref),
1002        );
1003        let ocx = ObligationCtxt::new(&self.infcx);
1004        ocx.register_obligation(obligation);
1005        let errs = ocx.evaluate_obligations_error_on_ambiguity();
1006        if errs.no_errors() {
1007            Ok(InferOk {
1008                value: (
1009                    vec![Adjustment {
1010                        kind: Adjust::GenericReborrow(ty::Mutability::Not),
1011                        target: b,
1012                    }],
1013                    b,
1014                ),
1015                obligations: ocx.into_pending_obligations(),
1016            })
1017        } else {
1018            Err(TypeError::Mismatch)
1019        }
1020    }
1021
1022    fn coerce_from_fn_pointer(
1023        &self,
1024        a: Ty<'tcx>,
1025        a_sig: ty::PolyFnSig<'tcx>,
1026        b: Ty<'tcx>,
1027    ) -> CoerceResult<'tcx> {
1028        {
    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:1028",
                        "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(1028u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("a_sig")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("a_sig");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("b")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("b");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_sig)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
1029        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);
1030
1031        match b.kind() {
1032            ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety().is_unsafe() => {
1033                let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
1034                let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
1035                self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
1036            }
1037            _ => self.unify(a, b, ForceLeakCheck::Yes),
1038        }
1039    }
1040
1041    fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1042        {
    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:1042",
                        "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(1042u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
1043        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);
1044        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);
1045
1046        match b.kind() {
1047            ty::FnPtr(_, b_hdr) => {
1048                let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety()))?;
1049
1050                let InferOk { value: a_sig, mut obligations } =
1051                    self.at(&self.cause, self.param_env).normalize(Unnormalized::new_wip(a_sig));
1052                let a = Ty::new_fn_ptr(self.tcx, a_sig);
1053
1054                let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety()));
1055                let InferOk { value, obligations: o2 } =
1056                    self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
1057
1058                obligations.extend(o2);
1059                Ok(InferOk { value, obligations })
1060            }
1061            _ => self.unify(a, b, ForceLeakCheck::No),
1062        }
1063    }
1064
1065    /// Attempts to coerce from a closure to a function pointer. Fails
1066    /// if the closure has any upvars.
1067    fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1068        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);
1069        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);
1070
1071        match b.kind() {
1072            ty::FnPtr(_, hdr) => {
1073                let safety = hdr.safety();
1074                let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
1075                let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety()), terr)?;
1076                let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
1077                {
    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:1077",
                        "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(1077u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
                                                    a, b, pointer_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
1078
1079                let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
1080                self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
1081            }
1082            _ => self.unify(a, b, ForceLeakCheck::No),
1083        }
1084    }
1085
1086    fn coerce_to_raw_ptr(
1087        &self,
1088        a: Ty<'tcx>,
1089        b: Ty<'tcx>,
1090        mutbl_b: hir::Mutability,
1091    ) -> CoerceResult<'tcx> {
1092        {
    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:1092",
                        "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(1092u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
                                                    a, b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
1093        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);
1094        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);
1095
1096        let (is_ref, mt_a) = match *a.kind() {
1097            ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
1098            ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
1099            _ => return self.unify(a, b, ForceLeakCheck::No),
1100        };
1101        coerce_mutbls(mt_a.mutbl, mutbl_b)?;
1102
1103        // Check that the types which they point at are compatible.
1104        let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
1105        // Although references and raw ptrs have the same
1106        // representation, we still register an Adjust::DerefRef so that
1107        // regionck knows that the region for `a` must be valid here.
1108        if is_ref {
1109            self.unify_and(
1110                a_raw,
1111                b,
1112                [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
1113                Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1114                ForceLeakCheck::No,
1115            )
1116        } else if mt_a.mutbl != mutbl_b {
1117            self.unify_and(
1118                a_raw,
1119                b,
1120                [],
1121                Adjust::Pointer(PointerCoercion::MutToConstPointer),
1122                ForceLeakCheck::No,
1123            )
1124        } else {
1125            self.unify(a_raw, b, ForceLeakCheck::No)
1126        }
1127    }
1128}
1129
1130impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1131    /// Attempt to coerce an expression to a type, and return the
1132    /// adjusted type of the expression, if successful.
1133    /// Adjustments are only recorded if the coercion succeeded.
1134    /// The expressions *must not* have any preexisting adjustments.
1135    pub(crate) fn coerce(
1136        &self,
1137        expr: &'tcx hir::Expr<'tcx>,
1138        expr_ty: Ty<'tcx>,
1139        target: Ty<'tcx>,
1140        allow_two_phase: AllowTwoPhase,
1141        cause: Option<ObligationCause<'tcx>>,
1142    ) -> RelateResult<'tcx, Ty<'tcx>> {
1143        let source = self.resolve_vars_with_obligations(expr_ty);
1144        {
    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:1144",
                        "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(1144u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
                                                    expr, source, target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
1145
1146        let cause =
1147            cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1148        let coerce = Coerce::new(
1149            self,
1150            cause,
1151            allow_two_phase,
1152            self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
1153        );
1154        let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
1155
1156        let (adjustments, _) = self.register_infer_ok_obligations(ok);
1157        self.apply_adjustments(expr, adjustments);
1158        Ok(if let Err(guar) = expr_ty.error_reported() {
1159            Ty::new_error(self.tcx, guar)
1160        } else {
1161            target
1162        })
1163    }
1164
1165    /// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1166    /// and may return false positives if types are not yet fully constrained by inference.
1167    ///
1168    /// Returns false if the coercion is not possible, or if the coercion creates any
1169    /// sub-obligations that result in errors.
1170    ///
1171    /// This should only be used for diagnostics.
1172    pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1173        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1174        // We don't ever need two-phase here since we throw out the result of the coercion.
1175        // We also just always set `coerce_never` to true, since this is a heuristic.
1176        let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1177        self.probe(|_| {
1178            // Make sure to structurally resolve the types, since we use
1179            // the `TyKind`s heavily in coercion.
1180            let ocx = ObligationCtxt::new(self);
1181            let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1182                return false;
1183            };
1184            ocx.register_obligations(ok.obligations);
1185            ocx.try_evaluate_obligations().no_errors()
1186        })
1187    }
1188
1189    /// Given a type and a target type, this function will calculate and return
1190    /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1191    /// it's not possible, return `None`.
1192    pub(crate) fn deref_steps_for_suggestion(
1193        &self,
1194        expr_ty: Ty<'tcx>,
1195        target: Ty<'tcx>,
1196    ) -> Option<usize> {
1197        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1198        // We don't ever need two-phase here since we throw out the result of the coercion.
1199        let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1200        coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1201            self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1202        })
1203    }
1204
1205    /// Given a type, this function will calculate and return the type given
1206    /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1207    ///
1208    /// This function is for diagnostics only, since it does not register
1209    /// trait or region sub-obligations. (presumably we could, but it's not
1210    /// particularly important for diagnostics...)
1211    pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1212        self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1213            self.infcx
1214                .type_implements_trait(
1215                    self.tcx.lang_items().deref_mut_trait()?,
1216                    [expr_ty],
1217                    self.param_env,
1218                )
1219                .may_apply()
1220                .then_some(deref_ty)
1221        })
1222    }
1223
1224    x;#[instrument(level = "debug", skip(self), ret)]
1225    fn sig_for_coerce_lub(
1226        &self,
1227        ty: Ty<'tcx>,
1228        closure_upvars_terr: TypeError<'tcx>,
1229    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1230        match ty.kind() {
1231            ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1232            ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1233            _ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1234        }
1235    }
1236
1237    fn sig_for_fn_def_coercion(
1238        &self,
1239        fndef: Ty<'tcx>,
1240        expected_safety: Option<hir::Safety>,
1241    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1242        let tcx = self.tcx;
1243
1244        let &ty::FnDef(def_id, _) = fndef.kind() else {
1245            {
    ::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);
1246        };
1247
1248        // Intrinsics are not coercible to function pointers
1249        if tcx.intrinsic(def_id).is_some() {
1250            return Err(TypeError::IntrinsicCast);
1251        }
1252
1253        let fn_attrs = tcx.codegen_fn_attrs(def_id);
1254        if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
    InlineAttr::Force { .. } => true,
    _ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1255            return Err(TypeError::ForceInlineCast);
1256        }
1257
1258        let sig = fndef.fn_sig(tcx);
1259        let sig = if fn_attrs.safe_target_features {
1260            // Allow the coercion if the current function has all the features that would be
1261            // needed to call the coercee safely.
1262            match tcx.adjust_target_feature_sig(def_id, sig, self.body_def_id.into()) {
1263                Some(adjusted_sig) => adjusted_sig,
1264                None if #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
    Some(hir::Safety::Safe) => true,
    _ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1265                    return Err(TypeError::TargetFeatureCast(def_id));
1266                }
1267                None => sig,
1268            }
1269        } else {
1270            sig
1271        };
1272
1273        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)) {
1274            Ok(tcx.safe_to_unsafe_sig(sig))
1275        } else {
1276            Ok(sig)
1277        }
1278    }
1279
1280    fn sig_for_closure_coercion(
1281        &self,
1282        closure: Ty<'tcx>,
1283        expected_safety: Option<hir::Safety>,
1284        closure_upvars_terr: TypeError<'tcx>,
1285    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1286        let tcx = self.tcx;
1287
1288        let ty::Closure(closure_def, closure_args) = closure.kind() else {
1289            {
    ::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);
1290        };
1291
1292        // At this point we haven't done capture analysis, which means
1293        // that the ClosureArgs just contains an inference variable instead
1294        // of tuple of captured types.
1295        //
1296        // All we care here is if any variable is being captured and not the exact paths,
1297        // so we check `upvars_mentioned` for root variables being captured.
1298        if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1299            return Err(closure_upvars_terr);
1300        }
1301
1302        // We coerce the closure, which has fn type
1303        //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
1304        // to
1305        //     `fn(arg0,arg1,...) -> _`
1306        // or
1307        //     `unsafe fn(arg0,arg1,...) -> _`
1308        let closure_sig = closure_args.as_closure().sig();
1309        Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1310    }
1311
1312    /// Given some expressions, their known unified type and another expression,
1313    /// tries to unify the types, potentially inserting coercions on any of the
1314    /// provided expressions and returns their LUB (aka "common supertype").
1315    ///
1316    /// This is really an internal helper. From outside the coercion
1317    /// module, you should instantiate a `CoerceMany` instance.
1318    fn try_find_coercion_lub(
1319        &self,
1320        cause: &ObligationCause<'tcx>,
1321        exprs: &[&'tcx hir::Expr<'tcx>],
1322        prev_ty: Ty<'tcx>,
1323        new: &hir::Expr<'_>,
1324        new_ty: Ty<'tcx>,
1325    ) -> RelateResult<'tcx, Ty<'tcx>> {
1326        let prev_ty = self.resolve_vars_with_obligations(prev_ty);
1327        let new_ty = self.resolve_vars_with_obligations(new_ty);
1328        {
    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:1328",
                        "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(1328u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1329            "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1330            prev_ty,
1331            new_ty,
1332            exprs.len()
1333        );
1334
1335        // Fast Path: don't go through the coercion logic if we're coercing
1336        // a type to itself. This is unfortunately quite perf relevant so
1337        // we do it even though it may mask bugs in the coercion logic.
1338        if prev_ty == new_ty {
1339            return Ok(prev_ty);
1340        }
1341
1342        let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1343        let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1344            // Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1345            // if they can just be lubbed.
1346            //
1347            // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1348            // we would erroneously coerce closures to fnptrs when attempting to
1349            // coerce a closure to itself.
1350            (ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1351                let lubbed_ty = self.commit_if_ok(|snapshot| {
1352                    let outer_universe = self.infcx.universe();
1353
1354                    // We need to eagerly handle nested obligations due to lazy norm.
1355                    let result = if self.next_trait_solver() {
1356                        let ocx = ObligationCtxt::new(self);
1357                        let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1358                        if ocx.try_evaluate_obligations().no_errors() {
1359                            Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1360                        } else {
1361                            Err(TypeError::Mismatch)
1362                        }
1363                    } else {
1364                        self.at(cause, self.param_env).lub(prev_ty, new_ty)
1365                    };
1366
1367                    self.leak_check(outer_universe, Some(snapshot))?;
1368                    result
1369                });
1370
1371                match lubbed_ty {
1372                    Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1373                    Err(_) => {
1374                        let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1375                        let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1376                        Some((a_sig, b_sig))
1377                    }
1378                }
1379            }
1380
1381            (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1382                let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1383                let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1384                Some((a_sig, b_sig))
1385            }
1386            // ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1387            // call using `lub` which is what will happen on the normal path.
1388            (ty::FnPtr(..), ty::FnPtr(..)) => None,
1389            _ => None,
1390        };
1391
1392        if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1393            // Allow coercing safe sigs to unsafe sigs
1394            if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1395                a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1396            } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1397                b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1398            };
1399
1400            // The signature must match.
1401            let (a_sig, b_sig) = self.normalize(new.span, Unnormalized::new_wip((a_sig, b_sig)));
1402            let sig = self
1403                .at(cause, self.param_env)
1404                .lub(a_sig, b_sig)
1405                .map(|ok| self.register_infer_ok_obligations(ok))?;
1406
1407            // Reify both sides and return the reified fn pointer type.
1408            let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1409            let prev_adjustment = match prev_ty.kind() {
1410                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1411                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1412                _ => ::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"),
1413            };
1414            let next_adjustment = match new_ty.kind() {
1415                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1416                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1417                _ => ::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"),
1418            };
1419            for expr in exprs.iter() {
1420                self.apply_adjustments(
1421                    expr,
1422                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }]))vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1423                );
1424            }
1425            self.apply_adjustments(new, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Adjustment { kind: next_adjustment, target: fn_ptr }]))vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1426            return Ok(fn_ptr);
1427        }
1428
1429        // Configure a Coerce instance to compute the LUB.
1430        // We don't allow two-phase borrows on any autorefs this creates since we
1431        // probably aren't processing function arguments here and even if we were,
1432        // they're going to get autorefed again anyway and we can apply 2-phase borrows
1433        // at that time.
1434        //
1435        // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1436        // operate on values and not places, so a never coercion is valid.
1437        let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1438        coerce.use_lub = true;
1439
1440        // First try to coerce the new expression to the type of the previous ones,
1441        // but only if the new expression has no coercion already applied to it.
1442        let mut first_error = None;
1443        if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1444            let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1445            match result {
1446                Ok(ok) => {
1447                    let (adjustments, target) = self.register_infer_ok_obligations(ok);
1448                    self.apply_adjustments(new, adjustments);
1449                    {
    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:1449",
                        "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(1449u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1450                        "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1451                        new_ty, prev_ty, target
1452                    );
1453                    return Ok(target);
1454                }
1455                Err(e) => first_error = Some(e),
1456            }
1457        }
1458
1459        let ok = self
1460            .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1461            // Avoid giving strange errors on failed attempts.
1462            .map_err(|e| first_error.unwrap_or(e))?;
1463
1464        let (adjustments, target) = self.register_infer_ok_obligations(ok);
1465        for expr in exprs {
1466            self.apply_adjustments(expr, adjustments.clone());
1467        }
1468        {
    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:1468",
                        "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(1468u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1469            "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1470            prev_ty, new_ty, target
1471        );
1472        Ok(target)
1473    }
1474}
1475
1476/// Check whether `ty` can be coerced to `output_ty`.
1477/// Used from clippy.
1478pub fn can_coerce<'tcx>(
1479    tcx: TyCtxt<'tcx>,
1480    param_env: ty::ParamEnv<'tcx>,
1481    body_def_id: LocalDefId,
1482    ty: Ty<'tcx>,
1483    output_ty: Ty<'tcx>,
1484) -> bool {
1485    let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_def_id);
1486    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_def_id);
1487    fn_ctxt.may_coerce(ty, output_ty)
1488}
1489
1490/// CoerceMany encapsulates the pattern you should use when you have
1491/// many expressions that are all getting coerced to a common
1492/// type. This arises, for example, when you have a match (the result
1493/// of each arm is coerced to a common type). It also arises in less
1494/// obvious places, such as when you have many `break foo` expressions
1495/// that target the same loop, or the various `return` expressions in
1496/// a function.
1497///
1498/// The basic protocol is as follows:
1499///
1500/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1501///   This will also serve as the "starting LUB". The expectation is
1502///   that this type is something which all of the expressions *must*
1503///   be coercible to. Use a fresh type variable if needed.
1504/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1505///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1506///     unit. This happens for example if you have a `break` with no expression,
1507///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1508///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1509///     from you so that you don't have to worry your pretty head about it.
1510///     But if an error is reported, the final type will be `err`.
1511///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1512///     previously coerced expressions.
1513/// - When all done, invoke `complete()`. This will return the LUB of
1514///   all your expressions.
1515///   - WARNING: I don't believe this final type is guaranteed to be
1516///     related to your initial `expected_ty` in any particular way,
1517///     although it will typically be a subtype, so you should check it.
1518///     Check the note below for more details.
1519///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1520///     previously coerced expressions.
1521///
1522/// Example:
1523///
1524/// ```ignore (illustrative)
1525/// let mut coerce = CoerceMany::new(expected_ty);
1526/// for expr in exprs {
1527///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1528///     coerce.coerce(fcx, &cause, expr, expr_ty);
1529/// }
1530/// let final_ty = coerce.complete(fcx);
1531/// ```
1532///
1533/// NOTE: Why does the `expected_ty` participate in the LUB?
1534/// When coercing, each branch should use the following expectations for type inference:
1535/// - The branch can be coerced to the expected type of the match/if/whatever.
1536/// - The branch can be coercion lub'd with the types of the previous branches.
1537/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1538/// but adding and using this feels very challenging.
1539/// What we instead do is to use the expected type of the match/if/whatever as
1540/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1541/// "types from previous branches" as the coercion target, which can contains both expectations.
1542///
1543/// Two concerns with this approach:
1544/// - We may have incompatible `final_ty` if that lub is different from the expected
1545///   type of the match. However, in this case coercing the final type of the
1546///   `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1547/// - We may constrain the `expected_ty` too early. For some branches with
1548///   type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1549///   `(a lub b) lub expected_ty`. They should be the same type. However,
1550///   `a lub expected_ty` may constrain inference variables in `expected_ty`.
1551///   In this case the difference does matter and we get actually incorrect results.
1552/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1553/// the expected type of the match when computing the types of its branches.
1554pub(crate) struct CoerceMany<'tcx> {
1555    expected_ty: Ty<'tcx>,
1556    final_ty: Option<Ty<'tcx>>,
1557    expressions: Vec<&'tcx hir::Expr<'tcx>>,
1558}
1559
1560impl<'tcx> CoerceMany<'tcx> {
1561    /// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1562    /// coercion sites is known before hand, consider `with_capacity()` instead
1563    /// to avoid allocation.
1564    pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1565        Self::with_capacity(expected_ty, 1)
1566    }
1567
1568    /// Creates a `CoerceMany` with a given capacity.
1569    pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1570        CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1571    }
1572
1573    /// Returns the "expected type" with which this coercion was
1574    /// constructed. This represents the "downward propagated" type
1575    /// that was given to us at the start of typing whatever construct
1576    /// we are typing (e.g., the match expression).
1577    ///
1578    /// Typically, this is used as the expected type when
1579    /// type-checking each of the alternative expressions whose types
1580    /// we are trying to merge.
1581    pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1582        self.expected_ty
1583    }
1584
1585    /// Returns the current "merged type", representing our best-guess
1586    /// at the LUB of the expressions we've seen so far (if any). This
1587    /// isn't *final* until you call `self.complete()`, which will return
1588    /// the merged type.
1589    pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1590        self.final_ty.unwrap_or(self.expected_ty)
1591    }
1592
1593    /// Indicates that the value generated by `expression`, which is
1594    /// of type `expression_ty`, is one of the possibilities that we
1595    /// could coerce from. This will record `expression`, and later
1596    /// calls to `coerce` may come back and add adjustments and things
1597    /// if necessary.
1598    pub(crate) fn coerce<'a>(
1599        &mut self,
1600        fcx: &FnCtxt<'a, 'tcx>,
1601        cause: &ObligationCause<'tcx>,
1602        expression: &'tcx hir::Expr<'tcx>,
1603        expression_ty: Ty<'tcx>,
1604    ) {
1605        self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1606    }
1607
1608    /// Indicates that one of the inputs is a "forced unit". This
1609    /// occurs in a case like `if foo { ... };`, where the missing else
1610    /// generates a "forced unit". Another example is a `loop { break;
1611    /// }`, where the `break` has no argument expression. We treat
1612    /// these cases slightly differently for error-reporting
1613    /// purposes. Note that these tend to correspond to cases where
1614    /// the `()` expression is implicit in the source, and hence we do
1615    /// not take an expression argument.
1616    ///
1617    /// The `augment_error` gives you a chance to extend the error
1618    /// message, in case any results (e.g., we use this to suggest
1619    /// removing a `;`).
1620    pub(crate) fn coerce_forced_unit<'a>(
1621        &mut self,
1622        fcx: &FnCtxt<'a, 'tcx>,
1623        cause: &ObligationCause<'tcx>,
1624        augment_error: impl FnOnce(&mut Diag<'_>),
1625        label_unit_as_expected: bool,
1626    ) {
1627        self.coerce_inner(
1628            fcx,
1629            cause,
1630            None,
1631            fcx.tcx.types.unit,
1632            augment_error,
1633            label_unit_as_expected,
1634        )
1635    }
1636
1637    /// The inner coercion "engine". If `expression` is `None`, this
1638    /// is a forced-unit case, and hence `expression_ty` must be
1639    /// `Nil`.
1640    #[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(1640u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expression")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expression");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expression_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expression_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
                                                            as &dyn ::tracing::field::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:1731",
                                    "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(1731u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("result")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("result");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
                                                        as &dyn ::tracing::field::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(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(block, _, 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))
                                    }));
                            if loop_src == hir::LoopSource::While &&
                                    let Some(pat) = irrefutable_if_let_expr(block) {
                                err.span_label(pat.span,
                                    "this pattern always matches, consider using `loop` instead");
                            }
                        }
                        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")]
1641    pub(crate) fn coerce_inner<'a>(
1642        &mut self,
1643        fcx: &FnCtxt<'a, 'tcx>,
1644        cause: &ObligationCause<'tcx>,
1645        expression: Option<&'tcx hir::Expr<'tcx>>,
1646        mut expression_ty: Ty<'tcx>,
1647        augment_error: impl FnOnce(&mut Diag<'_>),
1648        label_expression_as_expected: bool,
1649    ) {
1650        // Incorporate whatever type inference information we have
1651        // until now; in principle we might also want to process
1652        // pending obligations, but doing so should only improve
1653        // compatibility (hopefully that is true) by helping us
1654        // uncover never types better.
1655        if expression_ty.is_ty_var() {
1656            expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1657        }
1658
1659        // If we see any error types, just propagate that error
1660        // upwards.
1661        if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1662            self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1663            return;
1664        }
1665
1666        let (expected, found) = if label_expression_as_expected {
1667            // In the case where this is a "forced unit", like
1668            // `break`, we want to call the `()` "expected"
1669            // since it is implied by the syntax.
1670            // (Note: not all force-units work this way.)"
1671            (expression_ty, self.merged_ty())
1672        } else {
1673            // Otherwise, the "expected" type for error
1674            // reporting is the current unification type,
1675            // which is basically the LUB of the expressions
1676            // we've seen so far (combined with the expected
1677            // type)
1678            (self.merged_ty(), expression_ty)
1679        };
1680
1681        // Handle the actual type unification etc.
1682        let result = if let Some(expression) = expression {
1683            if self.expressions.is_empty() {
1684                // Special-case the first expression we are coercing.
1685                // To be honest, I'm not entirely sure why we do this.
1686                // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1687                fcx.coerce(
1688                    expression,
1689                    expression_ty,
1690                    self.expected_ty,
1691                    AllowTwoPhase::No,
1692                    Some(cause.clone()),
1693                )
1694            } else {
1695                fcx.try_find_coercion_lub(
1696                    cause,
1697                    &self.expressions,
1698                    self.merged_ty(),
1699                    expression,
1700                    expression_ty,
1701                )
1702            }
1703        } else {
1704            // this is a hack for cases where we default to `()` because
1705            // the expression etc has been omitted from the source. An
1706            // example is an `if let` without an else:
1707            //
1708            //     if let Some(x) = ... { }
1709            //
1710            // we wind up with a second match arm that is like `_ =>
1711            // ()`. That is the case we are considering here. We take
1712            // a different path to get the right "expected, found"
1713            // message and so forth (and because we know that
1714            // `expression_ty` will be unit).
1715            //
1716            // Another example is `break` with no argument expression.
1717            assert!(expression_ty.is_unit(), "if let hack without unit type");
1718            fcx.at(cause, fcx.param_env)
1719                .eq(
1720                    // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1721                    DefineOpaqueTypes::Yes,
1722                    expected,
1723                    found,
1724                )
1725                .map(|infer_ok| {
1726                    fcx.register_infer_ok_obligations(infer_ok);
1727                    expression_ty
1728                })
1729        };
1730
1731        debug!(?result);
1732        match result {
1733            Ok(v) => {
1734                self.final_ty = Some(v);
1735                if let Some(e) = expression {
1736                    self.expressions.push(e);
1737                }
1738            }
1739            Err(coercion_error) => {
1740                // Mark that we've failed to coerce the types here to suppress
1741                // any superfluous errors we might encounter while trying to
1742                // emit or provide suggestions on how to fix the initial error.
1743                fcx.set_tainted_by_errors(
1744                    fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1745                );
1746                let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
1747
1748                let mut err;
1749                let mut unsized_return = false;
1750                match *cause.code() {
1751                    ObligationCauseCode::ReturnNoExpression => {
1752                        err = struct_span_code_err!(
1753                            fcx.dcx(),
1754                            cause.span,
1755                            E0069,
1756                            "`return;` in a function whose return type is not `()`"
1757                        );
1758                        if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1759                        {
1760                            err.span_suggestion_verbose(
1761                                cause.span.shrink_to_hi(),
1762                                "give the `return` a value of the expected type",
1763                                format!(" {value}"),
1764                                Applicability::HasPlaceholders,
1765                            );
1766                        }
1767                        err.span_label(cause.span, "return type is not `()`");
1768                    }
1769                    ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1770                        err = self.report_return_mismatched_types(
1771                            cause,
1772                            expected,
1773                            found,
1774                            coercion_error,
1775                            fcx,
1776                            blk_id,
1777                            expression,
1778                        );
1779                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1780                    }
1781                    ObligationCauseCode::ReturnValue(return_expr_id) => {
1782                        err = self.report_return_mismatched_types(
1783                            cause,
1784                            expected,
1785                            found,
1786                            coercion_error,
1787                            fcx,
1788                            return_expr_id,
1789                            expression,
1790                        );
1791                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1792                    }
1793                    ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
1794                        arm_span,
1795                        arm_ty,
1796                        prior_arm_ty,
1797                        ref prior_non_diverging_arms,
1798                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1799                        ..
1800                    }) => {
1801                        err = fcx.err_ctxt().report_mismatched_types(
1802                            cause,
1803                            fcx.param_env,
1804                            expected,
1805                            found,
1806                            coercion_error,
1807                        );
1808                        // Check that we're actually in the second or later arm
1809                        if prior_non_diverging_arms.len() > 0 {
1810                            self.suggest_boxing_tail_for_return_position_impl_trait(
1811                                fcx,
1812                                &mut err,
1813                                rpit_def_id,
1814                                arm_ty,
1815                                prior_arm_ty,
1816                                prior_non_diverging_arms
1817                                    .iter()
1818                                    .chain(std::iter::once(&arm_span))
1819                                    .copied(),
1820                            );
1821                        }
1822                    }
1823                    ObligationCauseCode::IfExpression {
1824                        expr_id,
1825                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1826                    } => {
1827                        let hir::Node::Expr(hir::Expr {
1828                            kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1829                            ..
1830                        }) = fcx.tcx.hir_node(expr_id)
1831                        else {
1832                            unreachable!();
1833                        };
1834                        err = fcx.err_ctxt().report_mismatched_types(
1835                            cause,
1836                            fcx.param_env,
1837                            expected,
1838                            found,
1839                            coercion_error,
1840                        );
1841                        let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1842                        let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1843                        // Don't suggest wrapping whole block in `Box::new`.
1844                        if then_span != then_expr.span && else_span != else_expr.span {
1845                            let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1846                            let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1847                            self.suggest_boxing_tail_for_return_position_impl_trait(
1848                                fcx,
1849                                &mut err,
1850                                rpit_def_id,
1851                                then_ty,
1852                                else_ty,
1853                                [then_span, else_span].into_iter(),
1854                            );
1855                        }
1856                    }
1857                    _ => {
1858                        err = fcx.err_ctxt().report_mismatched_types(
1859                            cause,
1860                            fcx.param_env,
1861                            expected,
1862                            found,
1863                            coercion_error,
1864                        );
1865                    }
1866                }
1867
1868                augment_error(&mut err);
1869
1870                if let Some(expr) = expression {
1871                    if let hir::ExprKind::Loop(
1872                        block,
1873                        _,
1874                        loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1875                        _,
1876                    ) = expr.kind
1877                    {
1878                        let loop_type = if loop_src == hir::LoopSource::While {
1879                            "`while` loops"
1880                        } else {
1881                            "`for` loops"
1882                        };
1883
1884                        err.note(format!("{loop_type} evaluate to unit type `()`"));
1885                        if loop_src == hir::LoopSource::While
1886                            && let Some(pat) = irrefutable_if_let_expr(block)
1887                        {
1888                            err.span_label(
1889                                pat.span,
1890                                "this pattern always matches, consider using `loop` instead",
1891                            );
1892                        }
1893                    }
1894
1895                    fcx.emit_coerce_suggestions(
1896                        &mut err,
1897                        expr,
1898                        found,
1899                        expected,
1900                        None,
1901                        Some(coercion_error),
1902                    );
1903                }
1904
1905                let reported = err.emit_unless_delay(unsized_return);
1906
1907                self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1908            }
1909        }
1910    }
1911
1912    fn suggest_boxing_tail_for_return_position_impl_trait(
1913        &self,
1914        fcx: &FnCtxt<'_, 'tcx>,
1915        err: &mut Diag<'_>,
1916        rpit_def_id: LocalDefId,
1917        a_ty: Ty<'tcx>,
1918        b_ty: Ty<'tcx>,
1919        arm_spans: impl Iterator<Item = Span>,
1920    ) {
1921        let compatible = |ty: Ty<'tcx>| {
1922            fcx.probe(|_| {
1923                let ocx = ObligationCtxt::new(fcx);
1924                ocx.register_obligations(
1925                    fcx.tcx
1926                        .item_self_bounds(rpit_def_id)
1927                        .iter_identity()
1928                        .map(Unnormalized::skip_norm_wip)
1929                        .filter_map(|clause| {
1930                            let predicate = clause
1931                                .kind()
1932                                .map_bound(|clause| match clause {
1933                                    ty::ClauseKind::Trait(trait_pred) => {
1934                                        Some(ty::ClauseKind::Trait(
1935                                            trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1936                                        ))
1937                                    }
1938                                    ty::ClauseKind::Projection(proj_pred) => {
1939                                        Some(ty::ClauseKind::Projection(
1940                                            proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1941                                        ))
1942                                    }
1943                                    _ => None,
1944                                })
1945                                .transpose()?;
1946                            Some(Obligation::new(
1947                                fcx.tcx,
1948                                ObligationCause::dummy(),
1949                                fcx.param_env,
1950                                predicate,
1951                            ))
1952                        }),
1953                );
1954                ocx.try_evaluate_obligations().no_errors()
1955            })
1956        };
1957
1958        if !compatible(a_ty) || !compatible(b_ty) {
1959            return;
1960        }
1961
1962        let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1963        err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1964            start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1965            end_sp: rpid_def_span.shrink_to_hi(),
1966        });
1967
1968        let (starts, ends) =
1969            arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1970        err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1971    }
1972
1973    fn report_return_mismatched_types<'infcx>(
1974        &self,
1975        cause: &ObligationCause<'tcx>,
1976        expected: Ty<'tcx>,
1977        found: Ty<'tcx>,
1978        ty_err: TypeError<'tcx>,
1979        fcx: &'infcx FnCtxt<'_, 'tcx>,
1980        block_or_return_id: hir::HirId,
1981        expression: Option<&'tcx hir::Expr<'tcx>>,
1982    ) -> Diag<'infcx> {
1983        let mut err =
1984            fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1985
1986        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(..));
1987        let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1988        if let Some(expr) = expression
1989            && let hir::Node::Expr(&hir::Expr {
1990                kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1991                ..
1992            }) = parent
1993        {
1994            let needs_block =
1995                !#[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(..));
1996            fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1997        }
1998        // Verify that this is a tail expression of a function, otherwise the
1999        // label pointing out the cause for the type coercion will be wrong
2000        // as prior return coercions would not be relevant (#57664).
2001        if let Some(expr) = expression
2002            && due_to_block
2003        {
2004            fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
2005            let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
2006                &mut err,
2007                expr,
2008                expected,
2009                found,
2010                block_or_return_id,
2011            );
2012            if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
2013                && expected.is_unit()
2014                && !pointing_at_return_type
2015                // If the block is from an external macro or try (`?`) desugaring, then
2016                // do not suggest adding a semicolon, because there's nowhere to put it.
2017                // See issues #81943 and #87051.
2018                // Similarly, if the block is from a loop desugaring, then also do not
2019                // suggest adding a semicolon. See issue #150850.
2020                && cond_expr.span.desugaring_kind().is_none()
2021                && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
2022                && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
    _ => false,
}matches!(
2023                    cond_expr.kind,
2024                    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
2025                )
2026            {
2027                if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
2028                    cause.code()
2029                    && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
2030                    && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
2031                    && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
2032                    && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
2033                {
2034                    err.span_label(
2035                        cond_expr.span,
2036                        "`if` expressions without `else` arms expect their inner expression to be `()`",
2037                    );
2038                } else {
2039                    err.span_label(cond_expr.span, "expected this to be `()`");
2040                }
2041                if expr.can_have_side_effects() {
2042                    // Don't suggest semicolon after if expressions as it does not fix the issue
2043                    if !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
    hir::ExprKind::If(..) => true,
    _ => false,
}matches!(cond_expr.kind, hir::ExprKind::If(..)) {
2044                        fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
2045                    }
2046                }
2047            }
2048        }
2049
2050        // If this is due to an explicit `return`, suggest adding a return type.
2051        if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
2052            && !due_to_block
2053        {
2054            fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
2055        }
2056
2057        // If this is due to a block, then maybe we forgot a `return`/`break`.
2058        if due_to_block
2059            && let Some(expr) = expression
2060            && let Some(parent_fn_decl) =
2061                fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id))
2062        {
2063            fcx.suggest_missing_break_or_return_expr(
2064                &mut err,
2065                expr,
2066                parent_fn_decl,
2067                expected,
2068                found,
2069                block_or_return_id,
2070                fcx.body_def_id,
2071            );
2072        }
2073
2074        let is_return_position = fcx
2075            .tcx
2076            .hir_get_fn_id_for_return_block(block_or_return_id)
2077            .is_some_and(|fn_id| fn_id == fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id));
2078
2079        if is_return_position
2080            && let Some(sp) = fcx.ret_coercion_span.get()
2081            // If the closure has an explicit return type annotation, or if
2082            // the closure's return type has been inferred from outside
2083            // requirements (such as an Fn* trait bound), then a type error
2084            // may occur at the first return expression we see in the closure
2085            // (if it conflicts with the declared return type). Skip adding a
2086            // note in this case, since it would be incorrect.
2087            && let Some(fn_sig) = fcx.fn_sig()
2088            && fn_sig.output().is_ty_var()
2089        {
2090            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"));
2091        }
2092
2093        err
2094    }
2095
2096    /// Checks whether the return type is unsized via an obligation, which makes
2097    /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
2098    /// false but technically valid for typeck.
2099    fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
2100        if let Some(sig) = fcx.fn_sig() {
2101            !fcx.predicate_may_hold(&Obligation::new(
2102                fcx.tcx,
2103                ObligationCause::dummy(),
2104                fcx.param_env,
2105                ty::TraitRef::new(
2106                    fcx.tcx,
2107                    fcx.tcx.require_lang_item(LangItem::Sized, DUMMY_SP),
2108                    [sig.output()],
2109                ),
2110            ))
2111        } else {
2112            false
2113        }
2114    }
2115
2116    pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2117        if let Some(final_ty) = self.final_ty {
2118            final_ty
2119        } else {
2120            // If we only had inputs that were of type `!` (or no
2121            // inputs at all), then the final type is `!`.
2122            if !self.expressions.is_empty() {
    ::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
2123            fcx.tcx.types.never
2124        }
2125    }
2126}
2127
2128fn irrefutable_if_let_expr<'hir>(block: &hir::Block<'hir>) -> Option<&'hir hir::Pat<'hir>> {
2129    let hir::ExprKind::If(cond, _, _) = block.expr?.kind else {
2130        return None;
2131    };
2132    let hir::ExprKind::Let(let_expr) = cond.kind else {
2133        return None;
2134    };
2135    simple_irrefutable_pattern(let_expr.pat).then_some(let_expr.pat)
2136}
2137
2138fn simple_irrefutable_pattern(pat: &hir::Pat<'_>) -> bool {
2139    match pat.kind {
2140        hir::PatKind::Wild | hir::PatKind::Binding(_, _, _, None) => true,
2141        hir::PatKind::Tuple(pats, _) => pats.iter().all(simple_irrefutable_pattern),
2142        _ => false,
2143    }
2144}
2145
2146/// Recursively visit goals to decide whether an unsizing is possible.
2147/// `Break`s when it isn't, and an error should be raised.
2148/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2149struct CoerceVisitor<'a, 'tcx> {
2150    fcx: &'a FnCtxt<'a, 'tcx>,
2151    span: Span,
2152    /// Whether the coercion is impossible. If so we sometimes still try to
2153    /// coerce in these cases to emit better errors. This changes the behavior
2154    /// when hitting the recursion limit.
2155    errored: bool,
2156}
2157
2158impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2159    type Result = ControlFlow<()>;
2160
2161    fn span(&self) -> Span {
2162        self.span
2163    }
2164
2165    fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2166        let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2167            return ControlFlow::Continue(());
2168        };
2169
2170        // Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2171        // Otherwise there's nothing to do.
2172        if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2173            && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2174        {
2175            return ControlFlow::Continue(());
2176        }
2177
2178        match goal.result() {
2179            // If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2180            Ok(Certainty::Yes) => ControlFlow::Continue(()),
2181            Err(NoSolution) => {
2182                self.errored = true;
2183                // Even if we find no solution, continue recursing if we find a single candidate
2184                // for which we're shallowly certain it holds to get the right error source.
2185                if let [only_candidate] = &goal.candidates()[..]
2186                    && only_candidate.shallow_certainty() == Certainty::Yes
2187                {
2188                    only_candidate.visit_nested_no_probe(self)
2189                } else {
2190                    ControlFlow::Break(())
2191                }
2192            }
2193            Ok(Certainty::Maybe(_)) => {
2194                // FIXME: structurally normalize?
2195                if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2196                    && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2197                    && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2198                    && self.fcx.type_var_is_sized(vid)
2199                {
2200                    // We get here when trying to unsize a type variable to a `dyn Trait`,
2201                    // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2202                    // If the variable weren't sized, we may not need an unsizing coercion.
2203                    // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2204                    ControlFlow::Continue(())
2205                } else if let Some(cand) = goal.unique_applicable_candidate()
2206                    && cand.shallow_certainty() == Certainty::Yes
2207                {
2208                    cand.visit_nested_no_probe(self)
2209                } else {
2210                    ControlFlow::Break(())
2211                }
2212            }
2213        }
2214    }
2215
2216    fn on_recursion_limit(&mut self) -> Self::Result {
2217        if self.errored {
2218            // This prevents accidentally committing unfulfilled unsized coercions while trying to
2219            // find the error source for diagnostics.
2220            // See https://github.com/rust-lang/trait-system-refactor-initiative/issues/266.
2221            ControlFlow::Break(())
2222        } else {
2223            ControlFlow::Continue(())
2224        }
2225    }
2226}