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