Skip to main content

rustc_hir_typeck/fn_ctxt/
_impl.rs

1use std::collections::hash_map::Entry;
2use std::slice;
3
4use rustc_abi::FieldIdx;
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::{
7    Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan,
8};
9use rustc_hir::def::{CtorOf, DefKind, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::lang_items::LangItem;
13use rustc_hir::{self as hir, AmbigArg, ExprKind, GenericArg, HirId, Node, QPath, intravisit};
14use rustc_hir_analysis::hir_ty_lowering::errors::GenericsArgsErrExtend;
15use rustc_hir_analysis::hir_ty_lowering::generics::{
16    check_generic_arg_count_for_value_path, lower_generic_args,
17};
18use rustc_hir_analysis::hir_ty_lowering::{
19    ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgsLowerer,
20    GenericPathSegment, HirTyLowerer, IsMethodCall, RegionInferReason,
21};
22use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
23use rustc_infer::infer::{DefineOpaqueTypes, InferResult};
24use rustc_lint::builtin::SELF_CONSTRUCTOR_FROM_OUTER_ITEM;
25use rustc_middle::ty::adjustment::{
26    Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
27};
28use rustc_middle::ty::{
29    self, AdtKind, CanonicalUserType, GenericArgsRef, GenericParamDefKind, IsIdentity,
30    SizedTraitKind, SplattedDef, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt,
31    Unnormalized, UserArgs, UserSelfTy,
32};
33use rustc_middle::{bug, span_bug};
34use rustc_session::lint;
35use rustc_span::Span;
36use rustc_span::def_id::LocalDefId;
37use rustc_span::hygiene::DesugaringKind;
38use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
39use rustc_trait_selection::traits::{
40    self, NormalizeExt, ObligationCauseCode, StructurallyNormalizeExt,
41};
42use tracing::{debug, instrument};
43
44use crate::callee::{self, DeferredCallResolution};
45use crate::diagnostics::{self, CtorIsPrivate};
46use crate::method::{self, MethodCallee};
47use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy};
48
49impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
50    /// Transform generic args for inherent associated type constants (IACs).
51    ///
52    /// IACs have a different generic parameter structure than regular associated constants:
53    /// - Regular assoc const: parent (impl) generic params + own generic params
54    /// - IAC (type_const): Self type + own generic params
55    pub(crate) fn transform_args_for_inherent_type_const(
56        &self,
57        def_id: DefId,
58        args: GenericArgsRef<'tcx>,
59    ) -> GenericArgsRef<'tcx> {
60        let tcx = self.tcx;
61        if !tcx.is_type_const(def_id) {
62            return args;
63        }
64        let Some(assoc_item) = tcx.opt_associated_item(def_id) else {
65            return args;
66        };
67        if !#[allow(non_exhaustive_omitted_patterns)] match assoc_item.container {
    ty::AssocContainer::InherentImpl => true,
    _ => false,
}matches!(assoc_item.container, ty::AssocContainer::InherentImpl) {
68            return args;
69        }
70
71        let impl_def_id = assoc_item.container_id(tcx);
72        let generics = tcx.generics_of(def_id);
73        let impl_args = &args[..generics.parent_count];
74        let self_ty = tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip();
75        // Build new args: [Self, own_args...]
76        let own_args = &args[generics.parent_count..];
77        tcx.mk_args_from_iter(
78            std::iter::once(ty::GenericArg::from(self_ty)).chain(own_args.iter().copied()),
79        )
80    }
81
82    /// Produces warning on the given node, if the current point in the
83    /// function is unreachable, and there hasn't been another warning.
84    pub(crate) fn warn_if_unreachable(&self, id: HirId, span: Span, kind: &str) {
85        struct UnreachableItem<'a, 'b> {
86            kind: &'a str,
87            span: Span,
88            orig_span: Span,
89            custom_note: Option<&'b str>,
90        }
91
92        impl<'a, 'b, 'c> Diagnostic<'a, ()> for UnreachableItem<'b, 'c> {
93            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
94                let Self { kind, span, orig_span, custom_note } = self;
95                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unreachable {0}", kind))
    })format!("unreachable {kind}");
96                Diag::new(dcx, level, msg.clone()).with_span_label(span, msg).with_span_label(
97                    orig_span,
98                    custom_note.map(|c| c.to_owned()).unwrap_or_else(|| {
99                        "any code following this expression is unreachable".to_owned()
100                    }),
101                )
102            }
103        }
104
105        let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() else {
106            return;
107        };
108
109        match span.desugaring_kind() {
110            // Don't lint if the result of an async block or async function is `!`.
111            // This does not affect the unreachable lints *within* the body.
112            Some(DesugaringKind::Async) => return,
113
114            // Don't lint *within* the `.await` operator, since that's all just desugaring
115            // junk. We only want to lint if there is a subsequent expression after the
116            // `.await` operator.
117            Some(DesugaringKind::Await) => return,
118
119            _ => {}
120        }
121
122        // Don't emit the lint if we are in an impl marked as `#[automatically_derive]`.
123        // This is relevant for deriving `Clone` and `PartialEq` on types containing `!`.
124        if self.tcx.is_automatically_derived(self.tcx.parent(id.owner.def_id.into())) {
125            return;
126        }
127
128        // Don't warn twice.
129        self.diverges.set(Diverges::WarnedAlways);
130
131        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:131",
                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                        ::tracing_core::__macro_support::Option::Some(131u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                        ::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!("warn_if_unreachable: id={0:?} span={1:?} kind={2}",
                                                    id, span, kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
132
133        self.tcx().emit_node_span_lint(
134            lint::builtin::UNREACHABLE_CODE,
135            id,
136            span,
137            UnreachableItem { kind, span, orig_span, custom_note },
138        );
139    }
140
141    /// Resolves type and const variables in `t` if possible. Unlike the infcx
142    /// version (resolve_vars_if_possible), this version will
143    /// also select obligations if it seems useful, in an effort
144    /// to get more type information.
145    // FIXME(-Znext-solver): A lot of the calls to this method should
146    // probably be `resolve_vars_with_obligations` or `structurally_resolve_type` instead.
147    x;#[instrument(skip(self), level = "debug", ret)]
148    pub(crate) fn resolve_vars_with_obligations<T: TypeFoldable<TyCtxt<'tcx>>>(
149        &self,
150        mut t: T,
151    ) -> T {
152        // No Infer()? Nothing needs doing.
153        if !t.has_non_region_infer() {
154            debug!("no inference var, nothing needs doing");
155            return t;
156        }
157
158        // If `t` is a type variable, see whether we already know what it is.
159        t = self.resolve_vars_if_possible(t);
160        if !t.has_non_region_infer() {
161            debug!(?t);
162            return t;
163        }
164
165        // If not, try resolving pending obligations as much as
166        // possible. This can help substantially when there are
167        // indirect dependencies that don't seem worth tracking
168        // precisely.
169        self.select_obligations_where_possible(|_| {});
170        self.resolve_vars_if_possible(t)
171    }
172
173    pub(crate) fn record_deferred_call_resolution(
174        &self,
175        closure_def_id: LocalDefId,
176        r: DeferredCallResolution<'tcx>,
177    ) {
178        let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
179        deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
180    }
181
182    pub(crate) fn remove_deferred_call_resolutions(
183        &self,
184        closure_def_id: LocalDefId,
185    ) -> Vec<DeferredCallResolution<'tcx>> {
186        let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
187        deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
188    }
189
190    fn tag(&self) -> String {
191        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:p}", self))
    })format!("{self:p}")
192    }
193
194    pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> {
195        self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
196            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("no type for local variable {0}",
        self.tcx.hir_id_to_string(nid)))span_bug!(span, "no type for local variable {}", self.tcx.hir_id_to_string(nid))
197        })
198    }
199
200    #[inline]
201    pub(crate) fn write_ty(&self, id: HirId, ty: Ty<'tcx>) {
202        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:202",
                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                        ::tracing_core::__macro_support::Option::Some(202u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                        ::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!("write_ty({0:?}, {1:?}) in fcx {2}",
                                                    id, self.resolve_vars_if_possible(ty), self.tag()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
203        let mut typeck = self.typeck_results.borrow_mut();
204        let mut node_ty = typeck.node_types_mut();
205
206        if let Some(prev) = node_ty.insert(id, ty) {
207            if prev.references_error() {
208                node_ty.insert(id, prev);
209            } else if !ty.references_error() {
210                // Could change this to a bug, but there's lots of diagnostic code re-lowering
211                // or re-typechecking nodes that were already typecked.
212                // Lots of that diagnostics code relies on subtle effects of re-lowering, so we'll
213                // let it keep doing that and just ensure that compilation won't succeed.
214                self.dcx().span_delayed_bug(
215                    self.tcx.hir_span(id),
216                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}` overridden by `{2}` for {3:?} in {0:?}",
                self.body_def_id, prev, ty, id))
    })format!("`{prev}` overridden by `{ty}` for {id:?} in {:?}", self.body_def_id),
217                );
218            }
219        }
220
221        if let Err(e) = ty.error_reported() {
222            self.set_tainted_by_errors(e);
223        }
224    }
225
226    pub(crate) fn write_field_index(&self, hir_id: HirId, index: FieldIdx) {
227        self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
228    }
229
230    #[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("write_resolution",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(230u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("r")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("r");
                                                        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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
                                                            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;
        }
        {
            self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id,
                r);
        }
    }
}#[instrument(level = "debug", skip(self))]
231    pub(crate) fn write_resolution(
232        &self,
233        hir_id: HirId,
234        r: Result<(DefKind, DefId), ErrorGuaranteed>,
235    ) {
236        self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
237    }
238
239    #[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("write_splatted_resolution",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(239u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("r")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("r");
                                                        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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
                                                            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;
        }
        {
            self.typeck_results.borrow_mut().splatted_defs_mut().insert(hir_id,
                r);
        }
    }
}#[instrument(level = "debug", skip(self))]
240    pub(crate) fn write_splatted_resolution(
241        &self,
242        hir_id: HirId,
243        r: Result<SplattedDef, ErrorGuaranteed>,
244    ) {
245        self.typeck_results.borrow_mut().splatted_defs_mut().insert(hir_id, r);
246    }
247
248    #[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("write_method_call_and_enforce_effects",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(248u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("method")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("method");
                                                        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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
                                                            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;
        }
        {
            self.enforce_context_effects(Some(hir_id), span, method.def_id,
                method.args);
            self.write_resolution(hir_id,
                Ok((DefKind::AssocFn, method.def_id)));
            self.write_args(hir_id, method.args);
        }
    }
}#[instrument(level = "debug", skip(self))]
249    pub(crate) fn write_method_call_and_enforce_effects(
250        &self,
251        hir_id: HirId,
252        span: Span,
253        method: MethodCallee<'tcx>,
254    ) {
255        self.enforce_context_effects(Some(hir_id), span, method.def_id, method.args);
256        self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
257        self.write_args(hir_id, method.args);
258    }
259
260    #[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("write_splatted_call",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(260u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("callee_generic_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("callee_generic_args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("first_tupled_arg_index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("first_tupled_arg_index");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tupled_args_count")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tupled_args_count");
                                                        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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&callee_generic_args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&first_tupled_arg_index
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&tupled_args_count
                                                            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;
        }
        {
            self.write_splatted_resolution(hir_id,
                Ok(SplattedDef {
                        def_id: callee_def_id,
                        arg_index: first_tupled_arg_index,
                        arg_count: tupled_args_count,
                    }));
            if let Some(callee_generic_args) = callee_generic_args {
                self.write_args(hir_id, callee_generic_args);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
261    pub(crate) fn write_splatted_call(
262        &self,
263        hir_id: HirId,
264        span: Span,
265        callee_def_id: Option<DefId>,
266        callee_generic_args: Option<GenericArgsRef<'tcx>>,
267        first_tupled_arg_index: u16,
268        tupled_args_count: u16,
269    ) {
270        // FIXME(const_trait_impl): enforce constness using enforce_context_effects() and add
271        // _and_enforce_effects to this method's name
272
273        self.write_splatted_resolution(
274            hir_id,
275            Ok(SplattedDef {
276                def_id: callee_def_id,
277                arg_index: first_tupled_arg_index,
278                arg_count: tupled_args_count,
279            }),
280        );
281        if let Some(callee_generic_args) = callee_generic_args {
282            self.write_args(hir_id, callee_generic_args);
283        }
284    }
285
286    fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) {
287        if !args.is_empty() {
288            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:288",
                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                        ::tracing_core::__macro_support::Option::Some(288u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                        ::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!("write_args({0:?}, {1:?}) in fcx {2}",
                                                    node_id, args, self.tag()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag());
289
290            self.typeck_results.borrow_mut().node_args_mut().insert(node_id, args);
291        }
292    }
293
294    /// Given the args that we just converted from the HIR, try to
295    /// canonicalize them and store them as user-given parameters
296    /// (i.e., parameters that must be respected by the NLL check).
297    ///
298    /// This should be invoked **before any unifications have
299    /// occurred**, so that annotations like `Vec<_>` are preserved
300    /// properly.
301    #[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("write_user_type_annotation_from_args",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(301u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("user_self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("user_self_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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&user_self_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;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:309",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(309u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::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!("fcx {0}",
                                                                self.tag()) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if self.tcx.def_kind(def_id) == DefKind::ConstParam { return; }
            if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) {
                let canonicalized =
                    self.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(def_id,
                                UserArgs { args, user_self_ty })));
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:322",
                                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                        ::tracing_core::__macro_support::Option::Some(322u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("canonicalized")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("canonicalized");
                                                            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(&canonicalized)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                self.write_user_type_annotation(hir_id, canonicalized);
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
302    pub(crate) fn write_user_type_annotation_from_args(
303        &self,
304        hir_id: HirId,
305        def_id: DefId,
306        args: GenericArgsRef<'tcx>,
307        user_self_ty: Option<UserSelfTy<'tcx>>,
308    ) {
309        debug!("fcx {}", self.tag());
310
311        // Don't write user type annotations for const param types, since we give them
312        // identity args just so that we can trivially substitute their `EarlyBinder`.
313        // We enforce that they match their type in MIR later on.
314        if self.tcx.def_kind(def_id) == DefKind::ConstParam {
315            return;
316        }
317
318        if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) {
319            let canonicalized = self.canonicalize_user_type_annotation(ty::UserType::new(
320                ty::UserTypeKind::TypeOf(def_id, UserArgs { args, user_self_ty }),
321            ));
322            debug!(?canonicalized);
323            self.write_user_type_annotation(hir_id, canonicalized);
324        }
325    }
326
327    #[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("write_user_type_annotation",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(327u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("canonical_user_type_annotation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("canonical_user_type_annotation");
                                                        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(&hir_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&canonical_user_type_annotation)
                                                            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;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:333",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(333u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::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!("fcx {0}",
                                                                self.tag()) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if !canonical_user_type_annotation.is_identity() {
                self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_id,
                    canonical_user_type_annotation);
            } else {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:342",
                                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                        ::tracing_core::__macro_support::Option::Some(342u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                        ::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!("skipping identity args")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
328    pub(crate) fn write_user_type_annotation(
329        &self,
330        hir_id: HirId,
331        canonical_user_type_annotation: CanonicalUserType<'tcx>,
332    ) {
333        debug!("fcx {}", self.tag());
334
335        // FIXME: is_identity being on `UserType` and not `Canonical<UserType>` is awkward
336        if !canonical_user_type_annotation.is_identity() {
337            self.typeck_results
338                .borrow_mut()
339                .user_provided_types_mut()
340                .insert(hir_id, canonical_user_type_annotation);
341        } else {
342            debug!("skipping identity args");
343        }
344    }
345
346    #[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("apply_adjustments",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(346u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("adj")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("adj");
                                                        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(&adj)
                                                            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;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:348",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(348u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::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!("expr = {0:#?}",
                                                                expr) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if adj.is_empty() { return; }
            let mut expr_ty =
                self.typeck_results.borrow().expr_ty_adjusted(expr);
            for a in &adj {
                match a.kind {
                    Adjust::NeverToAny => {
                        if let ty::Infer(ty::TyVar(a_id)) = a.target.kind() {
                            self.diverging_type_vars.borrow_mut().push(*a_id);
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:361",
                                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(361u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                                    ::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!("apply_adjustments: adding `{0:?}` as diverging type var",
                                                                                a.target) as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                        }
                    }
                    Adjust::Deref(DerefAdjustKind::Overloaded(overloaded_deref))
                        => {
                        self.enforce_context_effects(None, expr.span,
                            overloaded_deref.method_call(self.tcx),
                            self.tcx.mk_args(&[expr_ty.into()]));
                    }
                    Adjust::Deref(DerefAdjustKind::Builtin) => {}
                    Adjust::Deref(DerefAdjustKind::Pin) => {}
                    Adjust::Pointer(_pointer_coercion) => {}
                    Adjust::GenericReborrow(_) => {}
                    Adjust::Borrow(_) => {}
                }
                expr_ty = a.target;
            }
            let autoborrow_mut =
                adj.iter().any(|adj|
                        {

                            #[allow(non_exhaustive_omitted_patterns)]
                            match adj {
                                &Adjustment {
                                    kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut {
                                        .. })), .. } => true,
                                _ => false,
                            }
                        });
            match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id)
                {
                Entry::Vacant(entry) => { entry.insert(adj); }
                Entry::Occupied(mut entry) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:407",
                                            "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                            ::tracing_core::__macro_support::Option::Some(407u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                            ::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!(" - composing on top of {0:?}",
                                                                        entry.get()) as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    match (&mut entry.get_mut()[..], &adj[..]) {
                        ([Adjustment { kind: Adjust::NeverToAny, target }],
                            &[.., Adjustment { target: new_target, .. }]) => {
                            *target = new_target;
                        }
                        (&mut [Adjustment { kind: Adjust::Deref(_), .. },
                            Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), ..
                            }], &[Adjustment { kind: Adjust::Deref(_), .. }, ..]) => {
                            *entry.get_mut() = adj;
                        }
                        _ => {
                            self.dcx().span_delayed_bug(expr.span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("while adjusting {0:?}, can\'t compose {1:?} and {2:?}",
                                                expr, entry.get(), adj))
                                    }));
                            *entry.get_mut() = adj;
                        }
                    }
                }
            }
            if autoborrow_mut { self.convert_place_derefs_to_mutable(expr); }
        }
    }
}#[instrument(skip(self, expr), level = "debug")]
347    pub(crate) fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
348        debug!("expr = {:#?}", expr);
349
350        if adj.is_empty() {
351            return;
352        }
353
354        let mut expr_ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
355
356        for a in &adj {
357            match a.kind {
358                Adjust::NeverToAny => {
359                    if let ty::Infer(ty::TyVar(a_id)) = a.target.kind() {
360                        self.diverging_type_vars.borrow_mut().push(*a_id);
361                        debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
362                    }
363                }
364                Adjust::Deref(DerefAdjustKind::Overloaded(overloaded_deref)) => {
365                    self.enforce_context_effects(
366                        None,
367                        expr.span,
368                        overloaded_deref.method_call(self.tcx),
369                        self.tcx.mk_args(&[expr_ty.into()]),
370                    );
371                }
372                Adjust::Deref(DerefAdjustKind::Builtin) => {
373                    // FIXME(const_trait_impl): We *could* enforce `&T: [const] Deref` here.
374                }
375                Adjust::Deref(DerefAdjustKind::Pin) => {
376                    // FIXME(const_trait_impl): We *could* enforce `Pin<&T>: [const] Deref` here.
377                }
378                Adjust::Pointer(_pointer_coercion) => {
379                    // FIXME(const_trait_impl): We should probably enforce these.
380                }
381                Adjust::GenericReborrow(_) => {
382                    // FIXME(reborrow): figure out if we have effects to enforce here.
383                }
384                Adjust::Borrow(_) => {
385                    // No effects to enforce here.
386                }
387            }
388
389            expr_ty = a.target;
390        }
391
392        let autoborrow_mut = adj.iter().any(|adj| {
393            matches!(
394                adj,
395                &Adjustment {
396                    kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut { .. })),
397                    ..
398                }
399            )
400        });
401
402        match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
403            Entry::Vacant(entry) => {
404                entry.insert(adj);
405            }
406            Entry::Occupied(mut entry) => {
407                debug!(" - composing on top of {:?}", entry.get());
408                match (&mut entry.get_mut()[..], &adj[..]) {
409                    (
410                        [Adjustment { kind: Adjust::NeverToAny, target }],
411                        &[.., Adjustment { target: new_target, .. }],
412                    ) => {
413                        // NeverToAny coercion can target any type, so instead of adding a new
414                        // adjustment on top we can change the target.
415                        //
416                        // This is required for things like `a == a` (where `a: !`) to produce
417                        // valid MIR -- we need borrow adjustment from things like `==` to change
418                        // the type to `&!` (or `&()` depending on the fallback). This might be
419                        // relevant even in unreachable code.
420                        *target = new_target;
421                    }
422
423                    (
424                        &mut [
425                            Adjustment { kind: Adjust::Deref(_), .. },
426                            Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
427                        ],
428                        &[
429                            Adjustment { kind: Adjust::Deref(_), .. },
430                            .., // Any following adjustments are allowed.
431                        ],
432                    ) => {
433                        // A reborrow has no effect before a dereference, so we can safely replace adjustments.
434                        *entry.get_mut() = adj;
435                    }
436
437                    _ => {
438                        // FIXME: currently we never try to compose autoderefs
439                        // and ReifyFnPointer/UnsafeFnPointer, but we could.
440                        self.dcx().span_delayed_bug(
441                            expr.span,
442                            format!(
443                                "while adjusting {:?}, can't compose {:?} and {:?}",
444                                expr,
445                                entry.get(),
446                                adj
447                            ),
448                        );
449
450                        *entry.get_mut() = adj;
451                    }
452                }
453            }
454        }
455
456        // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
457        // In this case implicit use of `Deref` and `Index` within `<expr>` should
458        // instead be `DerefMut` and `IndexMut`, so fix those up.
459        if autoborrow_mut {
460            self.convert_place_derefs_to_mutable(expr);
461        }
462    }
463
464    pub(crate) fn normalize<T>(&self, span: Span, value: Unnormalized<'tcx, T>) -> T
465    where
466        T: TypeFoldable<TyCtxt<'tcx>>,
467    {
468        self.register_infer_ok_obligations(
469            self.at(&self.misc(span), self.param_env).normalize(value),
470        )
471    }
472
473    pub(crate) fn require_type_meets(
474        &self,
475        ty: Ty<'tcx>,
476        span: Span,
477        code: traits::ObligationCauseCode<'tcx>,
478        def_id: DefId,
479    ) {
480        self.register_bound(ty, def_id, self.cause(span, code));
481    }
482
483    pub(crate) fn require_type_is_sized(
484        &self,
485        ty: Ty<'tcx>,
486        span: Span,
487        code: traits::ObligationCauseCode<'tcx>,
488    ) {
489        if !ty.references_error() {
490            let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
491            self.require_type_meets(ty, span, code, lang_item);
492        }
493    }
494
495    pub(crate) fn require_type_is_sized_deferred(
496        &self,
497        ty: Ty<'tcx>,
498        span: Span,
499        code: traits::ObligationCauseCode<'tcx>,
500    ) {
501        if !ty.references_error() {
502            self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
503        }
504    }
505
506    pub(crate) fn require_type_has_static_alignment(&self, ty: Ty<'tcx>, span: Span) {
507        if !ty.references_error() {
508            let tail = self.tcx.struct_tail_raw(
509                ty,
510                &self.misc(span),
511                |ty| self.normalize(span, ty),
512                || {},
513            );
514            // Sized types have static alignment, and so do slices.
515            if tail.has_trivial_sizedness(self.tcx, SizedTraitKind::Sized)
516                || #[allow(non_exhaustive_omitted_patterns)] match tail.kind() {
    ty::Slice(..) => true,
    _ => false,
}matches!(tail.kind(), ty::Slice(..))
517            {
518                // Nothing else is required here.
519            } else {
520                // We can't be sure, let's required full `Sized`.
521                let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
522                self.require_type_meets(ty, span, ObligationCauseCode::Misc, lang_item);
523            }
524        }
525    }
526
527    pub(crate) fn register_bound(
528        &self,
529        ty: Ty<'tcx>,
530        def_id: DefId,
531        cause: traits::ObligationCause<'tcx>,
532    ) {
533        if !ty.references_error() {
534            self.fulfillment_cx.borrow_mut().register_bound(
535                self,
536                self.param_env,
537                ty,
538                def_id,
539                cause,
540            );
541        }
542    }
543
544    pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
545        let ty = self.lowerer().lower_ty(hir_ty);
546        self.register_wf_obligation(ty.into(), hir_ty.span, ObligationCauseCode::WellFormed(None));
547        LoweredTy::from_raw(self, hir_ty.span, ty)
548    }
549
550    /// Walk a `hir_ty` and collect any clauses that may have come from a type
551    /// within the `hir_ty`. These clauses will be canonicalized with a user type
552    /// annotation so that we can enforce these bounds in borrowck, too.
553    pub(crate) fn collect_impl_trait_clauses_from_hir_ty(
554        &self,
555        hir_ty: &'tcx hir::Ty<'tcx>,
556    ) -> ty::Clauses<'tcx> {
557        struct CollectClauses<'a, 'tcx> {
558            clauses: Vec<ty::Clause<'tcx>>,
559            fcx: &'a FnCtxt<'a, 'tcx>,
560        }
561
562        impl<'tcx> intravisit::Visitor<'tcx> for CollectClauses<'_, 'tcx> {
563            fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
564                if let Some(clauses) = self.fcx.trait_ascriptions.borrow().get(&ty.hir_id.local_id)
565                {
566                    self.clauses.extend(clauses.iter().cloned());
567                }
568                intravisit::walk_ty(self, ty)
569            }
570        }
571
572        let mut clauses = CollectClauses { clauses: ::alloc::vec::Vec::new()vec![], fcx: self };
573        clauses.visit_ty_unambig(hir_ty);
574        self.tcx.mk_clauses(&clauses.clauses)
575    }
576
577    #[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("lower_ty_saving_user_provided_ty",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(577u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = self.lower_ty(hir_ty);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:580",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(580u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::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()
                                                    }], ::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(&ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if Self::can_contain_user_lifetime_bounds(ty.raw) {
                let c_ty =
                    self.canonicalize_response(ty::UserType::new(ty::UserTypeKind::Ty(ty.raw)));
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:584",
                                        "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                        ::tracing_core::__macro_support::Option::Some(584u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("c_ty")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("c_ty");
                                                            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(&c_ty)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id,
                    c_ty);
            }
            ty.normalized
        }
    }
}#[instrument(level = "debug", skip_all)]
578    pub(crate) fn lower_ty_saving_user_provided_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
579        let ty = self.lower_ty(hir_ty);
580        debug!(?ty);
581
582        if Self::can_contain_user_lifetime_bounds(ty.raw) {
583            let c_ty = self.canonicalize_response(ty::UserType::new(ty::UserTypeKind::Ty(ty.raw)));
584            debug!(?c_ty);
585            self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id, c_ty);
586        }
587
588        ty.normalized
589    }
590
591    pub(super) fn user_args_for_adt(ty: LoweredTy<'tcx>) -> UserArgs<'tcx> {
592        match (ty.raw.kind(), ty.normalized.kind()) {
593            (ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None },
594            (_, ty::Adt(adt, args)) => UserArgs {
595                args,
596                user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }),
597            },
598            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-adt type {0:?}", ty))bug!("non-adt type {:?}", ty),
599        }
600    }
601
602    pub(crate) fn lower_const_arg(
603        &self,
604        const_arg: &'tcx hir::ConstArg<'tcx>,
605        ty: Ty<'tcx>,
606    ) -> ty::Const<'tcx> {
607        let ct = self.lowerer().lower_const_arg(const_arg, ty);
608        self.register_wf_obligation(
609            ct.into(),
610            self.tcx.hir_span(const_arg.hir_id),
611            ObligationCauseCode::WellFormed(None),
612        );
613        ct
614    }
615
616    // If the type given by the user has free regions, save it for later, since
617    // NLL would like to enforce those. Also pass in types that involve
618    // projections, since those can resolve to `'static` bounds (modulo #54940,
619    // which hopefully will be fixed by the time you see this comment, dear
620    // reader, although I have my doubts). Also pass in types with inference
621    // types, because they may be repeated. Other sorts of things are already
622    // sufficiently enforced with erased regions. =)
623    fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
624    where
625        T: TypeVisitable<TyCtxt<'tcx>>,
626    {
627        // FIXME(mgca): should this also count stuff with infer consts
628        t.has_free_regions() || t.has_aliases() || t.has_infer_types() || t.has_param()
629    }
630
631    pub(crate) fn node_ty(&self, id: HirId) -> Ty<'tcx> {
632        match self.typeck_results.borrow().node_types().get(id) {
633            Some(&t) => t,
634            None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e),
635            None => {
636                ::rustc_middle::util::bug::bug_fmt(format_args!("no type for node {0} in fcx {1}",
        self.tcx.hir_id_to_string(id), self.tag()));bug!("no type for node {} in fcx {}", self.tcx.hir_id_to_string(id), self.tag());
637            }
638        }
639    }
640
641    pub(crate) fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>> {
642        match self.typeck_results.borrow().node_types().get(id) {
643            Some(&t) => Some(t),
644            None if let Some(e) = self.tainted_by_errors() => Some(Ty::new_error(self.tcx, e)),
645            None => None,
646        }
647    }
648
649    /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
650    pub(crate) fn register_wf_obligation(
651        &self,
652        term: ty::Term<'tcx>,
653        span: Span,
654        code: traits::ObligationCauseCode<'tcx>,
655    ) {
656        // WF obligations never themselves fail, so no real need to give a detailed cause:
657        let cause = self.cause(span, code);
658        self.register_predicate(traits::Obligation::new(
659            self.tcx,
660            cause,
661            self.param_env,
662            ty::ClauseKind::WellFormed(term),
663        ));
664    }
665
666    /// Registers obligations that all `args` are well-formed.
667    pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span) {
668        for term in args.iter().filter_map(ty::GenericArg::as_term) {
669            self.register_wf_obligation(term, span, ObligationCauseCode::WellFormed(None));
670        }
671    }
672
673    // FIXME(arielb1): use this instead of field.ty everywhere
674    // Only for fields! Returns <none> for methods>
675    // Indifferent to privacy flags
676    pub(crate) fn field_ty(
677        &self,
678        span: Span,
679        field: &'tcx ty::FieldDef,
680        args: GenericArgsRef<'tcx>,
681    ) -> Ty<'tcx> {
682        self.normalize(span, field.ty(self.tcx, args))
683    }
684
685    /// Drain all obligations that are stalled on coroutines defined in this body.
686    #[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("drain_stalled_coroutine_obligations",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(686u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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;
        }
        {
            self.select_obligations_where_possible(|_| {});
            let defining_opaque_types_and_generators =
                match self.typing_mode() {
                    ty::TypingMode::Typeck {
                        defining_opaque_types_and_generators } => {
                        defining_opaque_types_and_generators
                    }
                    ty::TypingMode::Coherence |
                        ty::TypingMode::PostTypeckUntilBorrowck { .. } |
                        ty::TypingMode::PostBorrowck { .. } |
                        ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {
                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                    }
                };
            if defining_opaque_types_and_generators.iter().any(|def_id|
                        self.tcx.is_coroutine(def_id.to_def_id())) {
                self.typeck_results.borrow_mut().coroutine_stalled_predicates.extend(self.fulfillment_cx.borrow_mut().drain_stalled_obligations_for_coroutines(&self.infcx).into_iter().map(|o|
                            (o.predicate, o.cause)));
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
687    pub(crate) fn drain_stalled_coroutine_obligations(&self) {
688        // Make as much inference progress as possible before
689        // draining the stalled coroutine obligations as this may
690        // change obligations from being stalled on infer vars to
691        // being stalled on a coroutine.
692        self.select_obligations_where_possible(|_| {});
693
694        let defining_opaque_types_and_generators = match self.typing_mode() {
695            ty::TypingMode::Typeck { defining_opaque_types_and_generators } => {
696                defining_opaque_types_and_generators
697            }
698            ty::TypingMode::Coherence
699            | ty::TypingMode::PostTypeckUntilBorrowck { .. }
700            | ty::TypingMode::PostBorrowck { .. }
701            | ty::TypingMode::PostAnalysis
702            | ty::TypingMode::Codegen => {
703                bug!()
704            }
705        };
706
707        if defining_opaque_types_and_generators
708            .iter()
709            .any(|def_id| self.tcx.is_coroutine(def_id.to_def_id()))
710        {
711            self.typeck_results.borrow_mut().coroutine_stalled_predicates.extend(
712                self.fulfillment_cx
713                    .borrow_mut()
714                    .drain_stalled_obligations_for_coroutines(&self.infcx)
715                    .into_iter()
716                    .map(|o| (o.predicate, o.cause)),
717            );
718        }
719    }
720
721    #[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("report_ambiguity_errors",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(721u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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;
        }
        {
            let mut errors =
                self.fulfillment_cx.borrow_mut().collect_remaining_errors(self);
            if !errors.is_empty() {
                self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
                self.err_ctxt().report_fulfillment_errors(errors);
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
722    pub(crate) fn report_ambiguity_errors(&self) {
723        let mut errors = self.fulfillment_cx.borrow_mut().collect_remaining_errors(self);
724
725        if !errors.is_empty() {
726            self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
727            self.err_ctxt().report_fulfillment_errors(errors);
728        }
729    }
730
731    /// Select as many obligations as we can at present.
732    pub(crate) fn select_obligations_where_possible(
733        &self,
734        mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
735    ) {
736        let mut result = self.fulfillment_cx.borrow_mut().try_evaluate_obligations(self);
737        if !result.is_empty() {
738            mutate_fulfillment_errors(&mut result);
739            self.adjust_fulfillment_errors_for_expr_obligation(&mut result);
740            self.err_ctxt().report_fulfillment_errors(result);
741        }
742    }
743
744    /// For the overloaded place expressions (`*x`, `x[3]`), the trait
745    /// returns a type of `&T`, but the actual type we assign to the
746    /// *expression* is `T`. So this function just peels off the return
747    /// type by one layer to yield `T`.
748    pub(crate) fn make_overloaded_place_return_type(&self, method: MethodCallee<'tcx>) -> Ty<'tcx> {
749        // extract method return type, which will be &T;
750        let ret_ty = method.sig.output();
751
752        // method returns &T, but the type as visible to user is T, so deref
753        ret_ty.builtin_deref(true).unwrap()
754    }
755
756    pub(crate) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
757        let sized_did = self.tcx.lang_items().sized_trait();
758
759        // NB: `T: Sized` implies that all subtypes and all supertypes of `T` are also sized,
760        //     so it's valid to use subtyping here. (subtyping has to preserve layout and
761        //     `T <: U => &T <: &U`, so subtyping can't change sizedness)
762        self.obligations_for_self_ty(self_ty, super::UseSubtyping::Yes).into_iter().any(
763            |obligation| match obligation.predicate.kind().skip_binder() {
764                ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
765                    Some(data.def_id()) == sized_did
766                }
767                _ => false,
768            },
769        )
770    }
771
772    pub(crate) fn err_args(&self, len: usize, guar: ErrorGuaranteed) -> Vec<Ty<'tcx>> {
773        let ty_error = Ty::new_error(self.tcx, guar);
774        ::alloc::vec::from_elem(ty_error, len)vec![ty_error; len]
775    }
776
777    /// Resolves an associated value path into a base type and associated constant, or method
778    /// resolution. The newly resolved definition is written into `type_dependent_defs`.
779    x;#[instrument(level = "trace", skip(self), ret)]
780    pub(crate) fn resolve_ty_and_res_fully_qualified_call(
781        &self,
782        qpath: &'tcx QPath<'tcx>,
783        hir_id: HirId,
784        span: Span,
785    ) -> (Res, Option<LoweredTy<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
786        let (ty, qself, item_segment) = match *qpath {
787            QPath::Resolved(ref opt_qself, path) => {
788                return (
789                    path.res,
790                    opt_qself.as_ref().map(|qself| self.lower_ty(qself)),
791                    path.segments,
792                );
793            }
794            QPath::TypeRelative(ref qself, ref segment) => {
795                // Don't use `self.lower_ty`, since this will register a WF obligation.
796                // If we're trying to call a nonexistent method on a trait
797                // (e.g. `MyTrait::missing_method`), then resolution will
798                // give us a `QPath::TypeRelative` with a trait object as
799                // `qself`. In that case, we want to avoid registering a WF obligation
800                // for `dyn MyTrait`, since we don't actually need the trait
801                // to be dyn-compatible.
802                // We manually call `register_wf_obligation` in the success path
803                // below.
804                let ty = self.lowerer().lower_ty(qself);
805                (LoweredTy::from_raw(self, span, ty), qself, segment)
806            }
807        };
808
809        self.register_wf_obligation(
810            ty.raw.into(),
811            qself.span,
812            ObligationCauseCode::WellFormed(None),
813        );
814        self.select_obligations_where_possible(|_| {});
815
816        if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
817        {
818            // Return directly on cache hit. This is useful to avoid doubly reporting
819            // errors with default match binding modes. See #44614.
820            let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
821            return (def, Some(ty), slice::from_ref(&**item_segment));
822        }
823        let item_name = item_segment.ident;
824        let result = self
825            .resolve_fully_qualified_call(span, item_name, ty.normalized, qself.span, hir_id)
826            .or_else(|error| {
827                let guar = self
828                    .dcx()
829                    .span_delayed_bug(span, "method resolution should've emitted an error");
830                let result = match error {
831                    method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
832                    _ => Err(guar),
833                };
834
835                let trait_missing_method =
836                    matches!(error, method::MethodError::NoMatch(_)) && ty.normalized.is_trait();
837                self.report_method_error(
838                    hir_id,
839                    ty.normalized,
840                    error,
841                    Expectation::NoExpectation,
842                    trait_missing_method && span.edition().at_least_rust_2021(), // emits missing method for trait only after edition 2021
843                );
844
845                result
846            });
847
848        // Write back the new resolution.
849        self.write_resolution(hir_id, result);
850        (
851            result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
852            Some(ty),
853            slice::from_ref(&**item_segment),
854        )
855    }
856
857    /// Given a `HirId`, return the `HirId` of the enclosing function and its `FnDecl`.
858    pub(crate) fn get_fn_decl(
859        &self,
860        blk_id: HirId,
861    ) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>)> {
862        // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
863        // `while` before reaching it, as block tail returns are not available in them.
864        self.tcx.hir_get_fn_id_for_return_block(blk_id).and_then(|item_id| {
865            match self.tcx.hir_node(item_id) {
866                Node::Item(&hir::Item {
867                    kind: hir::ItemKind::Fn { sig, .. }, owner_id, ..
868                }) => Some((owner_id.def_id, sig.decl)),
869                Node::TraitItem(&hir::TraitItem {
870                    kind: hir::TraitItemKind::Fn(ref sig, ..),
871                    owner_id,
872                    ..
873                }) => Some((owner_id.def_id, sig.decl)),
874                Node::ImplItem(&hir::ImplItem {
875                    kind: hir::ImplItemKind::Fn(ref sig, ..),
876                    owner_id,
877                    ..
878                }) => Some((owner_id.def_id, sig.decl)),
879                Node::Expr(&hir::Expr {
880                    hir_id,
881                    kind: hir::ExprKind::Closure(&hir::Closure { def_id, kind, fn_decl, .. }),
882                    ..
883                }) => {
884                    match kind {
885                        hir::ClosureKind::CoroutineClosure(_) => {
886                            // FIXME(async_closures): Implement this.
887                            return None;
888                        }
889                        hir::ClosureKind::Closure => Some((def_id, fn_decl)),
890                        hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
891                            _,
892                            hir::CoroutineSource::Fn,
893                        )) => {
894                            let (sig, owner_id) = match self.tcx.parent_hir_node(hir_id) {
895                                Node::Item(&hir::Item {
896                                    kind: hir::ItemKind::Fn { ref sig, .. },
897                                    owner_id,
898                                    ..
899                                }) => (sig, owner_id),
900                                Node::TraitItem(&hir::TraitItem {
901                                    kind: hir::TraitItemKind::Fn(ref sig, ..),
902                                    owner_id,
903                                    ..
904                                }) => (sig, owner_id),
905                                Node::ImplItem(&hir::ImplItem {
906                                    kind: hir::ImplItemKind::Fn(ref sig, ..),
907                                    owner_id,
908                                    ..
909                                }) => (sig, owner_id),
910                                _ => return None,
911                            };
912                            Some((owner_id.def_id, sig.decl))
913                        }
914                        _ => None,
915                    }
916                }
917                _ => None,
918            }
919        })
920    }
921
922    pub(crate) fn note_internal_mutation_in_method(
923        &self,
924        err: &mut Diag<'_>,
925        expr: &hir::Expr<'_>,
926        expected: Option<Ty<'tcx>>,
927        found: Ty<'tcx>,
928    ) {
929        if found != self.tcx.types.unit {
930            return;
931        }
932
933        let ExprKind::MethodCall(path_segment, rcvr, ..) = expr.kind else {
934            return;
935        };
936
937        let rcvr_has_the_expected_type = self
938            .typeck_results
939            .borrow()
940            .expr_ty_adjusted_opt(rcvr)
941            .zip(expected)
942            .is_some_and(|(ty, expected_ty)| expected_ty.peel_refs() == ty.peel_refs());
943
944        let prev_call_mutates_and_returns_unit = || {
945            self.typeck_results
946                .borrow()
947                .type_dependent_def_id(expr.hir_id)
948                .map(|def_id| self.tcx.fn_sig(def_id).skip_binder().skip_binder())
949                .and_then(|sig| sig.inputs_and_output.split_last())
950                .is_some_and(|(output, inputs)| {
951                    output.is_unit()
952                        && inputs
953                            .get(0)
954                            .and_then(|self_ty| self_ty.ref_mutability())
955                            .is_some_and(rustc_ast::Mutability::is_mut)
956                })
957        };
958
959        if !(rcvr_has_the_expected_type || prev_call_mutates_and_returns_unit()) {
960            return;
961        }
962
963        let mut sp = MultiSpan::from_span(path_segment.ident.span);
964        sp.push_span_label(
965            path_segment.ident.span,
966            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this call modifies {0} in-place",
                match rcvr.kind {
                    ExprKind::Path(QPath::Resolved(None, hir::Path {
                        segments: [segment], .. })) =>
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("`{0}`", segment.ident))
                            }),
                    _ => "its receiver".to_string(),
                }))
    })format!(
967                "this call modifies {} in-place",
968                match rcvr.kind {
969                    ExprKind::Path(QPath::Resolved(
970                        None,
971                        hir::Path { segments: [segment], .. },
972                    )) => format!("`{}`", segment.ident),
973                    _ => "its receiver".to_string(),
974                }
975            ),
976        );
977
978        let modifies_rcvr_note =
979            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("method `{0}` modifies its receiver in-place",
                path_segment.ident))
    })format!("method `{}` modifies its receiver in-place", path_segment.ident);
980        if rcvr_has_the_expected_type {
981            sp.push_span_label(
982                rcvr.span,
983                "you probably want to use this value after calling the method...",
984            );
985            err.span_note(sp, modifies_rcvr_note);
986            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...instead of the `()` output of method `{0}`",
                path_segment.ident))
    })format!("...instead of the `()` output of method `{}`", path_segment.ident));
987        } else if let ExprKind::MethodCall(..) = rcvr.kind {
988            err.span_note(
989                sp,
990                modifies_rcvr_note + ", it is not meant to be used in method chains.",
991            );
992        } else {
993            err.span_note(sp, modifies_rcvr_note);
994        }
995    }
996
997    // Instantiates the given path, which must refer to an item with the given
998    // number of type parameters and type.
999    #[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("instantiate_value_path",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(999u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("segments")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("segments");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_id");
                                                        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(&segments)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
                                                            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: (Ty<'tcx>, Res) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let generic_segments =
                match res {
                    Res::Local(_) | Res::SelfCtor(_) =>
                        ::alloc::vec::Vec::new(),
                    Res::Def(kind, def_id) =>
                        self.lowerer().probe_generic_path_segments(segments,
                            self_ty.map(|ty| ty.raw), kind, def_id, span),
                    Res::Err => {
                        return (Ty::new_error(tcx,
                                    tcx.dcx().span_delayed_bug(span,
                                        "could not resolve path {:?}")), res);
                    }
                    _ =>
                        ::rustc_middle::util::bug::bug_fmt(format_args!("instantiate_value_path on {0:?}",
                                res)),
                };
            let mut user_self_ty = None;
            let mut is_alias_variant_ctor = false;
            let mut err_extend = GenericsArgsErrExtend::None;
            match res {
                Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if
                    let Some(self_ty) = self_ty => {
                    let adt_def = self_ty.normalized.ty_adt_def().unwrap();
                    user_self_ty =
                        Some(UserSelfTy {
                                impl_def_id: adt_def.did(),
                                self_ty: self_ty.raw,
                            });
                    is_alias_variant_ctor = true;
                    err_extend = GenericsArgsErrExtend::DefVariant(segments);
                }
                Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
                    err_extend = GenericsArgsErrExtend::DefVariant(segments);
                }
                Res::Def(DefKind::AssocFn | DefKind::AssocConst { .. },
                    def_id) => {
                    let assoc_item = tcx.associated_item(def_id);
                    let container = assoc_item.container;
                    let container_id = assoc_item.container_id(tcx);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:1050",
                                            "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                            ::tracing_core::__macro_support::Option::Some(1050u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("def_id")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("def_id");
                                                                NAME.as_str()
                                                            },
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("container")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("container");
                                                                NAME.as_str()
                                                            },
                                                            {
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("container_id")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("container_id");
                                                                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(&def_id)
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&container)
                                                                as &dyn ::tracing::field::Value)),
                                                    (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&container_id)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    match container {
                        ty::AssocContainer::Trait => {
                            let arg_span =
                                if let hir::Node::Expr(call_expr) =
                                                self.tcx.parent_hir_node(hir_id) &&
                                            let hir::ExprKind::Call(_, args) = call_expr.kind &&
                                        let Some(first_arg) = args.first() {
                                    let mut arg = first_arg;
                                    while let hir::ExprKind::AddrOf(_, _, inner) = arg.kind {
                                        arg = inner;
                                    }
                                    Some(arg.span)
                                } else { None };
                            if let Err(e) =
                                    callee::check_legal_trait_for_method_call(tcx, path_span,
                                        arg_span, span, container_id, self.body_def_id.to_def_id())
                                {
                                self.set_tainted_by_errors(e);
                            }
                        }
                        ty::AssocContainer::InherentImpl |
                            ty::AssocContainer::TraitImpl(_) => {
                            if segments.len() == 1 {
                                user_self_ty =
                                    self_ty.map(|self_ty|
                                            UserSelfTy {
                                                impl_def_id: container_id,
                                                self_ty: self_ty.raw,
                                            });
                            }
                        }
                    }
                }
                _ => {}
            }
            let indices: FxHashSet<_> =
                generic_segments.iter().map(|GenericPathSegment(_, index)|
                            index).collect();
            let generics_err =
                self.lowerer().prohibit_generic_args(segments.iter().enumerate().filter_map(|(index,
                                seg)|
                            {
                                if !indices.contains(&index) || is_alias_variant_ctor {
                                    Some(seg)
                                } else { None }
                            }), err_extend);
            if let Err(e) =
                    self.lowerer().check_param_res_if_mcg_for_instantiate_value_path(res,
                        span) {
                return (Ty::new_error(self.tcx, e), res);
            }
            if let Res::Local(hid) = res {
                let ty = self.local_ty(span, hid);
                let ty = self.normalize(span, Unnormalized::new_wip(ty));
                return (ty, res);
            }
            if let Err(_) = generics_err { user_self_ty = None; }
            let mut infer_args_for_err = None;
            let mut explicit_late_bound = ExplicitLateBound::No;
            for &GenericPathSegment(def_id, index) in &generic_segments {
                let seg = &segments[index];
                let generics = tcx.generics_of(def_id);
                let arg_count =
                    check_generic_arg_count_for_value_path(self, def_id,
                        generics, seg, IsMethodCall::No);
                if let ExplicitLateBound::Yes = arg_count.explicit_late_bound
                    {
                    explicit_late_bound = ExplicitLateBound::Yes;
                }
                if let Err(GenericArgCountMismatch { reported, .. }) =
                        arg_count.correct {
                    infer_args_for_err.get_or_insert_with(||
                                    (reported, FxHashSet::default())).1.insert(index);
                    self.set_tainted_by_errors(reported);
                }
            }
            let has_self =
                generic_segments.last().is_some_and(|GenericPathSegment(def_id,
                            _)| tcx.generics_of(*def_id).has_self);
            let (res, implicit_args) =
                if let Res::Def(DefKind::ConstParam, def) = res {
                    (res,
                        Some(ty::GenericArgs::identity_for_item(tcx,
                                tcx.parent(def))))
                } else if let Res::SelfCtor(impl_def_id) = res {
                    let ty =
                        LoweredTy::from_raw(self, span,
                            tcx.at(span).type_of(impl_def_id).instantiate_identity().skip_norm_wip());
                    if std::iter::successors(Some(self.body_def_id.to_def_id()),
                                |&def_id|
                                    {
                                        self.tcx.generics_of(def_id).parent
                                    }).all(|def_id| def_id != impl_def_id) {
                        let sugg =
                            ty.normalized.ty_adt_def().map(|def|
                                    diagnostics::ReplaceWithName {
                                        span: path_span,
                                        name: self.tcx.item_name(def.did()).to_ident_string(),
                                    });
                        let item =
                            match self.tcx.hir_node_by_def_id(self.tcx.hir_get_parent_item(hir_id).def_id)
                                {
                                hir::Node::Item(item) =>
                                    Some(diagnostics::InnerItem {
                                            span: item.kind.ident().map(|i| i.span).unwrap_or(item.span),
                                        }),
                                _ => None,
                            };
                        if ty.raw.has_param() {
                            let guar =
                                self.dcx().emit_err(diagnostics::SelfCtorFromOuterItem {
                                        span: path_span,
                                        impl_span: tcx.def_span(impl_def_id),
                                        sugg,
                                        item,
                                    });
                            return (Ty::new_error(self.tcx, guar), res);
                        } else {
                            self.tcx.emit_node_span_lint(SELF_CONSTRUCTOR_FROM_OUTER_ITEM,
                                hir_id, path_span,
                                diagnostics::SelfCtorFromOuterItemLint {
                                    impl_span: tcx.def_span(impl_def_id),
                                    sugg,
                                    item,
                                });
                        }
                    }
                    match ty.normalized.ty_adt_def() {
                        Some(adt_def) if adt_def.has_ctor() => {
                            let (ctor_kind, ctor_def_id) =
                                adt_def.non_enum_variant().ctor.unwrap();
                            let vis = tcx.visibility(ctor_def_id);
                            if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(),
                                        tcx) {
                                self.dcx().emit_err(CtorIsPrivate {
                                        span,
                                        def: tcx.def_path_str(adt_def.did()),
                                    });
                            }
                            let new_res =
                                Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind),
                                    ctor_def_id);
                            let user_args = Self::user_args_for_adt(ty);
                            user_self_ty = user_args.user_self_ty;
                            (new_res, Some(user_args.args))
                        }
                        _ => {
                            let mut err =
                                self.dcx().struct_span_err(span,
                                    "the `Self` constructor can only be used with tuple or unit structs");
                            if let Some(adt_def) = ty.normalized.ty_adt_def() {
                                match adt_def.adt_kind() {
                                    AdtKind::Enum => {
                                        err.help("did you mean to use one of the enum's variants?");
                                    }
                                    AdtKind::Struct | AdtKind::Union => {
                                        err.span_suggestion(span, "use curly brackets",
                                            "Self { /* fields */ }", Applicability::HasPlaceholders);
                                    }
                                }
                            }
                            let reported = err.emit();
                            return (Ty::new_error(tcx, reported), res);
                        }
                    }
                } else { (res, None) };
            let def_id = res.def_id();
            let (correct, infer_args_for_err) =
                match infer_args_for_err {
                    Some((reported, args)) => {
                        (Err(GenericArgCountMismatch {
                                    reported,
                                    invalid_args: ::alloc::vec::Vec::new(),
                                }), args)
                    }
                    None => (Ok(()), Default::default()),
                };
            let arg_count =
                GenericArgCountResult { explicit_late_bound, correct };
            struct CtorGenericArgsCtxt<'a, 'tcx> {
                fcx: &'a FnCtxt<'a, 'tcx>,
                span: Span,
                generic_segments: &'a [GenericPathSegment],
                infer_args_for_err: &'a FxHashSet<usize>,
                segments: &'tcx [hir::PathSegment<'tcx>],
            }
            impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for
                CtorGenericArgsCtxt<'a, 'tcx> {
                fn args_for_def_id(&mut self, def_id: DefId)
                    -> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
                    if let Some(&GenericPathSegment(_, index)) =
                            self.generic_segments.iter().find(|&GenericPathSegment(did,
                                        _)| *did == def_id) {
                        if !self.infer_args_for_err.contains(&index) {
                            if let Some(data) = self.segments[index].args {
                                return (Some(data), self.segments[index].infer_args);
                            }
                        }
                        return (None, self.segments[index].infer_args);
                    }
                    (None, true)
                }
                fn provided_kind(&mut self,
                    preceding_args: &[ty::GenericArg<'tcx>],
                    param: &ty::GenericParamDef, arg: &GenericArg<'tcx>)
                    -> ty::GenericArg<'tcx> {
                    match (&param.kind, arg) {
                        (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) =>
                            self.fcx.lowerer().lower_lifetime(lt,
                                    RegionInferReason::Param(param)).into(),
                        (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) =>
                            {
                            self.fcx.lower_ty(ty.as_unambig_ty()).raw.into()
                        }
                        (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf))
                            => {
                            self.fcx.lower_ty(&inf.to_ty()).raw.into()
                        }
                        (GenericParamDefKind::Const { .. }, GenericArg::Const(ct))
                            =>
                            self.fcx.lower_const_arg(ct.as_unambig_ct(),
                                    self.fcx.tcx.type_of(param.def_id).instantiate(self.fcx.tcx,
                                            preceding_args).skip_norm_wip()).into(),
                        (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf))
                            => {
                            self.fcx.ct_infer(Some(param), inf.span).into()
                        }
                        _ =>
                            ::core::panicking::panic("internal error: entered unreachable code"),
                    }
                }
                fn inferred_kind(&mut self,
                    preceding_args: &[ty::GenericArg<'tcx>],
                    param: &ty::GenericParamDef, infer_args: bool)
                    -> ty::GenericArg<'tcx> {
                    let tcx = self.fcx.tcx();
                    if !infer_args &&
                            let Some(default) = param.default_value(tcx) {
                        return default.instantiate(tcx,
                                    preceding_args).skip_norm_wip();
                    }
                    self.fcx.var_for_def(self.span, param)
                }
            }
            let args_raw =
                implicit_args.unwrap_or_else(||
                        {
                            lower_generic_args(self, def_id, &[], has_self,
                                self_ty.map(|s| s.raw), &arg_count,
                                &mut CtorGenericArgsCtxt {
                                        fcx: self,
                                        span,
                                        generic_segments: &generic_segments,
                                        infer_args_for_err: &infer_args_for_err,
                                        segments,
                                    })
                        });
            let args_for_user_type =
                if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
                    self.transform_args_for_inherent_type_const(def_id,
                        args_raw)
                } else { args_raw };
            self.write_user_type_annotation_from_args(hir_id, def_id,
                args_for_user_type, user_self_ty);
            let args = self.normalize(span, Unnormalized::new_wip(args_raw));
            self.add_required_obligations_for_hir(span, def_id, args, hir_id);
            let ty = tcx.type_of(def_id);
            if !!args.has_escaping_bound_vars() {
                ::core::panicking::panic("assertion failed: !args.has_escaping_bound_vars()")
            };
            if !!ty.skip_binder().has_escaping_bound_vars() {
                ::core::panicking::panic("assertion failed: !ty.skip_binder().has_escaping_bound_vars()")
            };
            let ty_instantiated =
                self.normalize(span, ty.instantiate(tcx, args));
            if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
                let impl_ty =
                    self.normalize(span,
                        tcx.type_of(impl_def_id).instantiate(tcx, args));
                let self_ty =
                    self.normalize(span, Unnormalized::new_wip(self_ty));
                match self.at(&self.misc(span),
                            self.param_env).eq(DefineOpaqueTypes::Yes, impl_ty, self_ty)
                    {
                    Ok(ok) => self.register_infer_ok_obligations(ok),
                    Err(_) => {
                        self.dcx().span_bug(span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("instantiate_value_path: (UFCS) {0:?} was a subtype of {1:?} but now is not?",
                                            self_ty, impl_ty))
                                }));
                    }
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:1438",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1438u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::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!("instantiate_value_path: type of {0:?} is {1:?}",
                                                                hir_id, ty_instantiated) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let args =
                if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
                    self.transform_args_for_inherent_type_const(def_id, args)
                } else { args };
            self.write_args(hir_id, args);
            (ty_instantiated, res)
        }
    }
}#[instrument(skip(self, span), level = "debug")]
1000    pub(crate) fn instantiate_value_path(
1001        &self,
1002        segments: &'tcx [hir::PathSegment<'tcx>],
1003        self_ty: Option<LoweredTy<'tcx>>,
1004        res: Res,
1005        span: Span,
1006        path_span: Span,
1007        hir_id: HirId,
1008    ) -> (Ty<'tcx>, Res) {
1009        let tcx = self.tcx;
1010
1011        let generic_segments = match res {
1012            Res::Local(_) | Res::SelfCtor(_) => vec![],
1013            Res::Def(kind, def_id) => self.lowerer().probe_generic_path_segments(
1014                segments,
1015                self_ty.map(|ty| ty.raw),
1016                kind,
1017                def_id,
1018                span,
1019            ),
1020            Res::Err => {
1021                return (
1022                    Ty::new_error(
1023                        tcx,
1024                        tcx.dcx().span_delayed_bug(span, "could not resolve path {:?}"),
1025                    ),
1026                    res,
1027                );
1028            }
1029            _ => bug!("instantiate_value_path on {:?}", res),
1030        };
1031
1032        let mut user_self_ty = None;
1033        let mut is_alias_variant_ctor = false;
1034        let mut err_extend = GenericsArgsErrExtend::None;
1035        match res {
1036            Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if let Some(self_ty) = self_ty => {
1037                let adt_def = self_ty.normalized.ty_adt_def().unwrap();
1038                user_self_ty =
1039                    Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty: self_ty.raw });
1040                is_alias_variant_ctor = true;
1041                err_extend = GenericsArgsErrExtend::DefVariant(segments);
1042            }
1043            Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
1044                err_extend = GenericsArgsErrExtend::DefVariant(segments);
1045            }
1046            Res::Def(DefKind::AssocFn | DefKind::AssocConst { .. }, def_id) => {
1047                let assoc_item = tcx.associated_item(def_id);
1048                let container = assoc_item.container;
1049                let container_id = assoc_item.container_id(tcx);
1050                debug!(?def_id, ?container, ?container_id);
1051                match container {
1052                    ty::AssocContainer::Trait => {
1053                        let arg_span = if let hir::Node::Expr(call_expr) =
1054                            self.tcx.parent_hir_node(hir_id)
1055                            && let hir::ExprKind::Call(_, args) = call_expr.kind
1056                            && let Some(first_arg) = args.first()
1057                        {
1058                            let mut arg = first_arg;
1059                            while let hir::ExprKind::AddrOf(_, _, inner) = arg.kind {
1060                                arg = inner;
1061                            }
1062                            Some(arg.span)
1063                        } else {
1064                            None
1065                        };
1066
1067                        if let Err(e) = callee::check_legal_trait_for_method_call(
1068                            tcx,
1069                            path_span,
1070                            arg_span,
1071                            span,
1072                            container_id,
1073                            self.body_def_id.to_def_id(),
1074                        ) {
1075                            self.set_tainted_by_errors(e);
1076                        }
1077                    }
1078                    ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1079                        if segments.len() == 1 {
1080                            // `<T>::assoc` will end up here, and so
1081                            // can `T::assoc`. If this came from an
1082                            // inherent impl, we need to record the
1083                            // `T` for posterity (see `UserSelfTy` for
1084                            // details).
1085                            // Generated desugaring code may have a path without a self.
1086                            user_self_ty = self_ty.map(|self_ty| UserSelfTy {
1087                                impl_def_id: container_id,
1088                                self_ty: self_ty.raw,
1089                            });
1090                        }
1091                    }
1092                }
1093            }
1094            _ => {}
1095        }
1096
1097        // Now that we have categorized what space the parameters for each
1098        // segment belong to, let's sort out the parameters that the user
1099        // provided (if any) into their appropriate spaces. We'll also report
1100        // errors if type parameters are provided in an inappropriate place.
1101
1102        let indices: FxHashSet<_> =
1103            generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
1104        let generics_err = self.lowerer().prohibit_generic_args(
1105            segments.iter().enumerate().filter_map(|(index, seg)| {
1106                if !indices.contains(&index) || is_alias_variant_ctor { Some(seg) } else { None }
1107            }),
1108            err_extend,
1109        );
1110
1111        if let Err(e) = self.lowerer().check_param_res_if_mcg_for_instantiate_value_path(res, span)
1112        {
1113            return (Ty::new_error(self.tcx, e), res);
1114        }
1115
1116        if let Res::Local(hid) = res {
1117            let ty = self.local_ty(span, hid);
1118            let ty = self.normalize(span, Unnormalized::new_wip(ty));
1119            return (ty, res);
1120        }
1121
1122        if let Err(_) = generics_err {
1123            // Don't try to infer type parameters when prohibited generic arguments were given.
1124            user_self_ty = None;
1125        }
1126
1127        // Now we have to compare the types that the user *actually*
1128        // provided against the types that were *expected*. If the user
1129        // did not provide any types, then we want to instantiate inference
1130        // variables. If the user provided some types, we may still need
1131        // to add defaults. If the user provided *too many* types, that's
1132        // a problem.
1133
1134        let mut infer_args_for_err = None;
1135
1136        let mut explicit_late_bound = ExplicitLateBound::No;
1137        for &GenericPathSegment(def_id, index) in &generic_segments {
1138            let seg = &segments[index];
1139            let generics = tcx.generics_of(def_id);
1140
1141            // Argument-position `impl Trait` is treated as a normal generic
1142            // parameter internally, but we don't allow users to specify the
1143            // parameter's value explicitly, so we have to do some error-
1144            // checking here.
1145            let arg_count = check_generic_arg_count_for_value_path(
1146                self,
1147                def_id,
1148                generics,
1149                seg,
1150                IsMethodCall::No,
1151            );
1152
1153            if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1154                explicit_late_bound = ExplicitLateBound::Yes;
1155            }
1156
1157            if let Err(GenericArgCountMismatch { reported, .. }) = arg_count.correct {
1158                infer_args_for_err
1159                    .get_or_insert_with(|| (reported, FxHashSet::default()))
1160                    .1
1161                    .insert(index);
1162                self.set_tainted_by_errors(reported); // See issue #53251.
1163            }
1164        }
1165
1166        let has_self = generic_segments
1167            .last()
1168            .is_some_and(|GenericPathSegment(def_id, _)| tcx.generics_of(*def_id).has_self);
1169
1170        let (res, implicit_args) = if let Res::Def(DefKind::ConstParam, def) = res {
1171            // types of const parameters are somewhat special as they are part of
1172            // the same environment as the const parameter itself. this means that
1173            // unlike most paths `type-of(N)` can return a type naming parameters
1174            // introduced by the containing item, rather than provided through `N`.
1175            //
1176            // for example given `<T, const M: usize, const N: [T; M]>` and some
1177            // `let a = N;` expression. The path to `N` would wind up with no args
1178            // (as it has no args), but instantiating the early binder on `typeof(N)`
1179            // requires providing generic arguments for `[T, M, N]`.
1180            (res, Some(ty::GenericArgs::identity_for_item(tcx, tcx.parent(def))))
1181        } else if let Res::SelfCtor(impl_def_id) = res {
1182            let ty = LoweredTy::from_raw(
1183                self,
1184                span,
1185                tcx.at(span).type_of(impl_def_id).instantiate_identity().skip_norm_wip(),
1186            );
1187
1188            // Firstly, check that this SelfCtor even comes from the item we're currently
1189            // typechecking. This can happen because we never validated the resolution of
1190            // SelfCtors, and when we started doing so, we noticed regressions. After
1191            // sufficiently long time, we can remove this check and turn it into a hard
1192            // error in `validate_res_from_ribs` -- it's just difficult to tell whether the
1193            // self type has any generic types during rustc_resolve, which is what we use
1194            // to determine if this is a hard error or warning.
1195            if std::iter::successors(Some(self.body_def_id.to_def_id()), |&def_id| {
1196                self.tcx.generics_of(def_id).parent
1197            })
1198            .all(|def_id| def_id != impl_def_id)
1199            {
1200                let sugg = ty.normalized.ty_adt_def().map(|def| diagnostics::ReplaceWithName {
1201                    span: path_span,
1202                    name: self.tcx.item_name(def.did()).to_ident_string(),
1203                });
1204                let item = match self
1205                    .tcx
1206                    .hir_node_by_def_id(self.tcx.hir_get_parent_item(hir_id).def_id)
1207                {
1208                    hir::Node::Item(item) => Some(diagnostics::InnerItem {
1209                        span: item.kind.ident().map(|i| i.span).unwrap_or(item.span),
1210                    }),
1211                    _ => None,
1212                };
1213                if ty.raw.has_param() {
1214                    let guar = self.dcx().emit_err(diagnostics::SelfCtorFromOuterItem {
1215                        span: path_span,
1216                        impl_span: tcx.def_span(impl_def_id),
1217                        sugg,
1218                        item,
1219                    });
1220                    return (Ty::new_error(self.tcx, guar), res);
1221                } else {
1222                    self.tcx.emit_node_span_lint(
1223                        SELF_CONSTRUCTOR_FROM_OUTER_ITEM,
1224                        hir_id,
1225                        path_span,
1226                        diagnostics::SelfCtorFromOuterItemLint {
1227                            impl_span: tcx.def_span(impl_def_id),
1228                            sugg,
1229                            item,
1230                        },
1231                    );
1232                }
1233            }
1234
1235            match ty.normalized.ty_adt_def() {
1236                Some(adt_def) if adt_def.has_ctor() => {
1237                    let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap();
1238                    // Check the visibility of the ctor.
1239                    let vis = tcx.visibility(ctor_def_id);
1240                    if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) {
1241                        self.dcx()
1242                            .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) });
1243                    }
1244                    let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1245                    let user_args = Self::user_args_for_adt(ty);
1246                    user_self_ty = user_args.user_self_ty;
1247                    (new_res, Some(user_args.args))
1248                }
1249                _ => {
1250                    let mut err = self.dcx().struct_span_err(
1251                        span,
1252                        "the `Self` constructor can only be used with tuple or unit structs",
1253                    );
1254                    if let Some(adt_def) = ty.normalized.ty_adt_def() {
1255                        match adt_def.adt_kind() {
1256                            AdtKind::Enum => {
1257                                err.help("did you mean to use one of the enum's variants?");
1258                            }
1259                            AdtKind::Struct | AdtKind::Union => {
1260                                err.span_suggestion(
1261                                    span,
1262                                    "use curly brackets",
1263                                    "Self { /* fields */ }",
1264                                    Applicability::HasPlaceholders,
1265                                );
1266                            }
1267                        }
1268                    }
1269                    let reported = err.emit();
1270                    return (Ty::new_error(tcx, reported), res);
1271                }
1272            }
1273        } else {
1274            (res, None)
1275        };
1276        let def_id = res.def_id();
1277
1278        let (correct, infer_args_for_err) = match infer_args_for_err {
1279            Some((reported, args)) => {
1280                (Err(GenericArgCountMismatch { reported, invalid_args: vec![] }), args)
1281            }
1282            None => (Ok(()), Default::default()),
1283        };
1284
1285        let arg_count = GenericArgCountResult { explicit_late_bound, correct };
1286
1287        struct CtorGenericArgsCtxt<'a, 'tcx> {
1288            fcx: &'a FnCtxt<'a, 'tcx>,
1289            span: Span,
1290            generic_segments: &'a [GenericPathSegment],
1291            infer_args_for_err: &'a FxHashSet<usize>,
1292            segments: &'tcx [hir::PathSegment<'tcx>],
1293        }
1294        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for CtorGenericArgsCtxt<'a, 'tcx> {
1295            fn args_for_def_id(
1296                &mut self,
1297                def_id: DefId,
1298            ) -> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
1299                if let Some(&GenericPathSegment(_, index)) =
1300                    self.generic_segments.iter().find(|&GenericPathSegment(did, _)| *did == def_id)
1301                {
1302                    // If we've encountered an `impl Trait`-related error, we're just
1303                    // going to infer the arguments for better error messages.
1304                    if !self.infer_args_for_err.contains(&index) {
1305                        // Check whether the user has provided generic arguments.
1306                        if let Some(data) = self.segments[index].args {
1307                            return (Some(data), self.segments[index].infer_args);
1308                        }
1309                    }
1310                    return (None, self.segments[index].infer_args);
1311                }
1312
1313                (None, true)
1314            }
1315
1316            fn provided_kind(
1317                &mut self,
1318                preceding_args: &[ty::GenericArg<'tcx>],
1319                param: &ty::GenericParamDef,
1320                arg: &GenericArg<'tcx>,
1321            ) -> ty::GenericArg<'tcx> {
1322                match (&param.kind, arg) {
1323                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => self
1324                        .fcx
1325                        .lowerer()
1326                        .lower_lifetime(lt, RegionInferReason::Param(param))
1327                        .into(),
1328                    (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1329                        // We handle the ambig portions of `Ty` in match arm below
1330                        self.fcx.lower_ty(ty.as_unambig_ty()).raw.into()
1331                    }
1332                    (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1333                        self.fcx.lower_ty(&inf.to_ty()).raw.into()
1334                    }
1335                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
1336                        .fcx
1337                        // Ambiguous parts of `ConstArg` are handled in the match arms below
1338                        .lower_const_arg(
1339                            ct.as_unambig_ct(),
1340                            self.fcx
1341                                .tcx
1342                                .type_of(param.def_id)
1343                                .instantiate(self.fcx.tcx, preceding_args)
1344                                .skip_norm_wip(),
1345                        )
1346                        .into(),
1347                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1348                        self.fcx.ct_infer(Some(param), inf.span).into()
1349                    }
1350                    _ => unreachable!(),
1351                }
1352            }
1353
1354            fn inferred_kind(
1355                &mut self,
1356                preceding_args: &[ty::GenericArg<'tcx>],
1357                param: &ty::GenericParamDef,
1358                infer_args: bool,
1359            ) -> ty::GenericArg<'tcx> {
1360                let tcx = self.fcx.tcx();
1361                if !infer_args && let Some(default) = param.default_value(tcx) {
1362                    // If we have a default, then it doesn't matter that we're not inferring
1363                    // the type/const arguments: We provide the default where any is missing.
1364                    return default.instantiate(tcx, preceding_args).skip_norm_wip();
1365                }
1366                // If no type/const arguments were provided, we have to infer them.
1367                // This case also occurs as a result of some malformed input, e.g.,
1368                // a lifetime argument being given instead of a type/const parameter.
1369                // Using inference instead of `Error` gives better error messages.
1370                self.fcx.var_for_def(self.span, param)
1371            }
1372        }
1373
1374        let args_raw = implicit_args.unwrap_or_else(|| {
1375            lower_generic_args(
1376                self,
1377                def_id,
1378                &[],
1379                has_self,
1380                self_ty.map(|s| s.raw),
1381                &arg_count,
1382                &mut CtorGenericArgsCtxt {
1383                    fcx: self,
1384                    span,
1385                    generic_segments: &generic_segments,
1386                    infer_args_for_err: &infer_args_for_err,
1387                    segments,
1388                },
1389            )
1390        });
1391
1392        let args_for_user_type = if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
1393            self.transform_args_for_inherent_type_const(def_id, args_raw)
1394        } else {
1395            args_raw
1396        };
1397
1398        // First, store the "user args" for later.
1399        self.write_user_type_annotation_from_args(hir_id, def_id, args_for_user_type, user_self_ty);
1400
1401        // Normalize only after registering type annotations.
1402        let args = self.normalize(span, Unnormalized::new_wip(args_raw));
1403
1404        self.add_required_obligations_for_hir(span, def_id, args, hir_id);
1405
1406        // Instantiate the values for the type parameters into the type of
1407        // the referenced item.
1408        let ty = tcx.type_of(def_id);
1409        assert!(!args.has_escaping_bound_vars());
1410        assert!(!ty.skip_binder().has_escaping_bound_vars());
1411        let ty_instantiated = self.normalize(span, ty.instantiate(tcx, args));
1412
1413        if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1414            // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1415            // is inherent, there is no `Self` parameter; instead, the impl needs
1416            // type parameters, which we can infer by unifying the provided `Self`
1417            // with the instantiated impl type.
1418            // This also occurs for an enum variant on a type alias.
1419            let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).instantiate(tcx, args));
1420            let self_ty = self.normalize(span, Unnormalized::new_wip(self_ty));
1421            match self.at(&self.misc(span), self.param_env).eq(
1422                DefineOpaqueTypes::Yes,
1423                impl_ty,
1424                self_ty,
1425            ) {
1426                Ok(ok) => self.register_infer_ok_obligations(ok),
1427                Err(_) => {
1428                    self.dcx().span_bug(
1429                        span,
1430                        format!(
1431                            "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?",
1432                        ),
1433                    );
1434                }
1435            }
1436        }
1437
1438        debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_instantiated);
1439
1440        let args = if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
1441            self.transform_args_for_inherent_type_const(def_id, args)
1442        } else {
1443            args
1444        };
1445
1446        self.write_args(hir_id, args);
1447
1448        (ty_instantiated, res)
1449    }
1450
1451    /// Add all the obligations that are required, instantiated and normalized appropriately.
1452    pub(crate) fn add_required_obligations_for_hir(
1453        &self,
1454        span: Span,
1455        def_id: DefId,
1456        args: GenericArgsRef<'tcx>,
1457        hir_id: HirId,
1458    ) {
1459        self.add_required_obligations_with_code(span, def_id, args, |idx, span| {
1460            ObligationCauseCode::WhereClauseInExpr(def_id, span, hir_id, idx)
1461        })
1462    }
1463
1464    #[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("add_required_obligations_with_code",
                                    "rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1464u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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;
        }
        {
            let param_env = self.param_env;
            let bounds =
                self.tcx.predicates_of(def_id).instantiate(self.tcx, args);
            for obligation in
                traits::predicates_for_generics(|idx, predicate_span|
                        self.cause(span, code(idx, predicate_span)),
                    |pred| self.normalize(span, pred), param_env, bounds) {
                self.register_predicate(obligation);
            }
        }
    }
}#[instrument(level = "debug", skip(self, code, span, args))]
1465    pub(crate) fn add_required_obligations_with_code(
1466        &self,
1467        span: Span,
1468        def_id: DefId,
1469        args: GenericArgsRef<'tcx>,
1470        code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>,
1471    ) {
1472        let param_env = self.param_env;
1473
1474        let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, args);
1475
1476        for obligation in traits::predicates_for_generics(
1477            |idx, predicate_span| self.cause(span, code(idx, predicate_span)),
1478            |pred| self.normalize(span, pred),
1479            param_env,
1480            bounds,
1481        ) {
1482            self.register_predicate(obligation);
1483        }
1484    }
1485
1486    x;#[instrument(level = "debug", skip(self, sp), ret)]
1487    pub(crate) fn try_structurally_resolve_const(
1488        &self,
1489        sp: Span,
1490        ct: ty::Const<'tcx>,
1491    ) -> ty::Const<'tcx> {
1492        let ct = self.resolve_vars_with_obligations(ct);
1493
1494        if self.next_trait_solver()
1495            && let ty::ConstKind::Alias(..) = ct.kind()
1496        {
1497            // We need to use a separate variable here as otherwise the temporary for
1498            // `self.fulfillment_cx.borrow_mut()` is alive in the `Err` branch, resulting
1499            // in a reentrant borrow, causing an ICE.
1500            let result = self.at(&self.misc(sp), self.param_env).structurally_normalize_const(
1501                Unnormalized::new_wip(ct),
1502                &mut **self.fulfillment_cx.borrow_mut(),
1503            );
1504            match result {
1505                Ok(normalized_ct) => normalized_ct,
1506                Err(errors) => {
1507                    let guar = self.err_ctxt().report_fulfillment_errors(errors);
1508                    return ty::Const::new_error(self.tcx, guar);
1509                }
1510            }
1511        } else if self.tcx.features().generic_const_exprs() {
1512            rustc_trait_selection::traits::evaluate_const(&self.infcx, ct, self.param_env)
1513        } else {
1514            ct
1515        }
1516    }
1517
1518    /// Resolves `ty` by a single level if `ty` is a type variable.
1519    ///
1520    /// When the new solver is enabled, this will also attempt to normalize
1521    /// the type if it's a projection (note that it will not deeply normalize
1522    /// projections within the type, just the outermost layer of the type).
1523    ///
1524    /// If no resolution is possible, then an error is reported.
1525    /// Numeric inference variables may be left unresolved.
1526    pub(crate) fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1527        let ty = self.resolve_vars_with_obligations(ty);
1528
1529        if !ty.is_ty_var() { ty } else { self.type_must_be_known_at_this_point(sp, ty) }
1530    }
1531
1532    #[cold]
1533    pub(crate) fn type_must_be_known_at_this_point(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1534        let guar = self.tainted_by_errors().unwrap_or_else(|| {
1535            self.err_ctxt()
1536                .emit_inference_failure_err(
1537                    self.body_def_id,
1538                    sp,
1539                    ty.into(),
1540                    TypeAnnotationNeeded::E0282,
1541                    true,
1542                )
1543                .emit()
1544        });
1545        let err = Ty::new_error(self.tcx, guar);
1546        self.demand_suptype(sp, err, ty);
1547        err
1548    }
1549
1550    pub(crate) fn structurally_resolve_const(
1551        &self,
1552        sp: Span,
1553        ct: ty::Const<'tcx>,
1554    ) -> ty::Const<'tcx> {
1555        let ct = self.try_structurally_resolve_const(sp, ct);
1556
1557        if !ct.is_ct_infer() {
1558            ct
1559        } else {
1560            let e = self.tainted_by_errors().unwrap_or_else(|| {
1561                self.err_ctxt()
1562                    .emit_inference_failure_err(
1563                        self.body_def_id,
1564                        sp,
1565                        ct.into(),
1566                        TypeAnnotationNeeded::E0282,
1567                        true,
1568                    )
1569                    .emit()
1570            });
1571            // FIXME: Infer `?ct = {const error}`?
1572            ty::Const::new_error(self.tcx, e)
1573        }
1574    }
1575
1576    pub(crate) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1577        &self,
1578        id: HirId,
1579        ctxt: BreakableCtxt<'tcx>,
1580        f: F,
1581    ) -> (BreakableCtxt<'tcx>, R) {
1582        let index;
1583        {
1584            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1585            index = enclosing_breakables.stack.len();
1586            enclosing_breakables.by_id.insert(id, index);
1587            enclosing_breakables.stack.push(ctxt);
1588        }
1589        let result = f();
1590        let ctxt = {
1591            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1592            if true {
    if !(enclosing_breakables.stack.len() == index + 1) {
        ::core::panicking::panic("assertion failed: enclosing_breakables.stack.len() == index + 1")
    };
};debug_assert!(enclosing_breakables.stack.len() == index + 1);
1593            // FIXME(#120456) - is `swap_remove` correct?
1594            enclosing_breakables.by_id.swap_remove(&id).expect("missing breakable context");
1595            enclosing_breakables.stack.pop().expect("missing breakable context")
1596        };
1597        (ctxt, result)
1598    }
1599
1600    /// Instantiate a QueryResponse in a probe context, without a
1601    /// good ObligationCause.
1602    pub(crate) fn probe_instantiate_query_response(
1603        &self,
1604        span: Span,
1605        original_values: &OriginalQueryValues<'tcx>,
1606        query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1607    ) -> InferResult<'tcx, Ty<'tcx>> {
1608        self.instantiate_query_response_and_region_obligations(
1609            &self.misc(span),
1610            self.param_env,
1611            original_values,
1612            query_result,
1613        )
1614    }
1615
1616    /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1617    pub(crate) fn expr_in_place(&self, mut expr_id: HirId) -> bool {
1618        let mut contained_in_place = false;
1619
1620        while let hir::Node::Expr(parent_expr) = self.tcx.parent_hir_node(expr_id) {
1621            match &parent_expr.kind {
1622                hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1623                    if lhs.hir_id == expr_id {
1624                        contained_in_place = true;
1625                        break;
1626                    }
1627                }
1628                _ => (),
1629            }
1630            expr_id = parent_expr.hir_id;
1631        }
1632
1633        contained_in_place
1634    }
1635}