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::ty::adjustment::{
53    Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
54    PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
58use rustc_span::{BytePos, DUMMY_SP, Span, span_bug};
59use rustc_trait_selection::infer::InferCtxtExt as _;
60use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
61use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
62use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
63use rustc_trait_selection::traits::{
64    self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
65};
66use smallvec::{SmallVec, smallvec};
67use tracing::{debug, instrument};
68
69use crate::FnCtxt;
70use crate::diagnostics::SuggestBoxingForReturnImplTrait;
71
72struct Coerce<'a, 'tcx> {
73    fcx: &'a FnCtxt<'a, 'tcx>,
74    cause: ObligationCause<'tcx>,
75    use_lub: bool,
76    /// Determines whether or not allow_two_phase_borrow is set on any
77    /// autoref adjustments we create while coercing. We don't want to
78    /// allow deref coercions to create two-phase borrows, at least initially,
79    /// but we do need two-phase borrows for function argument reborrows.
80    /// See #47489 and #48598
81    /// See docs on the "AllowTwoPhase" type for a more detailed discussion
82    allow_two_phase: AllowTwoPhase,
83    /// Whether we allow `NeverToAny` coercions. This is unsound if we're
84    /// coercing a place expression without it counting as a read in the MIR.
85    /// This is a side-effect of HIR not really having a great distinction
86    /// between places and values.
87    coerce_never: bool,
88}
89
90impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
91    type Target = FnCtxt<'a, 'tcx>;
92    fn deref(&self) -> &Self::Target {
93        self.fcx
94    }
95}
96
97type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
98
99/// Coercing a mutable reference to an immutable works, while
100/// coercing `&T` to `&mut T` should be forbidden.
101fn coerce_mutbls<'tcx>(
102    from_mutbl: hir::Mutability,
103    to_mutbl: hir::Mutability,
104) -> RelateResult<'tcx, ()> {
105    if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
106}
107
108/// This always returns `Ok(...)`.
109fn success<'tcx>(
110    adj: Vec<Adjustment<'tcx>>,
111    target: Ty<'tcx>,
112    obligations: PredicateObligations<'tcx>,
113) -> CoerceResult<'tcx> {
114    Ok(InferOk { value: (adj, target), obligations })
115}
116
117/// Data extracted from a reference (pinned or not) for coercion to a reference (pinned or not).
118struct CoerceMaybePinnedRef<'tcx> {
119    /// coercion source, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
120    a: Ty<'tcx>,
121    /// coercion target, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
122    b: Ty<'tcx>,
123    /// referent type of the source
124    a_ty: Ty<'tcx>,
125    /// pinnedness of the source
126    a_pin: ty::Pinnedness,
127    /// mutability of the source
128    a_mut: ty::Mutability,
129    /// region of the source
130    a_r: ty::Region<'tcx>,
131    /// pinnedness of the target
132    b_pin: ty::Pinnedness,
133    /// mutability of the target
134    b_mut: ty::Mutability,
135}
136
137/// Whether to force a leak check to occur in `Coerce::unify_raw`.
138/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
139///
140/// FIXME: We may want to change type relations to always leak-check
141/// after exiting a binder, at which point we will always do so and
142/// no longer need to handle this explicitly
143enum ForceLeakCheck {
144    Yes,
145    No,
146}
147
148impl<'f, 'tcx> Coerce<'f, 'tcx> {
149    fn new(
150        fcx: &'f FnCtxt<'f, 'tcx>,
151        cause: ObligationCause<'tcx>,
152        allow_two_phase: AllowTwoPhase,
153        coerce_never: bool,
154    ) -> Self {
155        Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
156    }
157
158    fn unify_raw(
159        &self,
160        a: Ty<'tcx>,
161        b: Ty<'tcx>,
162        leak_check: ForceLeakCheck,
163    ) -> InferResult<'tcx, Ty<'tcx>> {
164        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:164",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(164u32),
                        ::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);
165        self.commit_if_ok(|snapshot| {
166            let outer_universe = self.infcx.universe();
167
168            let at = self.at(&self.cause, self.fcx.param_env);
169
170            let res = if self.use_lub {
171                at.lub(b, a)
172            } else {
173                at.sup(DefineOpaqueTypes::Yes, b, a)
174                    .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
175            };
176
177            // In the new solver, lazy norm may allow us to shallowly equate
178            // more types, but we emit possibly impossible-to-satisfy obligations.
179            // Filter these cases out to make sure our coercion is more accurate.
180            let res = match res {
181                Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
182                    let ocx = ObligationCtxt::new(self);
183                    ocx.register_obligations(obligations);
184                    if ocx.try_evaluate_obligations().no_errors() {
185                        Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
186                    } else {
187                        Err(TypeError::Mismatch)
188                    }
189                }
190                res => res,
191            };
192
193            // We leak check here mostly because lub operations are
194            // kind of scuffed around binders. Instead of computing an actual
195            // lub'd binder we instead:
196            // - Equate the binders
197            // - Return the lhs of the lub operation
198            //
199            // This may lead to incomplete type inference for the resulting type
200            // of a `match` or `if .. else`, etc. This is a backwards compat
201            // hazard for if/when we start handling `lub` more correctly.
202            //
203            // In order to actually ensure that equating the binders *does*
204            // result in equal binders, and that the lhs is actually a supertype
205            // of the rhs, we must perform a leak check here.
206            if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
    ForceLeakCheck::Yes => true,
    _ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
207                self.leak_check(outer_universe, Some(snapshot))?;
208            }
209
210            res
211        })
212    }
213
214    /// Unify two types (using sub or lub).
215    fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
216        self.unify_raw(a, b, leak_check)
217            .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
218    }
219
220    /// Unify two types (using sub or lub) and produce a specific coercion.
221    fn unify_and(
222        &self,
223        a: Ty<'tcx>,
224        b: Ty<'tcx>,
225        adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
226        final_adjustment: Adjust,
227        leak_check: ForceLeakCheck,
228    ) -> CoerceResult<'tcx> {
229        self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
230            success(
231                adjustments
232                    .into_iter()
233                    .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
234                    .collect(),
235                ty,
236                obligations,
237            )
238        })
239    }
240
241    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::INFO <=
                ::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",
                                "rustc_hir_typeck::coercion", ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                ::tracing_core::__macro_support::Option::Some(241u32),
                                ::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::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::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();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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;
                    }
                    {
                        let a = self.shallow_resolve(a);
                        let b = self.shallow_resolve(b);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:246",
                                                "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                                ::tracing_core::__macro_support::Option::Some(246u32),
                                                ::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.tys({0:?} => {1:?})",
                                                                            a, b) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if a.is_never() {
                            if self.coerce_never {
                                return success(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                                [Adjustment { kind: Adjust::NeverToAny, target: b }])), b,
                                        PredicateObligations::new());
                            } else { return self.unify(a, b, ForceLeakCheck::No); }
                        }
                        if a.is_ty_var() {
                            return self.coerce_from_inference_variable(a, b);
                        }
                        let unsize =
                            self.commit_if_ok(|_| self.coerce_unsized(a, b));
                        match unsize {
                            Ok(_) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:277",
                                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(277u32),
                                                        ::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: unsize successful")
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                return unsize;
                            }
                            Err(error) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:281",
                                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(281u32),
                                                        ::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("error")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("error");
                                                                            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: unsize failed")
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error)
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                            }
                        }
                        match *b.kind() {
                            ty::RawPtr(_, b_mutbl) => {
                                return self.coerce_to_raw_ptr(a, b, b_mutbl);
                            }
                            ty::Ref(r_b, _, mutbl_b) => {
                                if let Some(pin_ref_to_ref) =
                                        self.maybe_pin_ref_to_ref(a, b) {
                                    return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
                                }
                                return self.coerce_to_ref(a, b, r_b, mutbl_b);
                            }
                            _ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
                                return self.coerce_to_pin_ref(to_pin_ref);
                            }
                            ty::Adt(_, _) if
                                self.tcx.features().reborrow() &&
                                    self.fcx.infcx.type_implements_trait(self.tcx.lang_items().reborrow().expect("Unexpectedly using core/std without reborrow"),
                                            [b], self.fcx.param_env).must_apply_modulo_regions() => {
                                let reborrow_coerce =
                                    self.commit_if_ok(|_| self.coerce_reborrow(a, b));
                                if reborrow_coerce.is_ok() { return reborrow_coerce; }
                            }
                            _ => {}
                        }
                        match *a.kind() {
                            ty::FnDef(..) => { self.coerce_from_fn_item(a, b) }
                            ty::FnPtr(a_sig_tys, a_hdr) => {
                                self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
                            }
                            ty::Closure(..) => { self.coerce_closure_to_fn(a, b) }
                            ty::Adt(_, _) if self.tcx.features().reborrow() => {
                                let reborrow_coerce =
                                    self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
                                if reborrow_coerce.is_ok() {
                                    reborrow_coerce
                                } else { self.unify(a, b, ForceLeakCheck::No) }
                            }
                            _ => { self.unify(a, b, ForceLeakCheck::No) }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:241",
                        "rustc_hir_typeck::coercion", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(241u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(self), ret)]
242    fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
243        // First, remove any resolved type variables (at the top level, at least):
244        let a = self.shallow_resolve(a);
245        let b = self.shallow_resolve(b);
246        debug!("Coerce.tys({:?} => {:?})", a, b);
247
248        // Coercing from `!` to any type is allowed:
249        if a.is_never() {
250            if self.coerce_never {
251                return success(
252                    vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
253                    b,
254                    PredicateObligations::new(),
255                );
256            } else {
257                // Otherwise the only coercion we can do is unification.
258                return self.unify(a, b, ForceLeakCheck::No);
259            }
260        }
261
262        // Coercing *from* an unresolved inference variable means that
263        // we have no information about the source type. This will always
264        // ultimately fall back to some form of subtyping.
265        if a.is_ty_var() {
266            return self.coerce_from_inference_variable(a, b);
267        }
268
269        // Consider coercing the subtype to a DST
270        //
271        // NOTE: this is wrapped in a `commit_if_ok` because it creates
272        // a "spurious" type variable, and we don't want to have that
273        // type variable in memory if the coercion fails.
274        let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
275        match unsize {
276            Ok(_) => {
277                debug!("coerce: unsize successful");
278                return unsize;
279            }
280            Err(error) => {
281                debug!(?error, "coerce: unsize failed");
282            }
283        }
284
285        // Examine the target type and consider type-specific coercions, such
286        // as auto-borrowing, coercing pointer mutability, pin-ergonomics, or
287        // generic reborrow.
288        match *b.kind() {
289            ty::RawPtr(_, b_mutbl) => {
290                return self.coerce_to_raw_ptr(a, b, b_mutbl);
291            }
292            ty::Ref(r_b, _, mutbl_b) => {
293                if let Some(pin_ref_to_ref) = self.maybe_pin_ref_to_ref(a, b) {
294                    return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
295                }
296                return self.coerce_to_ref(a, b, r_b, mutbl_b);
297            }
298            _ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
299                return self.coerce_to_pin_ref(to_pin_ref);
300            }
301            ty::Adt(_, _)
302                if self.tcx.features().reborrow()
303                    && self
304                        .fcx
305                        .infcx
306                        .type_implements_trait(
307                            self.tcx
308                                .lang_items()
309                                .reborrow()
310                                .expect("Unexpectedly using core/std without reborrow"),
311                            [b],
312                            self.fcx.param_env,
313                        )
314                        .must_apply_modulo_regions() =>
315            {
316                let reborrow_coerce = self.commit_if_ok(|_| self.coerce_reborrow(a, b));
317                if reborrow_coerce.is_ok() {
318                    return reborrow_coerce;
319                }
320            }
321            _ => {}
322        }
323
324        match *a.kind() {
325            ty::FnDef(..) => {
326                // Function items are coercible to any closure
327                // type; function pointers are not (that would
328                // require double indirection).
329                // Additionally, we permit coercion of function
330                // items to drop the unsafe qualifier.
331                self.coerce_from_fn_item(a, b)
332            }
333            ty::FnPtr(a_sig_tys, a_hdr) => {
334                // We permit coercion of fn pointers to drop the
335                // unsafe qualifier.
336                self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
337            }
338            ty::Closure(..) => {
339                // Non-capturing closures are coercible to
340                // function pointers or unsafe function pointers.
341                // It cannot convert closures that require unsafe.
342                self.coerce_closure_to_fn(a, b)
343            }
344            ty::Adt(_, _) if self.tcx.features().reborrow() => {
345                let reborrow_coerce = self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
346                if reborrow_coerce.is_ok() {
347                    reborrow_coerce
348                } else {
349                    self.unify(a, b, ForceLeakCheck::No)
350                }
351            }
352            _ => {
353                // Otherwise, just use unification rules.
354                self.unify(a, b, ForceLeakCheck::No)
355            }
356        }
357    }
358
359    /// Coercing *from* an inference variable. In this case, we have no information
360    /// about the source type, so we can't really do a true coercion and we always
361    /// fall back to subtyping (`unify_and`).
362    fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
363        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:363",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(363u32),
                        ::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);
364        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);
365        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);
366
367        if b.is_ty_var() {
368            let mut obligations = PredicateObligations::with_capacity(2);
369            let mut push_coerce_obligation = |a, b| {
370                obligations.push(Obligation::new(
371                    self.tcx(),
372                    self.cause.clone(),
373                    self.param_env,
374                    ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
375                ));
376            };
377
378            let target_ty = if self.use_lub {
379                // When computing the lub, we create a new target
380                // and coerce both `a` and `b` to it.
381                let target_ty = self.next_ty_var(self.cause.span);
382                push_coerce_obligation(a, target_ty);
383                push_coerce_obligation(b, target_ty);
384                target_ty
385            } else {
386                // When subtyping, we don't need to create a new target
387                // as we only coerce `a` to `b`.
388                push_coerce_obligation(a, b);
389                b
390            };
391
392            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:392",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(392u32),
                        ::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!(
393                "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
394                target_ty, obligations
395            );
396            success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
397        } else {
398            // One unresolved type variable: just apply subtyping, we may be able
399            // to do something useful.
400            self.unify(a, b, ForceLeakCheck::No)
401        }
402    }
403
404    /// Handles coercing some arbitrary type `a` to some reference (`b`). This
405    /// handles a few cases:
406    /// - Introducing reborrows to give more flexible lifetimes
407    /// - Deref coercions to allow `&T` to coerce to `&T::Target`
408    /// - Coercing mutable references to immutable references
409    /// These coercions can be freely intermixed, for example we are able to
410    /// coerce `&mut T` to `&mut T::Target`.
411    fn coerce_to_ref(
412        &self,
413        a: Ty<'tcx>,
414        b: Ty<'tcx>,
415        r_b: ty::Region<'tcx>,
416        mutbl_b: hir::Mutability,
417    ) -> CoerceResult<'tcx> {
418        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:418",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(418u32),
                        ::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);
419        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);
420        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);
421
422        let (r_a, mt_a) = match *a.kind() {
423            ty::Ref(r_a, ty, mutbl) => {
424                coerce_mutbls(mutbl, mutbl_b)?;
425                (r_a, ty::TypeAndMut { ty, mutbl })
426            }
427            _ => return self.unify(a, b, ForceLeakCheck::No),
428        };
429
430        // Look at each step in the `Deref` chain and check if
431        // any of the autoref'd `Target` types unify with the
432        // coercion target.
433        //
434        // For example when coercing from `&mut Vec<T>` to `&M [T]` we
435        // have three deref steps:
436        // 1. `&mut Vec<T>`, skip autoref
437        // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
438        //     - `&M Vec<T>` does not unify with `&M [T]`
439        // 3. `[T]`, autoref'd ty: `&M [T]`
440        //     - `&M [T]` does unify with `&M [T]`
441        let mut first_error = None;
442        let mut r_borrow_var = None;
443        let mut autoderef = self.autoderef(self.cause.span, a);
444        let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
445            if autoderefs == 0 {
446                // Don't autoref the first step as otherwise we'd allow
447                // coercing `&T` to `&&T`.
448                return None;
449            }
450
451            // The logic here really shouldn't exist. We don't care about free
452            // lifetimes during HIR typeck. Unfortunately later parts of this
453            // function rely on structural identity of the autoref'd deref'd ty.
454            //
455            // This means that what region we use here actually impacts whether
456            // we emit a reborrow coercion or not which can affect diagnostics
457            // and capture analysis (which in turn affects borrowck).
458            let r = if !self.use_lub {
459                r_b
460            } else if autoderefs == 1 {
461                r_a
462            } else {
463                if r_borrow_var.is_none() {
464                    // create var lazily, at most once
465                    let coercion = RegionVariableOrigin::Coercion(self.cause.span);
466                    let r = self.next_region_var(coercion);
467                    r_borrow_var = Some(r);
468                }
469                r_borrow_var.unwrap()
470            };
471
472            let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
473
474            // Note that we unify the autoref'd `Target` type with `b` rather than
475            // the `Target` type with the pointee of `b`. This is necessary
476            // to properly account for the differing variances of the pointees
477            // of `&` vs `&mut` references.
478            match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
479                Ok(ok) => Some(ok),
480                Err(err) => {
481                    if first_error.is_none() {
482                        first_error = Some(err);
483                    }
484                    None
485                }
486            }
487        });
488
489        // Extract type or return an error. We return the first error
490        // we got, which should be from relating the "base" type
491        // (e.g., in example above, the failure from relating `Vec<T>`
492        // to the target type), since that should be the least
493        // confusing.
494        let Some(InferOk { value: coerced_a, mut obligations }) = found else {
495            if let Some(first_error) = first_error {
496                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:496",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(496u32),
                        ::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);
497                return Err(first_error);
498            } else {
499                // This may happen in the new trait solver since autoderef requires
500                // the pointee to be structurally normalizable, or else it'll just bail.
501                // So when we have a type like `&<not well formed>`, then we get no
502                // autoderef steps (even though there should be at least one). That means
503                // we get no type mismatches, since the loop above just exits early.
504                return Err(TypeError::Mismatch);
505            }
506        };
507
508        if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
509            // As a special case, if we would produce `&'a *x`, that's
510            // a total no-op. We end up with the type `&'a T` just as
511            // we started with. In that case, just skip it altogether.
512            //
513            // Unfortunately, this can actually effect capture analysis
514            // which in turn means this effects borrow checking. This can
515            // also effect diagnostics.
516            // FIXME(BoxyUwU): we should always emit reborrow coercions
517            //
518            // Note that for `&mut`, we DO want to reborrow --
519            // otherwise, this would be a move, which might be an
520            // error. For example `foo(self.x)` where `self` and
521            // `self.x` both have `&mut `type would be a move of
522            // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
523            // which is a borrow.
524            if !mutbl_b.is_not() {
    ::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
525            return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
526        }
527
528        let InferOk { value: mut adjustments, obligations: o } =
529            self.adjust_steps_as_infer_ok(&autoderef);
530        obligations.extend(o);
531        obligations.extend(autoderef.into_obligations());
532
533        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!(
534            matches!(coerced_a.kind(), ty::Ref(..)),
535            "expected a ref type, got {:?}",
536            coerced_a
537        );
538
539        // Now apply the autoref
540        let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
541        adjustments
542            .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
543
544        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:544",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(544u32),
                        ::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);
545
546        success(adjustments, coerced_a, obligations)
547    }
548
549    /// Performs [unsized coercion] by emulating a fulfillment loop on a
550    /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
551    /// are successfully selected.
552    ///
553    /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
554    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(554u32),
                                    ::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:556",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(556u32),
                                    ::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:564",
                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                        ::tracing_core::__macro_support::Option::Some(564u32),
                                        ::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:568",
                                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                        ::tracing_core::__macro_support::Option::Some(568u32),
                                        ::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:622",
                                            "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                            ::tracing_core::__macro_support::Option::Some(622u32),
                                            ::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")]
555    fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
556        debug!(?source, ?target);
557        debug_assert!(self.shallow_resolve(source) == source);
558        debug_assert!(self.shallow_resolve(target) == target);
559
560        // We don't apply any coercions incase either the source or target
561        // aren't sufficiently well known but tend to instead just equate
562        // them both.
563        if source.is_ty_var() {
564            debug!("coerce_unsized: source is a TyVar, bailing out");
565            return Err(TypeError::Mismatch);
566        }
567        if target.is_ty_var() {
568            debug!("coerce_unsized: target is a TyVar, bailing out");
569            return Err(TypeError::Mismatch);
570        }
571
572        // This is an optimization because coercion is one of the most common
573        // operations that we do in typeck, since it happens at every assignment
574        // and call arg (among other positions).
575        //
576        // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
577        // That's because these are built-in types for which a core-provided impl
578        // doesn't exist, and for which a user-written impl is invalid.
579        //
580        // This is technically incomplete when users write impossible bounds like
581        // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
582        // and coercion is allowed to be incomplete. The only case where this matters
583        // is impossible bounds.
584        //
585        // Note that some of these types implement `LHS: Unsize<RHS>`, but they
586        // do not implement *`CoerceUnsized`* which is the root obligation of the
587        // check below.
588        match target.kind() {
589            ty::Bool
590            | ty::Char
591            | ty::Int(_)
592            | ty::Uint(_)
593            | ty::Float(_)
594            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
595            | ty::Str
596            | ty::Array(_, _)
597            | ty::Slice(_)
598            | ty::FnDef(_, _)
599            | ty::FnPtr(_, _)
600            | ty::Dynamic(_, _)
601            | ty::Closure(_, _)
602            | ty::CoroutineClosure(_, _)
603            | ty::Coroutine(_, _)
604            | ty::CoroutineWitness(_, _)
605            | ty::Never
606            | ty::Tuple(_) => return Err(TypeError::Mismatch),
607            _ => {}
608        }
609        // `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
610        // so we fast path bail out here
611        if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
612            && source_pointee.is_str()
613            && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
614            && target_pointee.is_str()
615        {
616            return Err(TypeError::Mismatch);
617        }
618
619        let traits =
620            (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
621        let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
622            debug!("missing Unsize or CoerceUnsized traits");
623            return Err(TypeError::Mismatch);
624        };
625
626        // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
627        // a DST unless we have to. This currently comes out in the wash since
628        // we can't unify [T] with U. But to properly support DST, we need to allow
629        // that, at which point we will need extra checks on the target here.
630
631        // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
632        let reborrow = match (source.kind(), target.kind()) {
633            (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
634                coerce_mutbls(mutbl_a, mutbl_b)?;
635
636                let coercion = RegionVariableOrigin::Coercion(self.cause.span);
637                let r_borrow = self.next_region_var(coercion);
638
639                // We don't allow two-phase borrows here, at least for initial
640                // implementation. If it happens that this coercion is a function argument,
641                // the reborrow in coerce_borrowed_ptr will pick it up.
642                let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
643
644                Some((
645                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
646                    Adjustment {
647                        kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
648                        target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
649                    },
650                ))
651            }
652            (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
653                coerce_mutbls(mt_a, mt_b)?;
654
655                Some((
656                    Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
657                    Adjustment {
658                        kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
659                        target: Ty::new_ptr(self.tcx, ty_a, mt_b),
660                    },
661                ))
662            }
663            _ => None,
664        };
665        let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
666
667        // Setup either a subtyping or a LUB relationship between
668        // the `CoerceUnsized` target type and the expected type.
669        // We only have the latter, so we use an inference variable
670        // for the former and let type inference do the rest.
671        let coerce_target = self.next_ty_var(self.cause.span);
672
673        let mut coercion = self.unify_and(
674            coerce_target,
675            target,
676            reborrow.map(|(deref, autoref)| [deref, autoref]).into_flat_iter(),
677            Adjust::Pointer(PointerCoercion::Unsize),
678            ForceLeakCheck::No,
679        )?;
680
681        // Create an obligation for `Source: CoerceUnsized<Target>`.
682        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
683        let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
684        let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
685
686        if self.next_trait_solver() {
687            coercion.obligations.push(obligation);
688
689            if self
690                .infcx
691                .visit_proof_tree(
692                    Goal::new(self.tcx, self.param_env, pred),
693                    &mut CoerceVisitor { fcx: self.fcx, span: self.cause.span, errored: false },
694                )
695                .is_break()
696            {
697                return Err(TypeError::Mismatch);
698            }
699        } else {
700            self.coerce_unsized_old_solver(
701                obligation,
702                &mut coercion,
703                coerce_unsized_did,
704                unsize_did,
705            )?;
706        }
707
708        Ok(coercion)
709    }
710
711    fn coerce_unsized_old_solver(
712        &self,
713        obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
714        coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
715        coerce_unsized_did: DefId,
716        unsize_did: DefId,
717    ) -> Result<(), TypeError<'tcx>> {
718        let mut selcx = traits::SelectionContext::new(self);
719        // Use a FIFO queue for this custom fulfillment procedure.
720        //
721        // A Vec (or SmallVec) is not a natural choice for a queue. However,
722        // this code path is hot, and this queue usually has a max length of 1
723        // and almost never more than 3. By using a SmallVec we avoid an
724        // allocation, at the (very small) cost of (occasionally) having to
725        // shift subsequent elements down when removing the front element.
726        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];
727
728        // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
729        // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
730        // inference might unify those two inner type variables later.
731        let traits = [coerce_unsized_did, unsize_did];
732        while !queue.is_empty() {
733            let obligation = queue.remove(0);
734            let trait_pred = match obligation.predicate.kind().no_bound_vars() {
735                Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
736                    if traits.contains(&trait_pred.def_id()) =>
737                {
738                    self.deeply_resolve_ignoring_regions(trait_pred)
739                }
740                _ => {
741                    coercion.obligations.push(obligation);
742                    continue;
743                }
744            };
745            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:745",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(745u32),
                        ::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);
746            match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
747                // Uncertain or unimplemented.
748                Ok(None) => {
749                    if trait_pred.def_id() == unsize_did {
750                        let self_ty = trait_pred.self_ty();
751                        let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
752                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:752",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(752u32),
                        ::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);
753                        match (self_ty.kind(), unsize_ty.kind()) {
754                            (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
755                                if self.type_var_is_sized(v) =>
756                            {
757                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:757",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(757u32),
                        ::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);
758                                coercion.obligations.push(obligation);
759                                // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
760                                // for unsizing.
761                            }
762                            _ => {
763                                // Some other case for `$0: Unsize<Something>`. Note that we
764                                // hit this case even if `Something` is a sized type, so just
765                                // don't do the coercion.
766                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:766",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(766u32),
                        ::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");
767                                return Err(TypeError::Mismatch);
768                            }
769                        }
770                    } else {
771                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:771",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(771u32),
                        ::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");
772                        return Err(TypeError::Mismatch);
773                    }
774                }
775                Err(SelectionError::Unimplemented) => {
776                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:776",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(776u32),
                        ::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");
777                    return Err(TypeError::Mismatch);
778                }
779
780                Err(SelectionError::TraitDynIncompatible(_)) => {
781                    // Dyn compatibility errors in coercion will *always* be due to the
782                    // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
783                    // written in source somewhere (otherwise we will never have lowered
784                    // the dyn trait from HIR to middle).
785                    //
786                    // There's no reason to emit yet another dyn compatibility error,
787                    // especially since the span will differ slightly and thus not be
788                    // deduplicated at all!
789                    self.fcx.set_tainted_by_errors(
790                        self.fcx
791                            .dcx()
792                            .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
793                    );
794                }
795                Err(err) => {
796                    let guar = self.err_ctxt().report_selection_error(
797                        obligation.clone(),
798                        &obligation,
799                        &err,
800                    );
801                    self.fcx.set_tainted_by_errors(guar);
802                    // Treat this like an obligation and follow through
803                    // with the unsizing - the lack of a coercion should
804                    // be silent, as it causes a type mismatch later.
805                }
806                Ok(Some(ImplSource::UserDefined(impl_source))) => {
807                    queue.extend(impl_source.nested);
808                    // Certain incoherent `CoerceUnsized` implementations may cause ICEs,
809                    // so check the impl's validity. Taint the body so that we don't try
810                    // to evaluate these invalid coercions in CTFE. We only need to do this
811                    // for local impls, since upstream impls should be valid.
812                    if impl_source.impl_def_id.is_local()
813                        && let Err(guar) =
814                            self.tcx.ensure_result().coerce_unsized_info(impl_source.impl_def_id)
815                    {
816                        self.fcx.set_tainted_by_errors(guar);
817                    }
818                }
819                Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
820            }
821        }
822
823        Ok(())
824    }
825
826    /// Create an obligation for `ty: Unpin`, where .
827    fn unpin_obligation(
828        &self,
829        source: Ty<'tcx>,
830        target: Ty<'tcx>,
831        ty: Ty<'tcx>,
832    ) -> PredicateObligation<'tcx> {
833        let pred = ty::TraitRef::new(
834            self.tcx,
835            self.tcx.require_lang_item(LangItem::Unpin, self.cause.span),
836            [ty],
837        );
838        let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
839        PredicateObligation::new(self.tcx, cause, self.param_env, pred)
840    }
841
842    /// Checks if the given types are compatible for coercion from a pinned reference to a normal reference.
843    fn maybe_pin_ref_to_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
844        if !self.tcx.features().pin_ergonomics() {
845            return None;
846        }
847        if let Some((a_ty, a_pin @ ty::Pinnedness::Pinned, a_mut, a_r)) = a.maybe_pinned_ref()
848            && let Some((_, b_pin @ ty::Pinnedness::Not, b_mut, _)) = b.maybe_pinned_ref()
849        {
850            return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
851        }
852        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:852",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(852u32),
                        ::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);
853        None
854    }
855
856    /// Coerces from a pinned reference to a normal reference.
857    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(857u32),
                                    ::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")]
858    fn coerce_pin_ref_to_ref(
859        &self,
860        CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
861            'tcx,
862        >,
863    ) -> CoerceResult<'tcx> {
864        debug_assert!(self.shallow_resolve(a) == a);
865        debug_assert!(self.shallow_resolve(b) == b);
866        debug_assert!(self.tcx.features().pin_ergonomics());
867        debug_assert_eq!(a_pin, ty::Pinnedness::Pinned);
868        debug_assert_eq!(b_pin, ty::Pinnedness::Not);
869
870        coerce_mutbls(a_mut, b_mut)?;
871
872        let unpin_obligation = self.unpin_obligation(a, b, a_ty);
873
874        let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
875        let mut coerce = self.unify_and(
876            a,
877            b,
878            [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Pin), target: a_ty }],
879            Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut, self.allow_two_phase))),
880            ForceLeakCheck::No,
881        )?;
882        coerce.obligations.push(unpin_obligation);
883        Ok(coerce)
884    }
885
886    /// Checks if the given types are compatible for coercion to a pinned reference.
887    fn maybe_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
888        if !self.tcx.features().pin_ergonomics() {
889            return None;
890        }
891        if let Some((a_ty, a_pin, a_mut, a_r)) = a.maybe_pinned_ref()
892            && let Some((_, b_pin @ ty::Pinnedness::Pinned, b_mut, _)) = b.maybe_pinned_ref()
893        {
894            return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
895        }
896        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:896",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(896u32),
                        ::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);
897        None
898    }
899
900    /// Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:
901    ///
902    /// Currently we only support the following coercions:
903    /// - Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
904    /// - Reborrowing `Pin<&T>` -> `Pin<&T>`
905    /// - Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
906    /// - Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
907    /// - Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`
908    ///
909    /// In the future we might want to support other reborrowing coercions, such as:
910    /// - `Pin<Box<T>>` as `Pin<&T>`
911    /// - `Pin<Box<T>>` as `Pin<&mut T>`
912    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(912u32),
                                    ::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")]
913    fn coerce_to_pin_ref(
914        &self,
915        CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
916            'tcx,
917        >,
918    ) -> CoerceResult<'tcx> {
919        debug_assert!(self.shallow_resolve(a) == a);
920        debug_assert!(self.shallow_resolve(b) == b);
921        debug_assert!(self.tcx.features().pin_ergonomics());
922        debug_assert_eq!(b_pin, ty::Pinnedness::Pinned);
923
924        // We need to deref the reference first before we reborrow it to a pinned reference.
925        let (deref, unpin_obligation) = match a_pin {
926            // no `Unpin` required when reborrowing a pinned reference to a pinned reference
927            ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
928            // `Unpin` required when reborrowing a non-pinned reference to a pinned reference
929            ty::Pinnedness::Not => {
930                (DerefAdjustKind::Builtin, Some(self.unpin_obligation(a, b, a_ty)))
931            }
932        };
933
934        coerce_mutbls(a_mut, b_mut)?;
935
936        // update a with b's mutability since we'll be coercing mutability
937        let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
938
939        // To complete the reborrow, we need to make sure we can unify the inner types, and if so we
940        // add the adjustments.
941        let mut coerce = self.unify_and(
942            a,
943            b,
944            [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
945            Adjust::Borrow(AutoBorrow::Pin(b_mut)),
946            ForceLeakCheck::No,
947        )?;
948
949        coerce.obligations.extend(unpin_obligation);
950        Ok(coerce)
951    }
952
953    /// Applies generic exclusive reborrowing on type implementing `Reborrow`.
954    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(954u32),
                                    ::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")]
955    fn coerce_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
956        debug_assert!(self.shallow_resolve(a) == a);
957        debug_assert!(self.shallow_resolve(b) == b);
958
959        // We need to make sure the two types are compatible for reborrow.
960        let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
961            return Err(TypeError::Mismatch);
962        };
963        if a_def.did() == b_def.did() {
964            // Reborrow is applicable here
965            self.unify_and(
966                a,
967                b,
968                [],
969                Adjust::GenericReborrow(ty::Mutability::Mut),
970                ForceLeakCheck::No,
971            )
972        } else {
973            // FIXME: CoerceShared check goes here, error for now
974            Err(TypeError::Mismatch)
975        }
976    }
977
978    /// Applies generic exclusive reborrowing on type implementing `Reborrow`.
979    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(979u32),
                                    ::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")]
980    fn coerce_shared_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
981        debug_assert!(self.shallow_resolve(a) == a);
982        debug_assert!(self.shallow_resolve(b) == b);
983
984        // We need to make sure the two types are compatible for reborrow.
985        let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
986            return Err(TypeError::Mismatch);
987        };
988        if a_def.did() == b_def.did() {
989            // CoerceShared cannot be T -> T.
990            return Err(TypeError::Mismatch);
991        }
992        let Some(coerce_shared_trait_did) = self.tcx.lang_items().coerce_shared() else {
993            return Err(TypeError::Mismatch);
994        };
995        let coerce_shared_trait_ref = ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
996        let obligation = traits::Obligation::new(
997            self.tcx,
998            ObligationCause::dummy(),
999            self.param_env,
1000            ty::Binder::dummy(coerce_shared_trait_ref),
1001        );
1002        let ocx = ObligationCtxt::new(&self.infcx);
1003        ocx.register_obligation(obligation);
1004        let errs = ocx.evaluate_obligations_error_on_ambiguity();
1005        if errs.no_errors() {
1006            Ok(InferOk {
1007                value: (
1008                    vec![Adjustment {
1009                        kind: Adjust::GenericReborrow(ty::Mutability::Not),
1010                        target: b,
1011                    }],
1012                    b,
1013                ),
1014                obligations: ocx.into_pending_obligations(),
1015            })
1016        } else {
1017            Err(TypeError::Mismatch)
1018        }
1019    }
1020
1021    fn coerce_from_fn_pointer(
1022        &self,
1023        a: Ty<'tcx>,
1024        a_sig: ty::PolyFnSig<'tcx>,
1025        b: Ty<'tcx>,
1026    ) -> CoerceResult<'tcx> {
1027        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1027",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1027u32),
                        ::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");
1028        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);
1029
1030        match b.kind() {
1031            ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety().is_unsafe() => {
1032                let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
1033                let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
1034                self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
1035            }
1036            _ => self.unify(a, b, ForceLeakCheck::Yes),
1037        }
1038    }
1039
1040    fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1041        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1041",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1041u32),
                        ::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);
1042        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);
1043        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);
1044
1045        match b.kind() {
1046            ty::FnPtr(_, b_hdr) => {
1047                let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety()))?;
1048
1049                let InferOk { value: a_sig, mut obligations } =
1050                    self.at(&self.cause, self.param_env).normalize(Unnormalized::new_wip(a_sig));
1051                let a = Ty::new_fn_ptr(self.tcx, a_sig);
1052
1053                let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety()));
1054                let InferOk { value, obligations: o2 } =
1055                    self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
1056
1057                obligations.extend(o2);
1058                Ok(InferOk { value, obligations })
1059            }
1060            _ => self.unify(a, b, ForceLeakCheck::No),
1061        }
1062    }
1063
1064    /// Attempts to coerce from a closure to a function pointer. Fails
1065    /// if the closure has any upvars.
1066    fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1067        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);
1068        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);
1069
1070        match b.kind() {
1071            ty::FnPtr(_, hdr) => {
1072                let safety = hdr.safety();
1073                let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
1074                let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety()), terr)?;
1075                let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
1076                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1076",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1076u32),
                        ::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);
1077
1078                let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
1079                self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
1080            }
1081            _ => self.unify(a, b, ForceLeakCheck::No),
1082        }
1083    }
1084
1085    fn coerce_to_raw_ptr(
1086        &self,
1087        a: Ty<'tcx>,
1088        b: Ty<'tcx>,
1089        mutbl_b: hir::Mutability,
1090    ) -> CoerceResult<'tcx> {
1091        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1091",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1091u32),
                        ::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);
1092        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);
1093        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);
1094
1095        let (is_ref, mt_a) = match *a.kind() {
1096            ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
1097            ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
1098            _ => return self.unify(a, b, ForceLeakCheck::No),
1099        };
1100        coerce_mutbls(mt_a.mutbl, mutbl_b)?;
1101
1102        // Check that the types which they point at are compatible.
1103        let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
1104        // Although references and raw ptrs have the same
1105        // representation, we still register an Adjust::DerefRef so that
1106        // regionck knows that the region for `a` must be valid here.
1107        if is_ref {
1108            self.unify_and(
1109                a_raw,
1110                b,
1111                [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
1112                Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1113                ForceLeakCheck::No,
1114            )
1115        } else if mt_a.mutbl != mutbl_b {
1116            self.unify_and(
1117                a_raw,
1118                b,
1119                [],
1120                Adjust::Pointer(PointerCoercion::MutToConstPointer),
1121                ForceLeakCheck::No,
1122            )
1123        } else {
1124            self.unify(a_raw, b, ForceLeakCheck::No)
1125        }
1126    }
1127}
1128
1129impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1130    /// Attempt to coerce an expression to a type, and return the
1131    /// adjusted type of the expression, if successful.
1132    /// Adjustments are only recorded if the coercion succeeded.
1133    /// The expressions *must not* have any preexisting adjustments.
1134    pub(crate) fn coerce(
1135        &self,
1136        expr: &'tcx hir::Expr<'tcx>,
1137        expr_ty: Ty<'tcx>,
1138        target: Ty<'tcx>,
1139        allow_two_phase: AllowTwoPhase,
1140        cause: Option<ObligationCause<'tcx>>,
1141    ) -> RelateResult<'tcx, Ty<'tcx>> {
1142        let source = self.deeply_resolve_ignoring_regions_with_obligations(expr_ty);
1143        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1143",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1143u32),
                        ::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);
1144
1145        let cause =
1146            cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1147        let coerce = Coerce::new(
1148            self,
1149            cause,
1150            allow_two_phase,
1151            self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
1152        );
1153        let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
1154
1155        let (adjustments, _) = self.register_infer_ok_obligations(ok);
1156        self.apply_adjustments(expr, adjustments);
1157        Ok(if let Err(guar) = expr_ty.error_reported() {
1158            Ty::new_error(self.tcx, guar)
1159        } else {
1160            target
1161        })
1162    }
1163
1164    /// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1165    /// and may return false positives if types are not yet fully constrained by inference.
1166    ///
1167    /// Returns false if the coercion is not possible, or if the coercion creates any
1168    /// sub-obligations that result in errors.
1169    ///
1170    /// This should only be used for diagnostics.
1171    pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1172        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1173        // We don't ever need two-phase here since we throw out the result of the coercion.
1174        // We also just always set `coerce_never` to true, since this is a heuristic.
1175        let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1176        self.probe(|_| {
1177            // Make sure to structurally resolve the types, since we use
1178            // the `TyKind`s heavily in coercion.
1179            let ocx = ObligationCtxt::new(self);
1180            let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1181                return false;
1182            };
1183            ocx.register_obligations(ok.obligations);
1184            ocx.try_evaluate_obligations().no_errors()
1185        })
1186    }
1187
1188    /// Like [`Self::may_coerce`], but for suggestions whose replacement must complete with a
1189    /// value of the target type. A coercion from `!` to another type does not provide such a
1190    /// value, so it should not by itself justify these suggestions.
1191    ///
1192    /// This should only be used for suggestions.
1193    pub(crate) fn may_coerce_except_never(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1194        if expr_ty.is_never() && !target_ty.is_never() {
1195            return false;
1196        }
1197        self.may_coerce(expr_ty, target_ty)
1198    }
1199
1200    /// Given a type and a target type, this function will calculate and return
1201    /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1202    /// it's not possible, return `None`.
1203    pub(crate) fn deref_steps_for_suggestion(
1204        &self,
1205        expr_ty: Ty<'tcx>,
1206        target: Ty<'tcx>,
1207    ) -> Option<usize> {
1208        let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1209        // We don't ever need two-phase here since we throw out the result of the coercion.
1210        let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1211        coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1212            self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1213        })
1214    }
1215
1216    /// Given a type, this function will calculate and return the type given
1217    /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1218    ///
1219    /// This function is for diagnostics only, since it does not register
1220    /// trait or region sub-obligations. (presumably we could, but it's not
1221    /// particularly important for diagnostics...)
1222    pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1223        self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1224            self.infcx
1225                .type_implements_trait(
1226                    self.tcx.lang_items().deref_mut_trait()?,
1227                    [expr_ty],
1228                    self.param_env,
1229                )
1230                .may_apply()
1231                .then_some(deref_ty)
1232        })
1233    }
1234
1235    {}
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("sig_for_coerce_lub",
                                "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                ::tracing_core::__macro_support::Option::Some(1235u32),
                                ::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("ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("ty");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("closure_upvars_terr")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("closure_upvars_terr");
                                                    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(&ty)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_upvars_terr)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        match ty.kind() {
                            ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
                            ty::Closure(..) =>
                                self.sig_for_closure_coercion(ty, None,
                                    closure_upvars_terr),
                            _ => {
                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                        format_args!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {0:?}",
                                            ty)));
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1235",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1235u32),
                        ::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("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            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(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1236    fn sig_for_coerce_lub(
1237        &self,
1238        ty: Ty<'tcx>,
1239        closure_upvars_terr: TypeError<'tcx>,
1240    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1241        match ty.kind() {
1242            ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1243            ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1244            _ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1245        }
1246    }
1247
1248    fn sig_for_fn_def_coercion(
1249        &self,
1250        fndef: Ty<'tcx>,
1251        expected_safety: Option<hir::Safety>,
1252    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1253        let tcx = self.tcx;
1254
1255        let &ty::FnDef(def_id, _) = fndef.kind() else {
1256            {
    ::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);
1257        };
1258
1259        // Intrinsics are not coercible to function pointers
1260        if tcx.intrinsic(def_id).is_some() {
1261            return Err(TypeError::IntrinsicCast);
1262        }
1263
1264        let fn_attrs = tcx.codegen_fn_attrs(def_id);
1265        if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
    InlineAttr::Force { .. } => true,
    _ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1266            return Err(TypeError::ForceInlineCast);
1267        }
1268
1269        let sig = fndef.fn_sig(tcx);
1270        let sig = if fn_attrs.safe_target_features {
1271            // Allow the coercion if the current function has all the features that would be
1272            // needed to call the coercee safely.
1273            match tcx.adjust_target_feature_sig(def_id, sig, self.body_def_id.into()) {
1274                Some(adjusted_sig) => adjusted_sig,
1275                None if #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
    Some(hir::Safety::Safe) => true,
    _ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1276                    return Err(TypeError::TargetFeatureCast(def_id));
1277                }
1278                None => sig,
1279            }
1280        } else {
1281            sig
1282        };
1283
1284        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)) {
1285            Ok(tcx.safe_to_unsafe_sig(sig))
1286        } else {
1287            Ok(sig)
1288        }
1289    }
1290
1291    fn sig_for_closure_coercion(
1292        &self,
1293        closure: Ty<'tcx>,
1294        expected_safety: Option<hir::Safety>,
1295        closure_upvars_terr: TypeError<'tcx>,
1296    ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1297        let tcx = self.tcx;
1298
1299        let ty::Closure(closure_def, closure_args) = closure.kind() else {
1300            {
    ::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);
1301        };
1302
1303        // At this point we haven't done capture analysis, which means
1304        // that the ClosureArgs just contains an inference variable instead
1305        // of tuple of captured types.
1306        //
1307        // All we care here is if any variable is being captured and not the exact paths,
1308        // so we check `upvars_mentioned` for root variables being captured.
1309        if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1310            return Err(closure_upvars_terr);
1311        }
1312
1313        // We coerce the closure, which has fn type
1314        //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
1315        // to
1316        //     `fn(arg0,arg1,...) -> _`
1317        // or
1318        //     `unsafe fn(arg0,arg1,...) -> _`
1319        let closure_sig = closure_args.as_closure().sig();
1320        Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1321    }
1322
1323    /// Given some expressions, their known unified type and another expression,
1324    /// tries to unify the types, potentially inserting coercions on any of the
1325    /// provided expressions and returns their LUB (aka "common supertype").
1326    ///
1327    /// This is really an internal helper. From outside the coercion
1328    /// module, you should instantiate a `CoerceMany` instance.
1329    fn try_find_coercion_lub(
1330        &self,
1331        cause: &ObligationCause<'tcx>,
1332        exprs: &[&'tcx hir::Expr<'tcx>],
1333        prev_ty: Ty<'tcx>,
1334        new: &hir::Expr<'_>,
1335        new_ty: Ty<'tcx>,
1336    ) -> RelateResult<'tcx, Ty<'tcx>> {
1337        let prev_ty = self.deeply_resolve_ignoring_regions_with_obligations(prev_ty);
1338        let new_ty = self.deeply_resolve_ignoring_regions_with_obligations(new_ty);
1339        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1339",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1339u32),
                        ::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!(
1340            "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1341            prev_ty,
1342            new_ty,
1343            exprs.len()
1344        );
1345
1346        // Fast Path: don't go through the coercion logic if we're coercing
1347        // a type to itself. This is unfortunately quite perf relevant so
1348        // we do it even though it may mask bugs in the coercion logic.
1349        if prev_ty == new_ty {
1350            return Ok(prev_ty);
1351        }
1352
1353        let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1354        let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1355            // Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1356            // if they can just be lubbed.
1357            //
1358            // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1359            // we would erroneously coerce closures to fnptrs when attempting to
1360            // coerce a closure to itself.
1361            (ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1362                let lubbed_ty = self.commit_if_ok(|snapshot| {
1363                    let outer_universe = self.infcx.universe();
1364
1365                    // We need to eagerly handle nested obligations due to lazy norm.
1366                    let result = if self.next_trait_solver() {
1367                        let ocx = ObligationCtxt::new(self);
1368                        let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1369                        if ocx.try_evaluate_obligations().no_errors() {
1370                            Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1371                        } else {
1372                            Err(TypeError::Mismatch)
1373                        }
1374                    } else {
1375                        self.at(cause, self.param_env).lub(prev_ty, new_ty)
1376                    };
1377
1378                    self.leak_check(outer_universe, Some(snapshot))?;
1379                    result
1380                });
1381
1382                match lubbed_ty {
1383                    Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1384                    Err(_) => {
1385                        let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1386                        let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1387                        Some((a_sig, b_sig))
1388                    }
1389                }
1390            }
1391
1392            (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1393                let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1394                let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1395                Some((a_sig, b_sig))
1396            }
1397            // ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1398            // call using `lub` which is what will happen on the normal path.
1399            (ty::FnPtr(..), ty::FnPtr(..)) => None,
1400            _ => None,
1401        };
1402
1403        if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1404            // Allow coercing safe sigs to unsafe sigs
1405            if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1406                a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1407            } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1408                b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1409            };
1410
1411            // The signature must match.
1412            let (a_sig, b_sig) = self.normalize(new.span, Unnormalized::new_wip((a_sig, b_sig)));
1413            let sig = self
1414                .at(cause, self.param_env)
1415                .lub(a_sig, b_sig)
1416                .map(|ok| self.register_infer_ok_obligations(ok))?;
1417
1418            // Reify both sides and return the reified fn pointer type.
1419            let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1420            let prev_adjustment = match prev_ty.kind() {
1421                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1422                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1423                _ => bug_impl(Some(cause.span),
    format_args!("should not try to coerce a {0} to a fn pointer", prev_ty),
    Location::caller())span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1424            };
1425            let next_adjustment = match new_ty.kind() {
1426                ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1427                ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1428                _ => bug_impl(Some(new.span),
    format_args!("should not try to coerce a {0} to a fn pointer", new_ty),
    Location::caller())span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1429            };
1430            for expr in exprs.iter() {
1431                self.apply_adjustments(
1432                    expr,
1433                    ::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 }],
1434                );
1435            }
1436            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 }]);
1437            return Ok(fn_ptr);
1438        }
1439
1440        // Configure a Coerce instance to compute the LUB.
1441        // We don't allow two-phase borrows on any autorefs this creates since we
1442        // probably aren't processing function arguments here and even if we were,
1443        // they're going to get autorefed again anyway and we can apply 2-phase borrows
1444        // at that time.
1445        //
1446        // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1447        // operate on values and not places, so a never coercion is valid.
1448        let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1449        coerce.use_lub = true;
1450
1451        // First try to coerce the new expression to the type of the previous ones,
1452        // but only if the new expression has no coercion already applied to it.
1453        let mut first_error = None;
1454        if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1455            let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1456            match result {
1457                Ok(ok) => {
1458                    let (adjustments, target) = self.register_infer_ok_obligations(ok);
1459                    self.apply_adjustments(new, adjustments);
1460                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1460",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1460u32),
                        ::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!(
1461                        "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1462                        new_ty, prev_ty, target
1463                    );
1464                    return Ok(target);
1465                }
1466                Err(e) => first_error = Some(e),
1467            }
1468        }
1469
1470        let ok = self
1471            .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1472            // Avoid giving strange errors on failed attempts.
1473            .map_err(|e| first_error.unwrap_or(e))?;
1474
1475        let (adjustments, target) = self.register_infer_ok_obligations(ok);
1476        for expr in exprs {
1477            self.apply_adjustments(expr, adjustments.clone());
1478        }
1479        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1479",
                        "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                        ::tracing_core::__macro_support::Option::Some(1479u32),
                        ::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!(
1480            "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1481            prev_ty, new_ty, target
1482        );
1483        Ok(target)
1484    }
1485}
1486
1487/// Check whether `ty` can be coerced to `output_ty`.
1488/// Used from clippy.
1489pub fn can_coerce<'tcx>(
1490    tcx: TyCtxt<'tcx>,
1491    param_env: ty::ParamEnv<'tcx>,
1492    body_def_id: LocalDefId,
1493    ty: Ty<'tcx>,
1494    output_ty: Ty<'tcx>,
1495) -> bool {
1496    let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_def_id);
1497    let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_def_id);
1498    fn_ctxt.may_coerce(ty, output_ty)
1499}
1500
1501/// CoerceMany encapsulates the pattern you should use when you have
1502/// many expressions that are all getting coerced to a common
1503/// type. This arises, for example, when you have a match (the result
1504/// of each arm is coerced to a common type). It also arises in less
1505/// obvious places, such as when you have many `break foo` expressions
1506/// that target the same loop, or the various `return` expressions in
1507/// a function.
1508///
1509/// The basic protocol is as follows:
1510///
1511/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1512///   This will also serve as the "starting LUB". The expectation is
1513///   that this type is something which all of the expressions *must*
1514///   be coercible to. Use a fresh type variable if needed.
1515/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1516///   - In some cases we wish to coerce "non-expressions" whose types are implicitly
1517///     unit. This happens for example if you have a `break` with no expression,
1518///     or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1519///   - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1520///     from you so that you don't have to worry your pretty head about it.
1521///     But if an error is reported, the final type will be `err`.
1522///   - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1523///     previously coerced expressions.
1524/// - When all done, invoke `complete()`. This will return the LUB of
1525///   all your expressions.
1526///   - WARNING: I don't believe this final type is guaranteed to be
1527///     related to your initial `expected_ty` in any particular way,
1528///     although it will typically be a subtype, so you should check it.
1529///     Check the note below for more details.
1530///   - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1531///     previously coerced expressions.
1532///
1533/// Example:
1534///
1535/// ```ignore (illustrative)
1536/// let mut coerce = CoerceMany::new(expected_ty);
1537/// for expr in exprs {
1538///     let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1539///     coerce.coerce(fcx, &cause, expr, expr_ty);
1540/// }
1541/// let final_ty = coerce.complete(fcx);
1542/// ```
1543///
1544/// NOTE: Why does the `expected_ty` participate in the LUB?
1545/// When coercing, each branch should use the following expectations for type inference:
1546/// - The branch can be coerced to the expected type of the match/if/whatever.
1547/// - The branch can be coercion lub'd with the types of the previous branches.
1548/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1549/// but adding and using this feels very challenging.
1550/// What we instead do is to use the expected type of the match/if/whatever as
1551/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1552/// "types from previous branches" as the coercion target, which can contains both expectations.
1553///
1554/// Two concerns with this approach:
1555/// - We may have incompatible `final_ty` if that lub is different from the expected
1556///   type of the match. However, in this case coercing the final type of the
1557///   `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1558/// - We may constrain the `expected_ty` too early. For some branches with
1559///   type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1560///   `(a lub b) lub expected_ty`. They should be the same type. However,
1561///   `a lub expected_ty` may constrain inference variables in `expected_ty`.
1562///   In this case the difference does matter and we get actually incorrect results.
1563/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1564/// the expected type of the match when computing the types of its branches.
1565pub(crate) struct CoerceMany<'tcx> {
1566    expected_ty: Ty<'tcx>,
1567    final_ty: Option<Ty<'tcx>>,
1568    expressions: Vec<&'tcx hir::Expr<'tcx>>,
1569}
1570
1571impl<'tcx> CoerceMany<'tcx> {
1572    /// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1573    /// coercion sites is known before hand, consider `with_capacity()` instead
1574    /// to avoid allocation.
1575    pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1576        Self::with_capacity(expected_ty, 1)
1577    }
1578
1579    /// Creates a `CoerceMany` with a given capacity.
1580    pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1581        CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1582    }
1583
1584    /// Returns the "expected type" with which this coercion was
1585    /// constructed. This represents the "downward propagated" type
1586    /// that was given to us at the start of typing whatever construct
1587    /// we are typing (e.g., the match expression).
1588    ///
1589    /// Typically, this is used as the expected type when
1590    /// type-checking each of the alternative expressions whose types
1591    /// we are trying to merge.
1592    pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1593        self.expected_ty
1594    }
1595
1596    /// Returns the current "merged type", representing our best-guess
1597    /// at the LUB of the expressions we've seen so far (if any). This
1598    /// isn't *final* until you call `self.complete()`, which will return
1599    /// the merged type.
1600    pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1601        self.final_ty.unwrap_or(self.expected_ty)
1602    }
1603
1604    /// Indicates that the value generated by `expression`, which is
1605    /// of type `expression_ty`, is one of the possibilities that we
1606    /// could coerce from. This will record `expression`, and later
1607    /// calls to `coerce` may come back and add adjustments and things
1608    /// if necessary.
1609    pub(crate) fn coerce<'a>(
1610        &mut self,
1611        fcx: &FnCtxt<'a, 'tcx>,
1612        cause: &ObligationCause<'tcx>,
1613        expression: &'tcx hir::Expr<'tcx>,
1614        expression_ty: Ty<'tcx>,
1615    ) {
1616        self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1617    }
1618
1619    /// Indicates that one of the inputs is a "forced unit". This
1620    /// occurs in a case like `if foo { ... };`, where the missing else
1621    /// generates a "forced unit". Another example is a `loop { break;
1622    /// }`, where the `break` has no argument expression. We treat
1623    /// these cases slightly differently for error-reporting
1624    /// purposes. Note that these tend to correspond to cases where
1625    /// the `()` expression is implicit in the source, and hence we do
1626    /// not take an expression argument.
1627    ///
1628    /// The `augment_error` gives you a chance to extend the error
1629    /// message, in case any results (e.g., we use this to suggest
1630    /// removing a `;`).
1631    pub(crate) fn coerce_forced_unit<'a>(
1632        &mut self,
1633        fcx: &FnCtxt<'a, 'tcx>,
1634        cause: &ObligationCause<'tcx>,
1635        augment_error: impl FnOnce(&mut Diag<'_>),
1636        label_unit_as_expected: bool,
1637    ) {
1638        self.coerce_inner(
1639            fcx,
1640            cause,
1641            None,
1642            fcx.tcx.types.unit,
1643            augment_error,
1644            label_unit_as_expected,
1645        )
1646    }
1647
1648    /// The inner coercion "engine". If `expression` is `None`, this
1649    /// is a forced-unit case, and hence `expression_ty` must be
1650    /// `Nil`.
1651    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1651u32),
                                    ::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs:1742",
                                    "rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_typeck/src/coercion.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1742u32),
                                    ::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.deeply_resolve_ignoring_regions((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")]
1652    pub(crate) fn coerce_inner<'a>(
1653        &mut self,
1654        fcx: &FnCtxt<'a, 'tcx>,
1655        cause: &ObligationCause<'tcx>,
1656        expression: Option<&'tcx hir::Expr<'tcx>>,
1657        mut expression_ty: Ty<'tcx>,
1658        augment_error: impl FnOnce(&mut Diag<'_>),
1659        label_expression_as_expected: bool,
1660    ) {
1661        // Incorporate whatever type inference information we have
1662        // until now; in principle we might also want to process
1663        // pending obligations, but doing so should only improve
1664        // compatibility (hopefully that is true) by helping us
1665        // uncover never types better.
1666        if expression_ty.is_ty_var() {
1667            expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1668        }
1669
1670        // If we see any error types, just propagate that error
1671        // upwards.
1672        if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1673            self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1674            return;
1675        }
1676
1677        let (expected, found) = if label_expression_as_expected {
1678            // In the case where this is a "forced unit", like
1679            // `break`, we want to call the `()` "expected"
1680            // since it is implied by the syntax.
1681            // (Note: not all force-units work this way.)"
1682            (expression_ty, self.merged_ty())
1683        } else {
1684            // Otherwise, the "expected" type for error
1685            // reporting is the current unification type,
1686            // which is basically the LUB of the expressions
1687            // we've seen so far (combined with the expected
1688            // type)
1689            (self.merged_ty(), expression_ty)
1690        };
1691
1692        // Handle the actual type unification etc.
1693        let result = if let Some(expression) = expression {
1694            if self.expressions.is_empty() {
1695                // Special-case the first expression we are coercing.
1696                // To be honest, I'm not entirely sure why we do this.
1697                // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1698                fcx.coerce(
1699                    expression,
1700                    expression_ty,
1701                    self.expected_ty,
1702                    AllowTwoPhase::No,
1703                    Some(cause.clone()),
1704                )
1705            } else {
1706                fcx.try_find_coercion_lub(
1707                    cause,
1708                    &self.expressions,
1709                    self.merged_ty(),
1710                    expression,
1711                    expression_ty,
1712                )
1713            }
1714        } else {
1715            // this is a hack for cases where we default to `()` because
1716            // the expression etc has been omitted from the source. An
1717            // example is an `if let` without an else:
1718            //
1719            //     if let Some(x) = ... { }
1720            //
1721            // we wind up with a second match arm that is like `_ =>
1722            // ()`. That is the case we are considering here. We take
1723            // a different path to get the right "expected, found"
1724            // message and so forth (and because we know that
1725            // `expression_ty` will be unit).
1726            //
1727            // Another example is `break` with no argument expression.
1728            assert!(expression_ty.is_unit(), "if let hack without unit type");
1729            fcx.at(cause, fcx.param_env)
1730                .eq(
1731                    // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1732                    DefineOpaqueTypes::Yes,
1733                    expected,
1734                    found,
1735                )
1736                .map(|infer_ok| {
1737                    fcx.register_infer_ok_obligations(infer_ok);
1738                    expression_ty
1739                })
1740        };
1741
1742        debug!(?result);
1743        match result {
1744            Ok(v) => {
1745                self.final_ty = Some(v);
1746                if let Some(e) = expression {
1747                    self.expressions.push(e);
1748                }
1749            }
1750            Err(coercion_error) => {
1751                // Mark that we've failed to coerce the types here to suppress
1752                // any superfluous errors we might encounter while trying to
1753                // emit or provide suggestions on how to fix the initial error.
1754                fcx.set_tainted_by_errors(
1755                    fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1756                );
1757                let (expected, found) = fcx.deeply_resolve_ignoring_regions((expected, found));
1758
1759                let mut err;
1760                let mut unsized_return = false;
1761                match *cause.code() {
1762                    ObligationCauseCode::ReturnNoExpression => {
1763                        err = struct_span_code_err!(
1764                            fcx.dcx(),
1765                            cause.span,
1766                            E0069,
1767                            "`return;` in a function whose return type is not `()`"
1768                        );
1769                        if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1770                        {
1771                            err.span_suggestion_verbose(
1772                                cause.span.shrink_to_hi(),
1773                                "give the `return` a value of the expected type",
1774                                format!(" {value}"),
1775                                Applicability::HasPlaceholders,
1776                            );
1777                        }
1778                        err.span_label(cause.span, "return type is not `()`");
1779                    }
1780                    ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1781                        err = self.report_return_mismatched_types(
1782                            cause,
1783                            expected,
1784                            found,
1785                            coercion_error,
1786                            fcx,
1787                            blk_id,
1788                            expression,
1789                        );
1790                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1791                    }
1792                    ObligationCauseCode::ReturnValue(return_expr_id) => {
1793                        err = self.report_return_mismatched_types(
1794                            cause,
1795                            expected,
1796                            found,
1797                            coercion_error,
1798                            fcx,
1799                            return_expr_id,
1800                            expression,
1801                        );
1802                        unsized_return = self.is_return_ty_definitely_unsized(fcx);
1803                    }
1804                    ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
1805                        arm_span,
1806                        arm_ty,
1807                        prior_arm_ty,
1808                        ref prior_non_diverging_arms,
1809                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1810                        ..
1811                    }) => {
1812                        err = fcx.err_ctxt().report_mismatched_types(
1813                            cause,
1814                            fcx.param_env,
1815                            expected,
1816                            found,
1817                            coercion_error,
1818                        );
1819                        // Check that we're actually in the second or later arm
1820                        if prior_non_diverging_arms.len() > 0 {
1821                            self.suggest_boxing_tail_for_return_position_impl_trait(
1822                                fcx,
1823                                &mut err,
1824                                rpit_def_id,
1825                                arm_ty,
1826                                prior_arm_ty,
1827                                prior_non_diverging_arms
1828                                    .iter()
1829                                    .chain(std::iter::once(&arm_span))
1830                                    .copied(),
1831                            );
1832                        }
1833                    }
1834                    ObligationCauseCode::IfExpression {
1835                        expr_id,
1836                        tail_defines_return_position_impl_trait: Some(rpit_def_id),
1837                    } => {
1838                        let hir::Node::Expr(hir::Expr {
1839                            kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1840                            ..
1841                        }) = fcx.tcx.hir_node(expr_id)
1842                        else {
1843                            unreachable!();
1844                        };
1845                        err = fcx.err_ctxt().report_mismatched_types(
1846                            cause,
1847                            fcx.param_env,
1848                            expected,
1849                            found,
1850                            coercion_error,
1851                        );
1852                        let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1853                        let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1854                        // Don't suggest wrapping whole block in `Box::new`.
1855                        if then_span != then_expr.span && else_span != else_expr.span {
1856                            let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1857                            let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1858                            self.suggest_boxing_tail_for_return_position_impl_trait(
1859                                fcx,
1860                                &mut err,
1861                                rpit_def_id,
1862                                then_ty,
1863                                else_ty,
1864                                [then_span, else_span].into_iter(),
1865                            );
1866                        }
1867                    }
1868                    _ => {
1869                        err = fcx.err_ctxt().report_mismatched_types(
1870                            cause,
1871                            fcx.param_env,
1872                            expected,
1873                            found,
1874                            coercion_error,
1875                        );
1876                    }
1877                }
1878
1879                augment_error(&mut err);
1880
1881                if let Some(expr) = expression {
1882                    if let hir::ExprKind::Loop(
1883                        block,
1884                        _,
1885                        loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1886                        _,
1887                    ) = expr.kind
1888                    {
1889                        let loop_type = if loop_src == hir::LoopSource::While {
1890                            "`while` loops"
1891                        } else {
1892                            "`for` loops"
1893                        };
1894
1895                        err.note(format!("{loop_type} evaluate to unit type `()`"));
1896                        if loop_src == hir::LoopSource::While
1897                            && let Some(pat) = irrefutable_if_let_expr(block)
1898                        {
1899                            err.span_label(
1900                                pat.span,
1901                                "this pattern always matches, consider using `loop` instead",
1902                            );
1903                        }
1904                    }
1905
1906                    fcx.emit_coerce_suggestions(
1907                        &mut err,
1908                        expr,
1909                        found,
1910                        expected,
1911                        None,
1912                        Some(coercion_error),
1913                    );
1914                }
1915
1916                let reported = err.emit_unless_delay(unsized_return);
1917
1918                self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1919            }
1920        }
1921    }
1922
1923    fn suggest_boxing_tail_for_return_position_impl_trait(
1924        &self,
1925        fcx: &FnCtxt<'_, 'tcx>,
1926        err: &mut Diag<'_>,
1927        rpit_def_id: LocalDefId,
1928        a_ty: Ty<'tcx>,
1929        b_ty: Ty<'tcx>,
1930        arm_spans: impl Iterator<Item = Span>,
1931    ) {
1932        let compatible = |ty: Ty<'tcx>| {
1933            fcx.probe(|_| {
1934                let ocx = ObligationCtxt::new(fcx);
1935                ocx.register_obligations(
1936                    fcx.tcx
1937                        .item_self_bounds(rpit_def_id)
1938                        .iter_identity()
1939                        .map(Unnormalized::skip_norm_wip)
1940                        .filter_map(|clause| {
1941                            let predicate = clause
1942                                .kind()
1943                                .map_bound(|clause| match clause {
1944                                    ty::ClauseKind::Trait(trait_pred) => {
1945                                        Some(ty::ClauseKind::Trait(
1946                                            trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1947                                        ))
1948                                    }
1949                                    ty::ClauseKind::Projection(proj_pred) => {
1950                                        Some(ty::ClauseKind::Projection(
1951                                            proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1952                                        ))
1953                                    }
1954                                    _ => None,
1955                                })
1956                                .transpose()?;
1957                            Some(Obligation::new(
1958                                fcx.tcx,
1959                                ObligationCause::dummy(),
1960                                fcx.param_env,
1961                                predicate,
1962                            ))
1963                        }),
1964                );
1965                ocx.try_evaluate_obligations().no_errors()
1966            })
1967        };
1968
1969        if !compatible(a_ty) || !compatible(b_ty) {
1970            return;
1971        }
1972
1973        let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1974        err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1975            start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1976            end_sp: rpid_def_span.shrink_to_hi(),
1977        });
1978
1979        let (starts, ends) =
1980            arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1981        err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1982    }
1983
1984    fn report_return_mismatched_types<'infcx>(
1985        &self,
1986        cause: &ObligationCause<'tcx>,
1987        expected: Ty<'tcx>,
1988        found: Ty<'tcx>,
1989        ty_err: TypeError<'tcx>,
1990        fcx: &'infcx FnCtxt<'_, 'tcx>,
1991        block_or_return_id: hir::HirId,
1992        expression: Option<&'tcx hir::Expr<'tcx>>,
1993    ) -> Diag<'infcx> {
1994        let mut err =
1995            fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
1996
1997        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(..));
1998        let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1999        if let Some(expr) = expression
2000            && let hir::Node::Expr(&hir::Expr {
2001                kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
2002                ..
2003            }) = parent
2004        {
2005            let needs_block =
2006                !#[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(..));
2007            fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
2008        }
2009        // Verify that this is a tail expression of a function, otherwise the
2010        // label pointing out the cause for the type coercion will be wrong
2011        // as prior return coercions would not be relevant (#57664).
2012        if let Some(expr) = expression
2013            && due_to_block
2014        {
2015            fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
2016            let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
2017                &mut err,
2018                expr,
2019                expected,
2020                found,
2021                block_or_return_id,
2022            );
2023            if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
2024                && expected.is_unit()
2025                && !pointing_at_return_type
2026                // If the block is from an external macro or try (`?`) desugaring, then
2027                // do not suggest adding a semicolon, because there's nowhere to put it.
2028                // See issues #81943 and #87051.
2029                // Similarly, if the block is from a loop desugaring, then also do not
2030                // suggest adding a semicolon. See issue #150850.
2031                && cond_expr.span.desugaring_kind().is_none()
2032                && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
2033                && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
    _ => false,
}matches!(
2034                    cond_expr.kind,
2035                    hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
2036                )
2037            {
2038                if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
2039                    cause.code()
2040                    && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
2041                    && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
2042                    && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
2043                    && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
2044                {
2045                    err.span_label(
2046                        cond_expr.span,
2047                        "`if` expressions without `else` arms expect their inner expression to be `()`",
2048                    );
2049                } else {
2050                    err.span_label(cond_expr.span, "expected this to be `()`");
2051                }
2052                if expr.can_have_side_effects() {
2053                    // Don't suggest semicolon after if expressions as it does not fix the issue
2054                    if !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
    hir::ExprKind::If(..) => true,
    _ => false,
}matches!(cond_expr.kind, hir::ExprKind::If(..)) {
2055                        fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
2056                    }
2057                }
2058            }
2059        }
2060
2061        // If this is due to an explicit `return`, suggest adding a return type.
2062        if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
2063            && !due_to_block
2064        {
2065            fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
2066        }
2067
2068        // If this is due to a block, then maybe we forgot a `return`/`break`.
2069        if due_to_block
2070            && let Some(expr) = expression
2071            && let Some(parent_fn_decl) =
2072                fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id))
2073        {
2074            fcx.suggest_missing_break_or_return_expr(
2075                &mut err,
2076                expr,
2077                parent_fn_decl,
2078                expected,
2079                found,
2080                block_or_return_id,
2081                fcx.body_def_id,
2082            );
2083        }
2084
2085        let is_return_position = fcx
2086            .tcx
2087            .hir_get_fn_id_for_return_block(block_or_return_id)
2088            .is_some_and(|fn_id| fn_id == fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id));
2089
2090        if is_return_position
2091            && let Some(sp) = fcx.ret_coercion_span.get()
2092            // If the closure has an explicit return type annotation, or if
2093            // the closure's return type has been inferred from outside
2094            // requirements (such as an Fn* trait bound), then a type error
2095            // may occur at the first return expression we see in the closure
2096            // (if it conflicts with the declared return type). Skip adding a
2097            // note in this case, since it would be incorrect.
2098            && let Some(fn_sig) = fcx.fn_sig()
2099            && fn_sig.output().is_ty_var()
2100        {
2101            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"));
2102        }
2103
2104        err
2105    }
2106
2107    /// Checks whether the return type is unsized via an obligation, which makes
2108    /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
2109    /// false but technically valid for typeck.
2110    fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
2111        if let Some(sig) = fcx.fn_sig() {
2112            !fcx.predicate_may_hold(&Obligation::new(
2113                fcx.tcx,
2114                ObligationCause::dummy(),
2115                fcx.param_env,
2116                ty::TraitRef::new(
2117                    fcx.tcx,
2118                    fcx.tcx.require_lang_item(LangItem::Sized, DUMMY_SP),
2119                    [sig.output()],
2120                ),
2121            ))
2122        } else {
2123            false
2124        }
2125    }
2126
2127    pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2128        if let Some(final_ty) = self.final_ty {
2129            final_ty
2130        } else {
2131            // If we only had inputs that were of type `!` (or no
2132            // inputs at all), then the final type is `!`.
2133            if !self.expressions.is_empty() {
    ::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
2134            fcx.tcx.types.never
2135        }
2136    }
2137}
2138
2139fn irrefutable_if_let_expr<'hir>(block: &hir::Block<'hir>) -> Option<&'hir hir::Pat<'hir>> {
2140    let hir::ExprKind::If(cond, _, _) = block.expr?.kind else {
2141        return None;
2142    };
2143    let hir::ExprKind::Let(let_expr) = cond.kind else {
2144        return None;
2145    };
2146    simple_irrefutable_pattern(let_expr.pat).then_some(let_expr.pat)
2147}
2148
2149fn simple_irrefutable_pattern(pat: &hir::Pat<'_>) -> bool {
2150    match pat.kind {
2151        hir::PatKind::Wild | hir::PatKind::Binding(_, _, _, None) => true,
2152        hir::PatKind::Tuple(pats, _) => pats.iter().all(simple_irrefutable_pattern),
2153        _ => false,
2154    }
2155}
2156
2157/// Recursively visit goals to decide whether an unsizing is possible.
2158/// `Break`s when it isn't, and an error should be raised.
2159/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2160struct CoerceVisitor<'a, 'tcx> {
2161    fcx: &'a FnCtxt<'a, 'tcx>,
2162    span: Span,
2163    /// Whether the coercion is impossible. If so we sometimes still try to
2164    /// coerce in these cases to emit better errors. This changes the behavior
2165    /// when hitting the recursion limit.
2166    errored: bool,
2167}
2168
2169impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2170    type Result = ControlFlow<()>;
2171
2172    fn span(&self) -> Span {
2173        self.span
2174    }
2175
2176    fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2177        let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2178            return ControlFlow::Continue(());
2179        };
2180
2181        // Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2182        // Otherwise there's nothing to do.
2183        if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2184            && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2185        {
2186            return ControlFlow::Continue(());
2187        }
2188
2189        match goal.result() {
2190            // If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2191            Ok(Certainty::Yes) => ControlFlow::Continue(()),
2192            Err(NoSolution) => {
2193                self.errored = true;
2194                // Even if we find no solution, continue recursing if we find a single candidate
2195                // for which we're shallowly certain it holds to get the right error source.
2196                if let [only_candidate] = &goal.candidates()[..]
2197                    && only_candidate.shallow_certainty() == Certainty::Yes
2198                {
2199                    only_candidate.visit_nested_no_probe(self)
2200                } else {
2201                    ControlFlow::Break(())
2202                }
2203            }
2204            Ok(Certainty::Maybe(_)) => {
2205                // FIXME: structurally normalize?
2206                if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2207                    && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2208                    && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2209                    && self.fcx.type_var_is_sized(vid)
2210                {
2211                    // We get here when trying to unsize a type variable to a `dyn Trait`,
2212                    // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2213                    // If the variable weren't sized, we may not need an unsizing coercion.
2214                    // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2215                    ControlFlow::Continue(())
2216                } else if let Some(cand) = goal.unique_applicable_candidate()
2217                    && cand.shallow_certainty() == Certainty::Yes
2218                {
2219                    cand.visit_nested_no_probe(self)
2220                } else {
2221                    ControlFlow::Break(())
2222                }
2223            }
2224        }
2225    }
2226
2227    fn on_recursion_limit(&mut self) -> Self::Result {
2228        if self.errored {
2229            // This prevents accidentally committing unfulfilled unsized coercions while trying to
2230            // find the error source for diagnostics.
2231            // See https://github.com/rust-lang/trait-system-refactor-initiative/issues/266.
2232            ControlFlow::Break(())
2233        } else {
2234            ControlFlow::Continue(())
2235        }
2236    }
2237}