Skip to main content

rustc_hir_analysis/
collect.rs

1//! "Collection" is the process of determining the type and other external
2//! details of each item in Rust. Collection is specifically concerned
3//! with *inter-procedural* things -- for example, for a function
4//! definition, collection will figure out the type and signature of the
5//! function, but it will not visit the *body* of the function in any way,
6//! nor examine type annotations on local variables (that's the job of
7//! type *checking*).
8//!
9//! Collecting is ultimately defined by a bundle of queries that
10//! inquire after various facts about the items in the crate (e.g.,
11//! `type_of`, `generics_of`, `clauses_of`, etc). See the `provide` function
12//! for the full set.
13//!
14//! At present, however, we do run collection across all items in the
15//! crate as a kind of pass. This should eventually be factored away.
16
17use std::cell::Cell;
18use std::{assert_matches, debug_assert_matches, iter};
19
20use rustc_abi::{ExternAbi, Size};
21use rustc_ast::Recovered;
22use rustc_attr_ir::find_attr;
23use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
24use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
25use rustc_errors::{
26    Applicability, Diag, DiagCtxtHandle, Diagnostic, E0228, ErrorGuaranteed, Level, StashKey,
27};
28use rustc_hir::def::DefKind;
29use rustc_hir::def_id::{DefId, LocalDefId};
30use rustc_hir::intravisit::{InferKind, Visitor};
31use rustc_hir::{self as hir, GenericParamKind, HirId, Node, PreciseCapturingArgKind};
32use rustc_infer::infer::{InferCtxt, SolverRegionConstraint, TyCtxtInferExt};
33use rustc_infer::traits::{DynCompatibilityViolation, ObligationCause};
34use rustc_lint_defs::builtin::REPR_C_ENUMS_LARGER_THAN_INT;
35use rustc_middle::query::Providers;
36use rustc_middle::ty::util::{Discr, IntTypeExt};
37use rustc_middle::ty::{
38    self, AdtKind, Const, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
39    fold_regions,
40};
41use rustc_span::def_id::LocalModId;
42use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug, sym};
43use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName;
44use rustc_trait_selection::infer::InferCtxtExt;
45use rustc_trait_selection::traits::{
46    FulfillmentError, ObligationCtxt, hir_ty_lowering_dyn_compatibility_violations,
47};
48use tracing::{debug, instrument};
49use ty::region_constraint::LeafRegionConstraint;
50
51use crate::check::wfcheck::{TestBinderBody, TestBinderExists, TestBinderForall};
52use crate::diagnostics::{self, ElidedLifetimesAreNotAllowedInDelegations};
53use crate::hir_ty_lowering::{HirTyLowerer, InherentAssocCandidate, RegionInferReason};
54
55mod clauses_of;
56pub(crate) mod dump;
57mod generics_of;
58mod item_bounds;
59mod resolve_bound_vars;
60mod type_of;
61
62///////////////////////////////////////////////////////////////////////////
63
64/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
65pub(crate) fn provide(providers: &mut Providers) {
66    resolve_bound_vars::provide(providers);
67    *providers = Providers {
68        type_of: type_of::type_of,
69        type_of_opaque: type_of::type_of_opaque,
70        type_of_opaque_hir_typeck: type_of::type_of_opaque_hir_typeck,
71        type_alias_is_checked: type_of::type_alias_is_checked,
72        item_bounds: item_bounds::item_bounds,
73        explicit_item_bounds: item_bounds::explicit_item_bounds,
74        item_self_bounds: item_bounds::item_self_bounds,
75        explicit_item_self_bounds: item_bounds::explicit_item_self_bounds,
76        item_non_self_bounds: item_bounds::item_non_self_bounds,
77        impl_super_outlives: item_bounds::impl_super_outlives,
78        generics_of: generics_of::generics_of,
79        clauses_of: clauses_of::clauses_of,
80        explicit_clauses_of: clauses_of::explicit_clauses_of,
81        explicit_super_clauses_of: clauses_of::explicit_super_clauses_of,
82        explicit_implied_clauses_of: clauses_of::explicit_implied_clauses_of,
83        explicit_supertraits_containing_assoc_item:
84            clauses_of::explicit_supertraits_containing_assoc_item,
85        trait_explicit_clauses_and_bounds: clauses_of::trait_explicit_clauses_and_bounds,
86        const_conditions: clauses_of::const_conditions,
87        explicit_implied_const_bounds: clauses_of::explicit_implied_const_bounds,
88        type_param_clauses: clauses_of::type_param_clauses,
89        trait_def,
90        adt_def,
91        fn_sig,
92        impl_trait_header,
93        impl_is_fully_generic_for_reflection,
94        coroutine_kind,
95        coroutine_for_closure,
96        opaque_ty_origin,
97        rendered_precise_capturing_args,
98        const_param_default,
99        anon_const_kind,
100        const_of_item,
101        ..*providers
102    };
103}
104
105///////////////////////////////////////////////////////////////////////////
106
107/// Context specific to some particular item. This is what implements [`HirTyLowerer`].
108///
109/// # `ItemCtxt` vs `FnCtxt`
110///
111/// `ItemCtxt` is primarily used to type-check item signatures and lower them
112/// from HIR to their [`ty::Ty`] representation, which is exposed using [`HirTyLowerer`].
113/// It's also used for the bodies of items like structs where the body (the fields)
114/// are just signatures.
115///
116/// This is in contrast to `FnCtxt`, which is used to type-check bodies of
117/// functions, closures, and `const`s -- anywhere that expressions and statements show up.
118///
119/// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
120/// while `FnCtxt` does do inference.
121///
122/// [`InferCtxt`]: rustc_infer::infer::InferCtxt
123///
124/// # Trait predicates
125///
126/// `ItemCtxt` has information about the predicates that are defined
127/// on the trait. Unfortunately, this predicate information is
128/// available in various different forms at various points in the
129/// process. So we can't just store a pointer to e.g., the HIR or the
130/// parsed ty form, we have to be more flexible. To this end, the
131/// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
132/// `probe_ty_param_bounds` requests, drawing the information from
133/// the HIR (`hir::Generics`), recursively.
134pub(crate) struct ItemCtxt<'tcx> {
135    tcx: TyCtxt<'tcx>,
136    item_def_id: LocalDefId,
137    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
138    lowering_delegation_segment: bool,
139}
140
141///////////////////////////////////////////////////////////////////////////
142
143#[derive(#[automatically_derived]
impl ::core::default::Default for HirPlaceholderCollector {
    #[inline]
    fn default() -> Self {
        HirPlaceholderCollector {
            spans: ::core::default::Default::default(),
            may_contain_const_infer: ::core::default::Default::default(),
        }
    }
}Default)]
144pub(crate) struct HirPlaceholderCollector {
145    pub spans: Vec<Span>,
146    // If any of the spans points to a const infer var, then suppress any messages
147    // that may try to turn that const infer into a type parameter.
148    pub may_contain_const_infer: bool,
149}
150
151impl<'v> Visitor<'v> for HirPlaceholderCollector {
152    fn visit_infer(&mut self, _inf_id: HirId, inf_span: Span, kind: InferKind<'v>) -> Self::Result {
153        self.spans.push(inf_span);
154
155        if let InferKind::Const(_) | InferKind::Ambig(_) = kind {
156            self.may_contain_const_infer = true;
157        }
158    }
159}
160
161fn placeholder_type_error_diag<'cx, 'tcx>(
162    cx: &'cx dyn HirTyLowerer<'tcx>,
163    generics: Option<&hir::Generics<'_>>,
164    placeholder_types: Vec<Span>,
165    additional_spans: Vec<Span>,
166    suggest: bool,
167    hir_ty: Option<&hir::Ty<'_>>,
168    kind: &'static str,
169) -> Diag<'cx> {
170    if placeholder_types.is_empty() {
171        return bad_placeholder(cx, additional_spans, kind);
172    }
173
174    let params = generics.map(|g| g.params).unwrap_or_default();
175    let type_name = params.next_type_param_name(None);
176    let mut sugg: Vec<_> =
177        placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
178
179    if let Some(generics) = generics {
180        if let Some(span) = params.iter().find_map(|arg| match arg.name {
181            hir::ParamName::Plain(Ident { name: kw::Underscore, span }) => Some(span),
182            _ => None,
183        }) {
184            // Account for `_` already present in cases like `struct S<_>(_);` and suggest
185            // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
186            sugg.push((span, (*type_name).to_string()));
187        } else if let Some(span) = generics.span_for_param_suggestion() {
188            // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
189            sugg.push((span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", type_name))
    })format!(", {type_name}")));
190        } else {
191            sugg.push((generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", type_name))
    })format!("<{type_name}>")));
192        }
193    }
194
195    let mut err =
196        bad_placeholder(cx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
197
198    // Suggest, but only if it is not a function in const or static
199    if suggest {
200        let mut is_fn = false;
201        let mut is_const_or_static = false;
202
203        if let Some(hir_ty) = hir_ty
204            && let hir::TyKind::FnPtr(_) = hir_ty.kind
205        {
206            is_fn = true;
207
208            // Check if parent is const or static
209            is_const_or_static = #[allow(non_exhaustive_omitted_patterns)] match cx.tcx().parent_hir_node(hir_ty.hir_id)
    {
    Node::Item(&hir::Item {
        kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..), .. }) |
        Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..),
        .. }) |
        Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), ..
        }) => true,
    _ => false,
}matches!(
210                cx.tcx().parent_hir_node(hir_ty.hir_id),
211                Node::Item(&hir::Item {
212                    kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
213                    ..
214                }) | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..), .. })
215                    | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
216            );
217        }
218
219        // if function is wrapped around a const or static,
220        // then don't show the suggestion
221        if !(is_fn && is_const_or_static) {
222            err.multipart_suggestion(
223                "use type parameters instead",
224                sugg,
225                Applicability::HasPlaceholders,
226            );
227        }
228    }
229
230    err
231}
232
233///////////////////////////////////////////////////////////////////////////
234// Utility types and common code for the above passes.
235
236fn bad_placeholder<'cx, 'tcx>(
237    cx: &'cx dyn HirTyLowerer<'tcx>,
238    mut spans: Vec<Span>,
239    kind: &'static str,
240) -> Diag<'cx> {
241    let kind = if kind.ends_with('s') { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}es", kind))
    })format!("{kind}es") } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}s", kind))
    })format!("{kind}s") };
242
243    spans.sort_by_key(|span| span.lo_hi());
244    cx.dcx().create_err(diagnostics::PlaceholderNotAllowedItemSignatures { spans, kind })
245}
246
247impl<'tcx> ItemCtxt<'tcx> {
248    pub(crate) fn new(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
249        ItemCtxt::new_internal(tcx, item_def_id, false)
250    }
251
252    fn new_internal(
253        tcx: TyCtxt<'tcx>,
254        item_def_id: LocalDefId,
255        delegation: bool,
256    ) -> ItemCtxt<'tcx> {
257        ItemCtxt {
258            tcx,
259            item_def_id,
260            tainted_by_errors: Cell::new(None),
261            lowering_delegation_segment: delegation,
262        }
263    }
264
265    pub(crate) fn new_for_delegation(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
266        ItemCtxt::new_internal(tcx, item_def_id, true)
267    }
268
269    pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
270        self.lowerer().lower_ty(hir_ty)
271    }
272
273    pub(crate) fn hir_id(&self) -> hir::HirId {
274        self.tcx.local_def_id_to_hir_id(self.item_def_id)
275    }
276
277    pub(crate) fn node(&self) -> hir::Node<'tcx> {
278        self.tcx.hir_node(self.hir_id())
279    }
280
281    fn check_tainted_by_errors(&self) -> Result<(), ErrorGuaranteed> {
282        match self.tainted_by_errors.get() {
283            Some(err) => Err(err),
284            None => Ok(()),
285        }
286    }
287
288    fn report_placeholder_type_error(
289        &self,
290        placeholder_types: Vec<Span>,
291        infer_replacements: Vec<(Span, String)>,
292    ) -> ErrorGuaranteed {
293        let node = self.tcx.hir_node_by_def_id(self.item_def_id);
294        let generics = node.generics();
295        let kind_id = match node {
296            Node::GenericParam(_) | Node::WherePredicate(_) | Node::Field(_) => {
297                self.tcx.local_parent(self.item_def_id)
298            }
299            _ => self.item_def_id,
300        };
301        let kind = self.tcx.def_descr(kind_id.into());
302        let mut diag = placeholder_type_error_diag(
303            self,
304            generics,
305            placeholder_types,
306            infer_replacements.iter().map(|&(span, _)| span).collect(),
307            false,
308            None,
309            kind,
310        );
311        if !infer_replacements.is_empty() {
312            diag.multipart_suggestion(
313                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try replacing `_` with the type{0} in the corresponding trait method signature",
                if infer_replacements.len() == 1 { "" } else { "s" }))
    })format!(
314                    "try replacing `_` with the type{} in the corresponding trait method \
315                        signature",
316                    rustc_errors::pluralize!(infer_replacements.len()),
317                ),
318                infer_replacements,
319                Applicability::MachineApplicable,
320            );
321        }
322
323        diag.emit_err()
324    }
325
326    {}
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_test_binder_body",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(326u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("item")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("item");
                                                    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(&item)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: TestBinderBody<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let hir::TestBinderBody {
                                span, foralls, exists, constraints, predicates } = item;
                        let foralls =
                            foralls.iter().map(|forall|
                                        self.lower_test_binder_forall(forall)).collect();
                        let exists =
                            exists.iter().map(|exists|
                                        self.lower_test_binder_exists(exists)).collect();
                        let constraints =
                            self.lower_test_binder_constraint(&constraints);
                        let mut clauses = Default::default();
                        for predicate in *predicates {
                            clauses_of::where_predicate_clauses(self, predicate,
                                &mut clauses);
                        }
                        let predicates =
                            clauses.into_iter().map(|(c, span)|
                                        (c.kind(), span)).collect();
                        TestBinderBody {
                            span: *span,
                            foralls,
                            exists,
                            constraints,
                            predicates,
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:326",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(326u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
327    pub(super) fn lower_test_binder_body(
328        &self,
329        item: &hir::TestBinderBody<'tcx>,
330    ) -> TestBinderBody<'tcx> {
331        let hir::TestBinderBody { span, foralls, exists, constraints, predicates } = item;
332        let foralls = foralls.iter().map(|forall| self.lower_test_binder_forall(forall)).collect();
333        let exists = exists.iter().map(|exists| self.lower_test_binder_exists(exists)).collect();
334        let constraints = self.lower_test_binder_constraint(&constraints);
335        let mut clauses = Default::default();
336        for predicate in *predicates {
337            clauses_of::where_predicate_clauses(self, predicate, &mut clauses);
338        }
339        let predicates = clauses.into_iter().map(|(c, span)| (c.kind(), span)).collect();
340        TestBinderBody { span: *span, foralls, exists, constraints, predicates }
341    }
342
343    {}
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_test_binder_forall",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(343u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("forall")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("forall");
                                                    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(&forall)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: TestBinderForall<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let bound_vars = self.tcx.late_bound_vars(forall.hir_id);
                        let value = self.lower_test_binder_body(forall.body);
                        let mut type_outlives = ::alloc::vec::Vec::new();
                        let mut region_outlives = ::alloc::vec::Vec::new();
                        for predicate in forall.generics.predicates {
                            self.lower_test_binder_assumptions(predicate,
                                &mut type_outlives, &mut region_outlives);
                        }
                        let body =
                            crate::check::wfcheck::WithWhereClauses {
                                value,
                                type_outlives,
                                region_outlives,
                            };
                        let binder = ty::Binder::bind_with_vars(body, bound_vars);
                        let assert_on_exit =
                            forall.assert_on_exit.map(|assert_on_exit|
                                    self.lower_test_binder_constraint(assert_on_exit));
                        TestBinderForall {
                            span: forall.span,
                            binder,
                            assert_on_exit,
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:343",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(343u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
344    pub(super) fn lower_test_binder_forall(
345        &self,
346        forall: &hir::TestBinderForall<'tcx>,
347    ) -> TestBinderForall<'tcx> {
348        let bound_vars = self.tcx.late_bound_vars(forall.hir_id);
349        let value = self.lower_test_binder_body(forall.body);
350        let mut type_outlives = vec![];
351        let mut region_outlives = vec![];
352        for predicate in forall.generics.predicates {
353            self.lower_test_binder_assumptions(predicate, &mut type_outlives, &mut region_outlives);
354        }
355        let body =
356            crate::check::wfcheck::WithWhereClauses { value, type_outlives, region_outlives };
357        let binder = ty::Binder::bind_with_vars(body, bound_vars);
358        let assert_on_exit = forall
359            .assert_on_exit
360            .map(|assert_on_exit| self.lower_test_binder_constraint(assert_on_exit));
361        TestBinderForall { span: forall.span, binder, assert_on_exit }
362    }
363
364    {}
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_test_binder_exists",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(364u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("exists")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("exists");
                                                    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(&exists)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: TestBinderExists<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let bound_vars = self.tcx.late_bound_vars(exists.hir_id);
                        let body = self.lower_test_binder_body(exists.body);
                        let binder = ty::Binder::bind_with_vars(body, bound_vars);
                        TestBinderExists { span: exists.span, binder }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:364",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(364u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
365    pub(super) fn lower_test_binder_exists(
366        &self,
367        exists: &hir::TestBinderExists<'tcx>,
368    ) -> TestBinderExists<'tcx> {
369        let bound_vars = self.tcx.late_bound_vars(exists.hir_id);
370        let body = self.lower_test_binder_body(exists.body);
371        let binder = ty::Binder::bind_with_vars(body, bound_vars);
372        TestBinderExists { span: exists.span, binder }
373    }
374
375    fn lower_test_binder_assumptions(
376        &self,
377        predicate: &hir::WherePredicate<'tcx>,
378        type_outlives: &mut Vec<ty::PolyTypeOutlivesClause<'tcx>>,
379        region_outlives: &mut Vec<ty::RegionOutlivesClause<'tcx>>,
380    ) {
381        fn outlives_bounds<'tcx>(
382            dcx: DiagCtxtHandle<'tcx>,
383            bounds: hir::GenericBounds<'tcx>,
384        ) -> impl Iterator<Item = &'tcx hir::Lifetime> {
385            bounds.iter().flat_map(move |bound| match *bound {
386                rustc_hir::GenericBound::Trait(poly_trait_ref) => {
387                    dcx.span_err(
388                        poly_trait_ref.span,
389                        "trait bounds aren't supported in forall where clauses",
390                    );
391                    None
392                }
393                rustc_hir::GenericBound::Outlives(lifetime) => Some(lifetime),
394                rustc_hir::GenericBound::Use(_, span) => {
395                    dcx.span_err(span, "use bounds aren't supported in forall where clauses");
396                    None
397                }
398            })
399        }
400        match predicate.kind {
401            hir::WherePredicateKind::BoundPredicate(p) => {
402                let bound_vars = self.tcx.late_bound_vars(predicate.hir_id);
403                let ty = self.lower_ty(p.bounded_ty);
404                for lifetime in outlives_bounds(self.dcx(), p.bounds) {
405                    let region =
406                        self.lowerer().lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
407                    let binder =
408                        ty::Binder::bind_with_vars(ty::OutlivesClause(ty, region), bound_vars);
409                    type_outlives.push(binder);
410                }
411            }
412            hir::WherePredicateKind::RegionPredicate(p) => {
413                let lhs =
414                    self.lowerer().lower_lifetime(p.lifetime, RegionInferReason::RegionPredicate);
415                for lifetime in outlives_bounds(self.dcx(), p.bounds) {
416                    let rhs =
417                        self.lowerer().lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
418                    region_outlives.push(ty::OutlivesClause(lhs, rhs));
419                }
420            }
421        }
422    }
423
424    fn lower_test_binder_constraint(
425        &self,
426        constraint: &hir::TestBinderConstraint<'tcx>,
427    ) -> SolverRegionConstraint<'tcx> {
428        match constraint {
429            hir::TestBinderConstraint::And { items } => items
430                .into_iter()
431                .map(|item| self.lower_test_binder_constraint(item))
432                .reduce(SolverRegionConstraint::build_and)
433                .unwrap_or(SolverRegionConstraint::new_true()),
434            hir::TestBinderConstraint::Or { items } => items
435                .into_iter()
436                .map(|item| self.lower_test_binder_constraint(item))
437                .reduce(SolverRegionConstraint::build_or)
438                .unwrap_or(SolverRegionConstraint::new_false()),
439            rustc_hir::TestBinderConstraint::Ambiguity { span } => {
440                SolverRegionConstraint::new_ambig(*span)
441            }
442            hir::TestBinderConstraint::Lifetime { lhs, rhs } => {
443                let span = lhs.ident.span.to(rhs.ident.span);
444                let lhs = self.lowerer().lower_lifetime(lhs, RegionInferReason::RegionPredicate);
445                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
446                SolverRegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(
447                    lhs, rhs, span,
448                ))
449            }
450            hir::TestBinderConstraint::PlaceholderOutlives { lhs, rhs } => {
451                let span = lhs.span.to(rhs.ident.span);
452                let lhs = self.lower_ty(lhs);
453                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
454                // note that we cannot check that lhs is a placeholder at this moment, as at this
455                // point it is a bound variable that is not yet instantiated with a placeholder.
456                // instead, we check it when we emit the region constraint.
457                SolverRegionConstraint::new_leaf(LeafRegionConstraint::PlaceholderTyOutlives(
458                    lhs, rhs, span,
459                ))
460            }
461            hir::TestBinderConstraint::AliasOutlives {
462                bound_type_constraint:
463                    hir::TestBinderBoundTypeConstraint { span, hir_id, params: _, lhs, rhs },
464            } => {
465                let bound_vars = self.tcx.late_bound_vars(*hir_id);
466                let &ty::Alias(_, lhs) = self.lower_ty(lhs).kind() else {
467                    self.dcx().span_err(lhs.span, "bound type test binder constraint must be alias (it's a AliasTyOutlivesViaEnv)");
468                    return SolverRegionConstraint::new_true();
469                };
470                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
471                SolverRegionConstraint::new_leaf(LeafRegionConstraint::AliasTyOutlivesViaEnv(
472                    ty::Binder::bind_with_vars((lhs, rhs), bound_vars),
473                    *span,
474                ))
475            }
476        }
477    }
478}
479
480impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
481    fn tcx(&self) -> TyCtxt<'tcx> {
482        self.tcx
483    }
484
485    fn dcx(&self) -> DiagCtxtHandle<'_> {
486        self.tcx.dcx().into_taintable(&self.tainted_by_errors)
487    }
488
489    fn item_def_id(&self) -> LocalDefId {
490        self.item_def_id
491    }
492
493    fn mod_id(&self) -> LocalModId {
494        self.tcx.parent_module_from_def_id(self.item_def_id)
495    }
496
497    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
498        if let RegionInferReason::ObjectLifetimeDefault(sugg_sp) = reason {
499            // FIXME: Account for trailing plus `dyn Trait+`, the need of parens in
500            //        `*const dyn Trait` and `Fn() -> *const dyn Trait`.
501            let guar = self
502                .dcx()
503                .struct_span_err(
504                    span,
505                    "cannot deduce the lifetime bound for this trait object type from context",
506                )
507                .with_code(E0228)
508                .with_span_suggestion_verbose(
509                    sugg_sp,
510                    "please supply an explicit bound",
511                    " + /* 'a */",
512                    Applicability::HasPlaceholders,
513                )
514                .emit_err();
515            ty::Region::new_error(self.tcx(), guar)
516        } else {
517            // If we found elided lifetime during lowering of delegation parent or child
518            // segment then emit an error, as we need a named lifetime for proper signature
519            // inheritance (#156848).
520            if self.lowering_delegation_segment {
521                self.tcx.dcx().emit_err(ElidedLifetimesAreNotAllowedInDelegations { span });
522            }
523
524            // This indicates an illegal lifetime in a non-assoc-trait position
525            ty::Region::new_error_with_message(self.tcx(), span, "inferred lifetime in signature")
526        }
527    }
528
529    fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
530        if !self.tcx.dcx().has_stashed_diagnostic(span, StashKey::ItemNoType) {
531            self.report_placeholder_type_error(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span]))vec![span], ::alloc::vec::Vec::new()vec![]);
532        }
533        Ty::new_error_with_message(self.tcx(), span, "bad placeholder type")
534    }
535
536    fn ct_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
537        self.report_placeholder_type_error(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span]))vec![span], ::alloc::vec::Vec::new()vec![]);
538        ty::Const::new_error_with_message(self.tcx(), span, "bad placeholder constant")
539    }
540
541    fn register_trait_ascription_bounds(
542        &self,
543        _: Vec<(ty::Clause<'tcx>, Span)>,
544        _: HirId,
545        span: Span,
546    ) {
547        self.dcx().span_delayed_bug(span, "trait ascription type not allowed here");
548    }
549
550    fn probe_ty_param_bounds(
551        &self,
552        span: Span,
553        def_id: LocalDefId,
554        assoc_ident: Ident,
555    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
556        self.tcx.at(span).type_param_clauses((self.item_def_id, def_id, assoc_ident))
557    }
558
559    {}
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("select_inherent_assoc_candidates",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(559u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    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("candidates")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("candidates");
                                                    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(&self_ty)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                (Vec<InherentAssocCandidate>,
                                ThinVec<FulfillmentError<'tcx>>) = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if !!self_ty.has_infer() {
                            ::core::panicking::panic("assertion failed: !self_ty.has_infer()")
                        };
                        let self_ty = self.tcx.expand_free_alias_tys(self_ty);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:573",
                                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                                ::tracing_core::__macro_support::Option::Some(573u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                                ::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!("select_inherent_assoc_candidates: self_ty={0:?}",
                                                                            self_ty) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let candidates =
                            candidates.into_iter().filter(|&InherentAssocCandidate {
                                            impl_, .. }|
                                        {
                                            let impl_ty =
                                                self.tcx().type_of(impl_).instantiate_identity().skip_norm_wip();
                                            let impl_ty = self.tcx.expand_free_alias_tys(impl_ty);
                                            {
                                                use ::tracing::__macro_support::Callsite as _;
                                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                    {
                                                        static META: ::tracing::Metadata<'static> =
                                                            {
                                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:582",
                                                                    "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                                                    ::tracing_core::__macro_support::Option::Some(582u32),
                                                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                                                    ::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!("select_inherent_assoc_candidates: impl_ty={0:?}",
                                                                                                impl_ty) as &dyn ::tracing::field::Value))])
                                                        });
                                                } else { ; }
                                            };
                                            ty::DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify_with_depth(self_ty,
                                                impl_ty, usize::MAX)
                                        }).collect();
                        (candidates, ::thin_vec::ThinVec::new())
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:559",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(559u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self, _span), ret)]
560    fn select_inherent_assoc_candidates(
561        &self,
562        _span: Span,
563        self_ty: Ty<'tcx>,
564        candidates: Vec<InherentAssocCandidate>,
565    ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>) {
566        assert!(!self_ty.has_infer());
567
568        // We don't just call the normal normalization routine here as we can't provide the
569        // correct `ParamEnv` and it would be wrong to invoke arbitrary trait solving under
570        // the wrong `ParamEnv`. Expanding free aliases doesn't need a `ParamEnv` so we do
571        // this just to make resolution a little bit smarter.
572        let self_ty = self.tcx.expand_free_alias_tys(self_ty);
573        debug!("select_inherent_assoc_candidates: self_ty={:?}", self_ty);
574
575        let candidates = candidates
576            .into_iter()
577            .filter(|&InherentAssocCandidate { impl_, .. }| {
578                let impl_ty = self.tcx().type_of(impl_).instantiate_identity().skip_norm_wip();
579
580                // See comment on doing this operation for `self_ty`
581                let impl_ty = self.tcx.expand_free_alias_tys(impl_ty);
582                debug!("select_inherent_assoc_candidates: impl_ty={:?}", impl_ty);
583
584                // We treat parameters in the self ty as rigid and parameters in the impl ty as infers
585                // because it allows `impl<T> Foo<T>` to unify with `Foo<u8>::IAT`, while also disallowing
586                // `Foo<T>::IAT` from unifying with `impl Foo<u8>`.
587                //
588                // We don't really care about a depth limit here because we're only working with user-written
589                // types and if they wrote a type that would take hours to walk then that's kind of on them. On
590                // the other hand the default depth limit is relatively low and could realistically be hit by
591                // users in normal cases.
592                //
593                // `DeepRejectCtxt` leads to slightly worse IAT resolution than real type equality in cases
594                // where the `impl_ty` has repeated uses of generic parameters. E.g. `impl<T> Foo<T, T>` would
595                // be considered a valid candidate when resolving `Foo<u8, u16>::IAT`.
596                //
597                // Not replacing escaping bound vars in `self_ty` with placeholders also leads to slightly worse
598                // resolution, but it probably won't come up in practice and it would be backwards compatible
599                // to switch over to doing that.
600                ty::DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify_with_depth(
601                    self_ty,
602                    impl_ty,
603                    usize::MAX,
604                )
605            })
606            .collect();
607
608        (candidates, thin_vec![])
609    }
610
611    fn lower_assoc_item_path(
612        &self,
613        span: Span,
614        item_def_id: DefId,
615        item_segment: &rustc_hir::PathSegment<'_>,
616        poly_trait_ref: ty::PolyTraitRef<'tcx>,
617    ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
618        if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
619            let item_args = self.lowerer().lower_generic_args_of_assoc_item(
620                span,
621                item_def_id,
622                item_segment,
623                trait_ref.args,
624            );
625            Ok((item_def_id, item_args))
626        } else {
627            // There are no late-bound regions; we can just ignore the binder.
628            let (mut mpart_sugg, mut inferred_sugg) = (None, None);
629            let mut bound = String::new();
630
631            match self.node() {
632                hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
633                    let item = self
634                        .tcx
635                        .hir_expect_item(self.tcx.hir_get_parent_item(self.hir_id()).def_id);
636                    match &item.kind {
637                        hir::ItemKind::Enum(_, generics, _)
638                        | hir::ItemKind::Struct(_, generics, _)
639                        | hir::ItemKind::Union(_, generics, _) => {
640                            let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
641                            let (lt_sp, sugg) = match generics.params {
642                                [] => (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", lt_name))
    })format!("<{lt_name}>")),
643                                [bound, ..] => (bound.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", lt_name))
    })format!("{lt_name}, ")),
644                            };
645                            mpart_sugg = Some(diagnostics::AssociatedItemTraitUninferredGenericParamsMultipartSuggestion {
646                                fspan: lt_sp,
647                                first: sugg,
648                                sspan: span.with_hi(item_segment.ident.span.lo()),
649                                second: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::",
                self.tcx.instantiate_bound_regions_uncached(poly_trait_ref,
                    |_|
                        {
                            ty::Region::new_early_param(self.tcx,
                                ty::EarlyParamRegion {
                                    index: 0,
                                    name: Symbol::intern(&lt_name),
                                })
                        })))
    })format!(
650                                    "{}::",
651                                    // Replace the existing lifetimes with a new named lifetime.
652                                    self.tcx.instantiate_bound_regions_uncached(
653                                        poly_trait_ref,
654                                        |_| {
655                                            ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion {
656                                                index: 0,
657                                                name: Symbol::intern(&lt_name),
658                                            })
659                                        }
660                                    ),
661                                ),
662                            });
663                        }
664                        _ => {}
665                    }
666                }
667                hir::Node::Item(hir::Item {
668                    kind:
669                        hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
670                    ..
671                }) => {}
672                hir::Node::Item(_)
673                | hir::Node::ForeignItem(_)
674                | hir::Node::TraitItem(_)
675                | hir::Node::ImplItem(_) => {
676                    inferred_sugg = Some(span.with_hi(item_segment.ident.span.lo()));
677                    bound = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::",
                self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder()))
    })format!(
678                        "{}::",
679                        // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
680                        self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
681                    );
682                }
683                _ => {}
684            }
685
686            Err(self.tcx().dcx().emit_err(
687                diagnostics::AssociatedItemTraitUninferredGenericParams {
688                    span,
689                    inferred_sugg,
690                    bound,
691                    mpart_sugg,
692                    what: self.tcx.def_descr(item_def_id),
693                },
694            ))
695        }
696    }
697
698    fn probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
699        // FIXME(#103640): Should we handle the case where `ty` is a projection?
700        ty.ty_adt_def()
701    }
702
703    fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
704        // There's no place to record types from signatures?
705    }
706
707    fn infcx(&self) -> Option<&InferCtxt<'tcx>> {
708        None
709    }
710
711    fn lower_fn_sig(
712        &self,
713        decl: &hir::FnDecl<'_>,
714        _generics: Option<&hir::Generics<'_>>,
715        hir_id: rustc_hir::HirId,
716        _hir_ty: Option<&hir::Ty<'_>>,
717    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
718        let tcx = self.tcx();
719
720        let mut infer_replacements = ::alloc::vec::Vec::new()vec![];
721
722        let input_tys = decl
723            .inputs
724            .iter()
725            .enumerate()
726            .map(|(i, a)| {
727                if let hir::TyKind::Infer(()) = a.kind
728                    && let Some(suggested_ty) =
729                        self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
730                {
731                    infer_replacements.push((a.span, suggested_ty.to_string()));
732                    return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string());
733                }
734
735                self.lowerer().lower_ty(a)
736            })
737            .collect();
738
739        let output_ty = match decl.output {
740            hir::FnRetTy::Return(output) => {
741                if let hir::TyKind::Infer(()) = output.kind
742                    && let Some(suggested_ty) =
743                        self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
744                {
745                    infer_replacements.push((output.span, suggested_ty.to_string()));
746                    Ty::new_error_with_message(tcx, output.span, suggested_ty.to_string())
747                } else {
748                    self.lower_ty(output)
749                }
750            }
751            hir::FnRetTy::DefaultReturn(..) => tcx.types.unit,
752        };
753
754        if !infer_replacements.is_empty() {
755            self.report_placeholder_type_error(::alloc::vec::Vec::new()vec![], infer_replacements);
756        }
757        (input_tys, output_ty)
758    }
759
760    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
761        hir_ty_lowering_dyn_compatibility_violations(self.tcx, trait_def_id)
762    }
763}
764
765/// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
766fn get_new_lifetime_name<'tcx>(
767    tcx: TyCtxt<'tcx>,
768    poly_trait_ref: ty::PolyTraitRef<'tcx>,
769    generics: &hir::Generics<'tcx>,
770) -> String {
771    let existing_lifetimes = tcx
772        .collect_referenced_late_bound_regions(poly_trait_ref)
773        .into_iter()
774        .filter_map(|lt| lt.get_name(tcx).map(|name| name.as_str().to_string()))
775        .chain(generics.params.iter().filter_map(|param| {
776            if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
777                Some(param.name.ident().as_str().to_string())
778            } else {
779                None
780            }
781        }))
782        .collect::<FxHashSet<String>>();
783
784    let a_to_z_repeat_n = |n| {
785        (b'a'..=b'z').map(move |c| {
786            let mut s = '\''.to_string();
787            s.extend(std::iter::repeat_n(char::from(c), n));
788            s
789        })
790    };
791
792    // If all single char lifetime names are present, we wrap around and double the chars.
793    (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
794}
795
796pub(super) fn check_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
797    tcx.ensure_ok().generics_of(def_id);
798    tcx.ensure_ok().type_of(def_id);
799    tcx.ensure_ok().clauses_of(def_id);
800}
801
802pub(super) fn check_enum_variant_types(tcx: TyCtxt<'_>, def_id: LocalDefId) {
803    struct ReprCIssue {
804        msg: &'static str,
805    }
806
807    impl<'a> Diagnostic<'a> for ReprCIssue {
808        fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
809            let Self { msg } = self;
810            Diag::new(dcx, level, msg)
811                .with_note("`repr(C)` enums with big discriminants are non-portable, and their size in Rust might not match their size in C")
812                .with_help("use `repr($int_ty)` instead to explicitly set the size of this enum")
813        }
814    }
815
816    let def = tcx.adt_def(def_id);
817    let repr_type = def.repr().discr_type();
818    let initial = repr_type.initial_discriminant(tcx);
819    let mut prev_discr = None::<Discr<'_>>;
820    // Some of the logic below relies on `i128` being able to hold all c_int and c_uint values.
821    if !(tcx.sess.target.c_int_width < 128) {
    ::core::panicking::panic("assertion failed: tcx.sess.target.c_int_width < 128")
};assert!(tcx.sess.target.c_int_width < 128);
822    let mut min_discr = i128::MAX;
823    let mut max_discr = i128::MIN;
824
825    // fill the discriminant values and field types
826    for variant in def.variants() {
827        let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
828        let cur_discr = if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
829            def.eval_explicit_discr(tcx, const_def_id).ok()
830        } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
831            Some(discr)
832        } else {
833            let span = tcx.def_span(variant.def_id);
834            tcx.dcx().emit_err(diagnostics::EnumDiscriminantOverflowed {
835                span,
836                discr: prev_discr.unwrap().to_string(),
837                item_name: tcx.item_ident(variant.def_id),
838                wrapped_discr: wrapped_discr.to_string(),
839            });
840            None
841        }
842        .unwrap_or(wrapped_discr);
843
844        if def.repr().c() {
845            let c_int = Size::from_bits(tcx.sess.target.c_int_width);
846            let c_uint_max = i128::try_from(c_int.unsigned_int_max()).unwrap();
847            // c_int is a signed type, so get a proper signed version of the discriminant
848            let discr_size = cur_discr.ty.int_size_and_signed(tcx).0;
849            let discr_val = discr_size.sign_extend(cur_discr.val);
850            min_discr = min_discr.min(discr_val);
851            max_discr = max_discr.max(discr_val);
852
853            // The discriminant range must either fit into c_int or c_uint.
854            if !(min_discr >= c_int.signed_int_min() && max_discr <= c_int.signed_int_max())
855                && !(min_discr >= 0 && max_discr <= c_uint_max)
856            {
857                let span = tcx.def_span(variant.def_id);
858                let msg = if discr_val < c_int.signed_int_min() || discr_val > c_uint_max {
859                    "`repr(C)` enum discriminant does not fit into C `int` nor into C `unsigned int`"
860                } else if discr_val < 0 {
861                    "`repr(C)` enum discriminant does not fit into C `unsigned int`, and a previous discriminant does not fit into C `int`"
862                } else {
863                    "`repr(C)` enum discriminant does not fit into C `int`, and a previous discriminant does not fit into C `unsigned int`"
864                };
865                tcx.emit_node_span_lint(
866                    REPR_C_ENUMS_LARGER_THAN_INT,
867                    tcx.local_def_id_to_hir_id(def_id),
868                    span,
869                    ReprCIssue { msg },
870                );
871            }
872        }
873
874        prev_discr = Some(cur_discr);
875
876        for f in &variant.fields {
877            tcx.ensure_ok().generics_of(f.did);
878            tcx.ensure_ok().type_of(f.did);
879            tcx.ensure_ok().clauses_of(f.did);
880        }
881
882        // Lower the ctor, if any. This also registers the variant as an item.
883        if let Some(ctor_def_id) = variant.ctor_def_id() {
884            check_ctor(tcx, ctor_def_id.expect_local());
885        }
886    }
887}
888
889#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NestedSpan { }
#[automatically_derived]
impl ::core::clone::Clone for NestedSpan {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for NestedSpan { }Copy)]
890struct NestedSpan {
891    span: Span,
892    nested_field_span: Span,
893}
894
895impl NestedSpan {
896    fn to_field_already_declared_nested_help(&self) -> diagnostics::FieldAlreadyDeclaredNestedHelp {
897        diagnostics::FieldAlreadyDeclaredNestedHelp { span: self.span }
898    }
899}
900
901#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FieldDeclSpan { }
#[automatically_derived]
impl ::core::clone::Clone for FieldDeclSpan {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<NestedSpan>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FieldDeclSpan { }Copy)]
902enum FieldDeclSpan {
903    NotNested(Span),
904    Nested(NestedSpan),
905}
906
907impl From<Span> for FieldDeclSpan {
908    fn from(span: Span) -> Self {
909        Self::NotNested(span)
910    }
911}
912
913impl From<NestedSpan> for FieldDeclSpan {
914    fn from(span: NestedSpan) -> Self {
915        Self::Nested(span)
916    }
917}
918
919struct FieldUniquenessCheckContext<'tcx> {
920    tcx: TyCtxt<'tcx>,
921    seen_fields: FxIndexMap<Ident, FieldDeclSpan>,
922}
923
924impl<'tcx> FieldUniquenessCheckContext<'tcx> {
925    fn new(tcx: TyCtxt<'tcx>) -> Self {
926        Self { tcx, seen_fields: FxIndexMap::default() }
927    }
928
929    /// Check if a given field `ident` declared at `field_decl` has been declared elsewhere before.
930    fn check_field_decl(&mut self, field_name: Ident, field_decl: FieldDeclSpan) {
931        use FieldDeclSpan::*;
932        let field_name = field_name.normalize_to_macros_2_0();
933        match (field_decl, self.seen_fields.get(&field_name).copied()) {
934            (NotNested(span), Some(NotNested(prev_span))) => {
935                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::NotNested {
936                    field_name,
937                    span,
938                    prev_span,
939                });
940            }
941            (NotNested(span), Some(Nested(prev))) => {
942                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::PreviousNested {
943                    field_name,
944                    span,
945                    prev_span: prev.span,
946                    prev_nested_field_span: prev.nested_field_span,
947                    prev_help: prev.to_field_already_declared_nested_help(),
948                });
949            }
950            (
951                Nested(current @ NestedSpan { span, nested_field_span, .. }),
952                Some(NotNested(prev_span)),
953            ) => {
954                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::CurrentNested {
955                    field_name,
956                    span,
957                    nested_field_span,
958                    help: current.to_field_already_declared_nested_help(),
959                    prev_span,
960                });
961            }
962            (Nested(current @ NestedSpan { span, nested_field_span }), Some(Nested(prev))) => {
963                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::BothNested {
964                    field_name,
965                    span,
966                    nested_field_span,
967                    help: current.to_field_already_declared_nested_help(),
968                    prev_span: prev.span,
969                    prev_nested_field_span: prev.nested_field_span,
970                    prev_help: prev.to_field_already_declared_nested_help(),
971                });
972            }
973            (field_decl, None) => {
974                self.seen_fields.insert(field_name, field_decl);
975            }
976        }
977    }
978}
979
980fn lower_variant<'tcx>(
981    tcx: TyCtxt<'tcx>,
982    variant_did: Option<LocalDefId>,
983    ident: Ident,
984    discr: ty::VariantDiscr,
985    def: &hir::VariantData<'tcx>,
986    adt_kind: ty::AdtKind,
987    parent_did: LocalDefId,
988) -> ty::VariantDef {
989    let mut field_uniqueness_check_ctx = FieldUniquenessCheckContext::new(tcx);
990    let fields = def
991        .fields()
992        .iter()
993        .inspect(|field| {
994            field_uniqueness_check_ctx.check_field_decl(field.ident, field.span.into());
995        })
996        .map(|f| ty::FieldDef {
997            did: f.def_id.to_def_id(),
998            name: f.ident.name,
999            vis: tcx.visibility(f.def_id),
1000            mut_restriction: match f.mut_restriction.kind {
1001                hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1002                hir::RestrictionKind::Restricted(path) => {
1003                    ty::RestrictionKind::Restricted(path.res, f.mut_restriction.span)
1004                }
1005            },
1006            safety: f.safety,
1007            value: f.default.map(|v| v.def_id.to_def_id()),
1008        })
1009        .collect();
1010    let recovered = match def {
1011        hir::VariantData::Struct { recovered: Recovered::Yes(guar), .. } => Some(*guar),
1012        _ => None,
1013    };
1014    ty::VariantDef::new(
1015        ident.name,
1016        variant_did.map(LocalDefId::to_def_id),
1017        def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
1018        discr,
1019        fields,
1020        parent_did.to_def_id(),
1021        recovered,
1022        adt_kind == AdtKind::Struct && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(parent_did, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(NonExhaustive(..)) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, parent_did, NonExhaustive(..))
1023            || variant_did
1024                .is_some_and(|variant_did| {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(variant_did, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(NonExhaustive(..)) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, variant_did, NonExhaustive(..))),
1025    )
1026}
1027
1028fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
1029    use rustc_hir::*;
1030
1031    let Node::Item(item) = tcx.hir_node_by_def_id(def_id) else {
1032        ::rustc_span::macros::bug_impl(None,
    format_args!("expected ADT to be an item"), Location::caller());bug!("expected ADT to be an item");
1033    };
1034
1035    let repr = tcx.repr_options_of_def(def_id);
1036    let (kind, variants) = match &item.kind {
1037        ItemKind::Enum(_, _, def) => {
1038            let mut distance_from_explicit = 0;
1039            let variants = def
1040                .variants
1041                .iter()
1042                .map(|v| {
1043                    let discr = if let Some(e) = &v.disr_expr {
1044                        distance_from_explicit = 0;
1045                        ty::VariantDiscr::Explicit(e.def_id.to_def_id())
1046                    } else {
1047                        ty::VariantDiscr::Relative(distance_from_explicit)
1048                    };
1049                    distance_from_explicit += 1;
1050
1051                    lower_variant(
1052                        tcx,
1053                        Some(v.def_id),
1054                        v.ident,
1055                        discr,
1056                        &v.data,
1057                        AdtKind::Enum,
1058                        def_id,
1059                    )
1060                })
1061                .collect();
1062
1063            (AdtKind::Enum, variants)
1064        }
1065        ItemKind::Struct(ident, _, def) | ItemKind::Union(ident, _, def) => {
1066            let adt_kind = match item.kind {
1067                ItemKind::Struct(..) => AdtKind::Struct,
1068                _ => AdtKind::Union,
1069            };
1070            let variants = std::iter::once(lower_variant(
1071                tcx,
1072                None,
1073                *ident,
1074                ty::VariantDiscr::Relative(0),
1075                def,
1076                adt_kind,
1077                def_id,
1078            ))
1079            .collect();
1080
1081            (adt_kind, variants)
1082        }
1083        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} is not an ADT", item.owner_id.def_id),
    Location::caller())bug!("{:?} is not an ADT", item.owner_id.def_id),
1084    };
1085    tcx.mk_adt_def(def_id.to_def_id(), kind, variants, repr)
1086}
1087
1088fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
1089    let item = tcx.hir_expect_item(def_id);
1090
1091    let (constness, is_alias, is_auto, safety, impl_restriction) = match item.kind {
1092        hir::ItemKind::Trait { impl_restriction, constness, is_auto, safety, .. } => (
1093            constness,
1094            false,
1095            is_auto == hir::IsAuto::Yes,
1096            safety,
1097            match impl_restriction.kind {
1098                hir::RestrictionKind::Restricted(path) => {
1099                    ty::RestrictionKind::Restricted(path.res, impl_restriction.span)
1100                }
1101                hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1102            },
1103        ),
1104        hir::ItemKind::TraitAlias(constness, ..) => {
1105            (constness, true, false, hir::Safety::Safe, ty::RestrictionKind::Unrestricted)
1106        }
1107        _ => ::rustc_span::macros::bug_impl(Some(item.span),
    format_args!("trait_def_of_item invoked on non-trait"),
    Location::caller())span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1108    };
1109
1110    // we do a bunch of find_attr calls here, probably faster to get them from the tcx just once.
1111    #[allow(deprecated)]
1112    let attrs = tcx.get_all_attrs(def_id);
1113
1114    let paren_sugar = {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcParenSugar) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcParenSugar);
1115
1116    // Only regular traits can be marker.
1117    let is_marker = !is_alias && {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Marker) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, Marker);
1118
1119    let rustc_coinductive = {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcCoinductive) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcCoinductive);
1120    let is_fundamental = {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Fundamental) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, Fundamental);
1121
1122    let [skip_array_during_method_dispatch, skip_boxed_slice_during_method_dispatch] = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(RustcSkipDuringMethodDispatch {
                    array, boxed_slice }) => {
                    break 'done Some([*array, *boxed_slice]);
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(
1123        attrs,
1124        RustcSkipDuringMethodDispatch { array, boxed_slice } => [*array, *boxed_slice]
1125    )
1126    .unwrap_or([false; 2]);
1127
1128    let specialization_kind = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcAllowLifetimeDependentSpecialization)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcAllowLifetimeDependentSpecialization) {
1129        ty::trait_def::TraitSpecializationKind::Marker
1130    } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcSpecializationTrait)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcSpecializationTrait) {
1131        ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1132    } else {
1133        ty::trait_def::TraitSpecializationKind::None
1134    };
1135
1136    let must_implement_one_of = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(RustcMustImplementOneOf {
                    fn_names, .. }) => {
                    break 'done
                        Some(fn_names.iter().cloned().collect::<Box<[_]>>());
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(
1137        attrs,
1138        RustcMustImplementOneOf { fn_names, .. } =>
1139            fn_names
1140                .iter()
1141                .cloned()
1142                .collect::<Box<[_]>>()
1143    );
1144
1145    let deny_explicit_impl = {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDenyExplicitImpl) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcDenyExplicitImpl);
1146    let force_dyn_incompatible = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(RustcDynIncompatibleTrait(span))
                    => {
                    break 'done Some(*span);
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcDynIncompatibleTrait(span) => *span);
1147
1148    ty::TraitDef {
1149        def_id: def_id.to_def_id(),
1150        impl_restriction,
1151        safety,
1152        constness,
1153        paren_sugar,
1154        has_auto_impl: is_auto,
1155        is_marker,
1156        is_coinductive: rustc_coinductive || is_auto,
1157        is_fundamental,
1158        skip_array_during_method_dispatch,
1159        skip_boxed_slice_during_method_dispatch,
1160        specialization_kind,
1161        must_implement_one_of,
1162        force_dyn_incompatible,
1163        deny_explicit_impl,
1164    }
1165}
1166
1167{}
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("fn_sig",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(1167u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::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();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                ty::EarlyBinder<'_, ty::PolyFnSig<'_>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        use rustc_hir::Node::*;
                        use rustc_hir::*;
                        let hir_id = tcx.local_def_id_to_hir_id(def_id);
                        let icx = ItemCtxt::new(tcx, def_id);
                        let output =
                            match tcx.hir_node(hir_id) {
                                TraitItem(hir::TraitItem {
                                    kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
                                    generics, .. }) |
                                    Item(hir::Item { kind: ItemKind::Fn { sig, generics, .. },
                                    .. }) => {
                                    lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics,
                                        def_id)
                                }
                                ImplItem(hir::ImplItem {
                                    kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
                                    if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
                                                tcx.parent_hir_node(hir_id) && i.of_trait.is_some() {
                                        icx.lowerer().lower_fn_ty(hir_id, sig.header.safety(),
                                            sig.header.abi, sig.decl, Some(generics), None)
                                    } else {
                                        lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics,
                                            def_id)
                                    }
                                }
                                TraitItem(hir::TraitItem {
                                    kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
                                    generics, .. }) =>
                                    icx.lowerer().lower_fn_ty(hir_id, header.safety(),
                                        header.abi, decl, Some(generics), None),
                                ForeignItem(&hir::ForeignItem {
                                    kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
                                    let abi = tcx.hir_get_foreign_abi(hir_id);
                                    compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi,
                                        sig.header.safety())
                                }
                                Ctor(data) => {
                                    {
                                        match data.ctor() {
                                            Some(_) => {}
                                            ref left_val => {
                                                ::core::panicking::assert_matches_failed(left_val,
                                                    "Some(_)", ::core::option::Option::None);
                                            }
                                        }
                                    };
                                    let adt_def_id =
                                        tcx.hir_get_parent_item(hir_id).def_id.to_def_id();
                                    let ty =
                                        tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
                                    let inputs =
                                        data.fields().iter().map(|f|
                                                tcx.type_of(f.def_id).instantiate_identity().skip_norm_wip());
                                    ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(inputs, ty,
                                            hir::Safety::Safe))
                                }
                                Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. })
                                    => {
                                    ::rustc_span::macros::bug_impl(None,
                                        format_args!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`"),
                                        Location::caller());
                                }
                                x => {
                                    ::rustc_span::macros::bug_impl(None,
                                        format_args!("unexpected sort of node in fn_sig(): {0:?}",
                                            x), Location::caller());
                                }
                            };
                        ty::EarlyBinder::bind(tcx, output)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:1167",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(1167u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
1168fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFnSig<'_>> {
1169    use rustc_hir::Node::*;
1170    use rustc_hir::*;
1171
1172    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1173
1174    let icx = ItemCtxt::new(tcx, def_id);
1175
1176    let output = match tcx.hir_node(hir_id) {
1177        TraitItem(hir::TraitItem {
1178            kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1179            generics,
1180            ..
1181        })
1182        | Item(hir::Item { kind: ItemKind::Fn { sig, generics, .. }, .. }) => {
1183            lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1184        }
1185
1186        ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1187            // Do not try to infer the return type for a impl method coming from a trait
1188            if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) = tcx.parent_hir_node(hir_id)
1189                && i.of_trait.is_some()
1190            {
1191                icx.lowerer().lower_fn_ty(
1192                    hir_id,
1193                    sig.header.safety(),
1194                    sig.header.abi,
1195                    sig.decl,
1196                    Some(generics),
1197                    None,
1198                )
1199            } else {
1200                lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1201            }
1202        }
1203
1204        TraitItem(hir::TraitItem {
1205            kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1206            generics,
1207            ..
1208        }) => icx.lowerer().lower_fn_ty(
1209            hir_id,
1210            header.safety(),
1211            header.abi,
1212            decl,
1213            Some(generics),
1214            None,
1215        ),
1216
1217        ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
1218            let abi = tcx.hir_get_foreign_abi(hir_id);
1219            compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety())
1220        }
1221
1222        Ctor(data) => {
1223            assert_matches!(data.ctor(), Some(_));
1224            let adt_def_id = tcx.hir_get_parent_item(hir_id).def_id.to_def_id();
1225            let ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
1226            let inputs = data
1227                .fields()
1228                .iter()
1229                .map(|f| tcx.type_of(f.def_id).instantiate_identity().skip_norm_wip());
1230            ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(inputs, ty, hir::Safety::Safe))
1231        }
1232
1233        Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1234            // Closure signatures are not like other function
1235            // signatures and cannot be accessed through `fn_sig`. For
1236            // example, a closure signature excludes the `self`
1237            // argument. In any case they are embedded within the
1238            // closure type as part of the `ClosureArgs`.
1239            //
1240            // To get the signature of a closure, you should use the
1241            // `sig` method on the `ClosureArgs`:
1242            //
1243            //    args.as_closure().sig(def_id, tcx)
1244            bug!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`",);
1245        }
1246
1247        x => {
1248            bug!("unexpected sort of node in fn_sig(): {:?}", x);
1249        }
1250    };
1251    ty::EarlyBinder::bind(tcx, output)
1252}
1253
1254fn lower_fn_sig_recovering_infer_ret_ty<'tcx>(
1255    icx: &ItemCtxt<'tcx>,
1256    sig: &'tcx hir::FnSig<'tcx>,
1257    generics: &'tcx hir::Generics<'tcx>,
1258    def_id: LocalDefId,
1259) -> ty::PolyFnSig<'tcx> {
1260    if let Some(infer_ret_ty) = sig.decl.output.is_suggestable_infer_ty() {
1261        return recover_infer_ret_ty(icx, infer_ret_ty, generics, def_id);
1262    }
1263
1264    icx.lowerer().lower_fn_ty(
1265        icx.tcx().local_def_id_to_hir_id(def_id),
1266        sig.header.safety(),
1267        sig.header.abi,
1268        sig.decl,
1269        Some(generics),
1270        None,
1271    )
1272}
1273
1274/// Convert `ReLateParam`s in `value` back into `ReBound`s and bind it with `bound_vars`.
1275fn late_param_regions_to_bound<'tcx, T>(
1276    tcx: TyCtxt<'tcx>,
1277    scope: DefId,
1278    bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
1279    value: T,
1280) -> ty::Binder<'tcx, T>
1281where
1282    T: ty::TypeFoldable<TyCtxt<'tcx>>,
1283{
1284    let value = fold_regions(tcx, value, |r, debruijn| match r.kind() {
1285        ty::ReLateParam(lp) => {
1286            // Should be in scope, otherwise inconsistency happens somewhere.
1287            {
    match (&lp.scope, &scope) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(lp.scope, scope);
1288
1289            let br = match lp.kind {
1290                // These variants preserve the bound var index.
1291                kind @ (ty::LateParamRegionKind::Anon(idx)
1292                | ty::LateParamRegionKind::NamedAnon(idx, _)) => {
1293                    let idx = idx as usize;
1294                    let var = ty::BoundVar::from_usize(idx);
1295
1296                    let Some(ty::BoundVariableKind::Region(kind)) = bound_vars.get(idx).copied()
1297                    else {
1298                        ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected late-bound region {0:?} for bound vars {1:?}",
        kind, bound_vars), Location::caller());bug!("unexpected late-bound region {kind:?} for bound vars {bound_vars:?}");
1299                    };
1300
1301                    ty::BoundRegion { var, kind }
1302                }
1303
1304                // For named regions, look up the corresponding bound var.
1305                ty::LateParamRegionKind::Named(def_id) => bound_vars
1306                    .iter()
1307                    .enumerate()
1308                    .find_map(|(idx, bv)| match bv {
1309                        ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::Named(did))
1310                            if did == def_id =>
1311                        {
1312                            Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1313                        }
1314                        _ => None,
1315                    })
1316                    .unwrap(),
1317
1318                ty::LateParamRegionKind::ClosureEnv => bound_vars
1319                    .iter()
1320                    .enumerate()
1321                    .find_map(|(idx, bv)| match bv {
1322                        ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::ClosureEnv) => {
1323                            Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1324                        }
1325                        _ => None,
1326                    })
1327                    .unwrap(),
1328            };
1329
1330            ty::Region::new_bound(tcx, debruijn, br)
1331        }
1332        _ => r,
1333    });
1334
1335    ty::Binder::bind_with_vars(value, bound_vars)
1336}
1337
1338fn recover_infer_ret_ty<'tcx>(
1339    icx: &ItemCtxt<'tcx>,
1340    infer_ret_ty: &'tcx hir::Ty<'tcx>,
1341    generics: &'tcx hir::Generics<'tcx>,
1342    def_id: LocalDefId,
1343) -> ty::PolyFnSig<'tcx> {
1344    let tcx = icx.tcx;
1345    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1346
1347    let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1348
1349    // Typeck doesn't expect erased regions to be returned from `type_of`.
1350    // This is a heuristic approach. If the scope has region parameters,
1351    // we should change fn_sig's lifetime from `ReErased` to `ReError`,
1352    // otherwise to `ReStatic`.
1353    let has_region_params = generics.params.iter().any(|param| match param.kind {
1354        GenericParamKind::Lifetime { .. } => true,
1355        _ => false,
1356    });
1357    let fn_sig = fold_regions(tcx, fn_sig, |r, _| match r.kind() {
1358        ty::ReErased => {
1359            if has_region_params {
1360                ty::Region::new_error_with_message(
1361                    tcx,
1362                    DUMMY_SP,
1363                    "erased region is not allowed here in return type",
1364                )
1365            } else {
1366                tcx.lifetimes.re_static
1367            }
1368        }
1369        _ => r,
1370    });
1371
1372    let mut visitor = HirPlaceholderCollector::default();
1373    visitor.visit_ty_unambig(infer_ret_ty);
1374
1375    let mut diag = bad_placeholder(icx.lowerer(), visitor.spans, "return type");
1376    let ret_ty = fn_sig.output();
1377
1378    // Don't leak types into signatures unless they're nameable!
1379    // For example, if a function returns itself, we don't want that
1380    // recursive function definition to leak out into the fn sig.
1381    let mut recovered_ret_ty = None;
1382    if let Some(suggestable_ret_ty) = ret_ty.make_suggestable(tcx, false, None) {
1383        diag.span_suggestion_verbose(
1384            infer_ret_ty.span,
1385            "replace with the correct return type",
1386            suggestable_ret_ty,
1387            Applicability::MachineApplicable,
1388        );
1389        recovered_ret_ty = Some(suggestable_ret_ty);
1390    } else if let Some(sugg) = suggest_impl_trait(
1391        &tcx.infer_ctxt().build(TypingMode::non_body_analysis()),
1392        tcx.param_env(def_id),
1393        ret_ty,
1394    ) {
1395        diag.span_suggestion_verbose(
1396            infer_ret_ty.span,
1397            "replace with an appropriate return type",
1398            sugg,
1399            Applicability::MachineApplicable,
1400        );
1401    } else if ret_ty.is_closure() {
1402        diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1403    }
1404
1405    // Also note how `Fn` traits work just in case!
1406    if ret_ty.is_closure() {
1407        diag.note(
1408            "for more information on `Fn` traits and closure types, see \
1409                     https://doc.rust-lang.org/book/ch13-01-closures.html",
1410        );
1411    }
1412    let guar = diag.emit_err();
1413
1414    // If we return a dummy binder here, we can ICE later in borrowck when it encounters
1415    // `ReLateParam` regions (e.g. in a local type annotation) which weren't registered via the
1416    // signature binder. See #135845.
1417    let bound_vars = tcx.late_bound_vars(hir_id);
1418    let scope = def_id.to_def_id();
1419
1420    let fn_sig = tcx.mk_fn_sig(
1421        fn_sig.inputs().iter().copied(),
1422        recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)),
1423        fn_sig.fn_sig_kind,
1424    );
1425
1426    late_param_regions_to_bound(tcx, scope, bound_vars, fn_sig)
1427}
1428
1429pub fn suggest_impl_trait<'tcx>(
1430    infcx: &InferCtxt<'tcx>,
1431    param_env: ty::ParamEnv<'tcx>,
1432    ret_ty: Ty<'tcx>,
1433) -> Option<String> {
1434    let format_as_assoc: fn(_, _, _, _, _) -> _ =
1435        |tcx: TyCtxt<'tcx>,
1436         _: ty::GenericArgsRef<'tcx>,
1437         trait_def_id: DefId,
1438         assoc_item_def_id: DefId,
1439         item_ty: Ty<'tcx>| {
1440            let trait_name = tcx.item_name(trait_def_id);
1441            let assoc_name = tcx.item_name(assoc_item_def_id);
1442            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl {0}<{1} = {2}>", trait_name,
                assoc_name, item_ty))
    })format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1443        };
1444    let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1445        |tcx: TyCtxt<'tcx>,
1446         args: ty::GenericArgsRef<'tcx>,
1447         trait_def_id: DefId,
1448         _: DefId,
1449         item_ty: Ty<'tcx>| {
1450            let trait_name = tcx.item_name(trait_def_id);
1451            let args_tuple = args.type_at(1);
1452            let ty::Tuple(types) = *args_tuple.kind() else {
1453                return None;
1454            };
1455            let types = types.make_suggestable(tcx, false, None)?;
1456            let maybe_ret =
1457                if item_ty.is_unit() { String::new() } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}", item_ty))
    })format!(" -> {item_ty}") };
1458            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl {1}({0}){2}",
                types.iter().map(|ty|
                                ty.to_string()).collect::<Vec<_>>().join(", "), trait_name,
                maybe_ret))
    })format!(
1459                "impl {trait_name}({}){maybe_ret}",
1460                types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1461            ))
1462        };
1463
1464    for (trait_def_id, assoc_item_def_id, formatter) in [
1465        (
1466            infcx.tcx.get_diagnostic_item(sym::Iterator),
1467            infcx.tcx.get_diagnostic_item(sym::IteratorItem),
1468            format_as_assoc,
1469        ),
1470        (
1471            infcx.tcx.lang_items().future_trait(),
1472            infcx.tcx.lang_items().future_output(),
1473            format_as_assoc,
1474        ),
1475        (
1476            infcx.tcx.lang_items().async_fn_trait(),
1477            infcx.tcx.lang_items().async_fn_once_output(),
1478            format_as_parenthesized,
1479        ),
1480        (
1481            infcx.tcx.lang_items().async_fn_mut_trait(),
1482            infcx.tcx.lang_items().async_fn_once_output(),
1483            format_as_parenthesized,
1484        ),
1485        (
1486            infcx.tcx.lang_items().async_fn_once_trait(),
1487            infcx.tcx.lang_items().async_fn_once_output(),
1488            format_as_parenthesized,
1489        ),
1490        (
1491            infcx.tcx.lang_items().fn_trait(),
1492            infcx.tcx.lang_items().fn_once_output(),
1493            format_as_parenthesized,
1494        ),
1495        (
1496            infcx.tcx.lang_items().fn_mut_trait(),
1497            infcx.tcx.lang_items().fn_once_output(),
1498            format_as_parenthesized,
1499        ),
1500        (
1501            infcx.tcx.lang_items().fn_once_trait(),
1502            infcx.tcx.lang_items().fn_once_output(),
1503            format_as_parenthesized,
1504        ),
1505    ] {
1506        let Some(trait_def_id) = trait_def_id else {
1507            continue;
1508        };
1509        let Some(assoc_item_def_id) = assoc_item_def_id else {
1510            continue;
1511        };
1512        if infcx.tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1513            continue;
1514        }
1515        let sugg = infcx.probe(|_| {
1516            let args = ty::GenericArgs::for_item(infcx.tcx, trait_def_id, |param, _| {
1517                if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(DUMMY_SP, param) }
1518            });
1519            if !infcx
1520                .type_implements_trait(trait_def_id, args, param_env)
1521                .must_apply_modulo_regions()
1522            {
1523                return None;
1524            }
1525            let ocx = ObligationCtxt::new(&infcx);
1526            let item_ty = ocx.normalize(
1527                &ObligationCause::dummy(),
1528                param_env,
1529                Unnormalized::new(Ty::new_projection_from_args(
1530                    infcx.tcx,
1531                    ty::IsRigid::No,
1532                    assoc_item_def_id,
1533                    args,
1534                )),
1535            );
1536            // FIXME(compiler-errors): We may benefit from resolving regions here.
1537            if ocx.try_evaluate_obligations().no_errors()
1538                && let item_ty = infcx.deeply_resolve_ignoring_regions(item_ty)
1539                && let Some(item_ty) = item_ty.make_suggestable(infcx.tcx, false, None)
1540                && let Some(sugg) = formatter(
1541                    infcx.tcx,
1542                    infcx.deeply_resolve_ignoring_regions(args),
1543                    trait_def_id,
1544                    assoc_item_def_id,
1545                    item_ty,
1546                )
1547            {
1548                return Some(sugg);
1549            }
1550
1551            None
1552        });
1553
1554        if sugg.is_some() {
1555            return sugg;
1556        }
1557    }
1558    None
1559}
1560
1561fn impl_is_fully_generic_for_reflection(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1562    tcx.impl_trait_header(def_id).is_fully_generic_for_reflection()
1563        && tcx.explicit_clauses_of(def_id).is_fully_generic_for_reflection()
1564}
1565
1566fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::ImplTraitHeader<'_> {
1567    let icx = ItemCtxt::new(tcx, def_id);
1568    let item = tcx.hir_expect_item(def_id);
1569    let impl_ = item.expect_impl();
1570    let of_trait = impl_
1571        .of_trait
1572        .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("expected impl trait, found inherent impl on {0:?}",
            def_id));
}panic!("expected impl trait, found inherent impl on {def_id:?}"));
1573    let selfty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1574
1575    check_impl_constness(tcx, impl_.constness, &of_trait.trait_ref);
1576
1577    let trait_ref = icx.lowerer().lower_impl_trait_ref(&of_trait.trait_ref, selfty);
1578
1579    ty::ImplTraitHeader {
1580        trait_ref: ty::EarlyBinder::bind(tcx, trait_ref),
1581        safety: of_trait.safety,
1582        polarity: polarity_of_impl(of_trait),
1583        constness: impl_.constness,
1584    }
1585}
1586
1587fn check_impl_constness(
1588    tcx: TyCtxt<'_>,
1589    constness: hir::Constness,
1590    hir_trait_ref: &hir::TraitRef<'_>,
1591) {
1592    if let hir::Constness::NotConst = constness {
1593        return;
1594    }
1595
1596    let Some(trait_def_id) = hir_trait_ref.trait_def_id() else { return };
1597    if tcx.is_const_trait(trait_def_id) {
1598        return;
1599    }
1600
1601    let trait_name = tcx.item_name(trait_def_id).to_string();
1602    let (suggestion, suggestion_pre) = match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
1603    {
1604        (Some(trait_def_id), true) => {
1605            let span = tcx.hir_expect_item(trait_def_id).vis_span;
1606            let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1607
1608            (
1609                Some(span.shrink_to_hi()),
1610                if tcx.features().const_trait_impl() {
1611                    ""
1612                } else {
1613                    "enable `#![feature(const_trait_impl)]` in your crate and "
1614                },
1615            )
1616        }
1617        (None, _) | (_, false) => (None, ""),
1618    };
1619    tcx.dcx().emit_err(diagnostics::ConstImplForNonConstTrait {
1620        trait_ref_span: hir_trait_ref.path.span,
1621        trait_name,
1622        suggestion,
1623        suggestion_pre,
1624        marking: (),
1625        adding: (),
1626    });
1627}
1628
1629fn polarity_of_impl(of_trait: &hir::TraitImplHeader<'_>) -> ty::ImplPolarity {
1630    match of_trait.polarity {
1631        hir::ImplPolarity::Negative(_) => ty::ImplPolarity::Negative,
1632        hir::ImplPolarity::Positive => ty::ImplPolarity::Positive,
1633    }
1634}
1635
1636/// Returns the early-bound lifetimes declared in this generics
1637/// listing. For anything other than fns/methods, this is just all
1638/// the lifetimes that are declared. For fns or methods, we have to
1639/// screen out those that do not appear in any where-clauses etc using
1640/// `resolve_lifetime::early_bound_lifetimes`.
1641fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1642    tcx: TyCtxt<'tcx>,
1643    generics: &'a hir::Generics<'a>,
1644) -> impl Iterator<Item = &'a hir::GenericParam<'a>> {
1645    generics.params.iter().filter(move |param| match param.kind {
1646        GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1647        _ => false,
1648    })
1649}
1650
1651fn compute_sig_of_foreign_fn_decl<'tcx>(
1652    tcx: TyCtxt<'tcx>,
1653    def_id: LocalDefId,
1654    decl: &'tcx hir::FnDecl<'tcx>,
1655    abi: ExternAbi,
1656    safety: hir::Safety,
1657) -> ty::PolyFnSig<'tcx> {
1658    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1659    let fty =
1660        ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, safety, abi, decl, None, None);
1661
1662    // Feature gate SIMD types in FFI, since I am not sure that the
1663    // ABIs are handled at all correctly. -huonw
1664    if !tcx.features().simd_ffi() {
1665        let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1666            if ty.is_simd() {
1667                let snip = tcx
1668                    .sess
1669                    .source_map()
1670                    .span_to_snippet(hir_ty.span)
1671                    .map_or_else(|_| String::new(), |s| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}`", s))
    })format!(" `{s}`"));
1672                tcx.dcx()
1673                    .emit_err(diagnostics::SIMDFFIHighlyExperimental { span: hir_ty.span, snip });
1674            }
1675        };
1676        for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1677            check(input, *ty)
1678        }
1679        if let hir::FnRetTy::Return(ty) = decl.output {
1680            check(ty, fty.output().skip_binder())
1681        }
1682    }
1683
1684    fty
1685}
1686
1687fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<hir::CoroutineKind> {
1688    match tcx.hir_node_by_def_id(def_id) {
1689        Node::Expr(&hir::Expr {
1690            kind:
1691                hir::ExprKind::Closure(&rustc_hir::Closure {
1692                    kind: hir::ClosureKind::Coroutine(kind),
1693                    ..
1694                }),
1695            ..
1696        }) => Some(kind),
1697        _ => None,
1698    }
1699}
1700
1701fn coroutine_for_closure(tcx: TyCtxt<'_>, def_id: LocalDefId) -> DefId {
1702    let &rustc_hir::Closure { kind: hir::ClosureKind::CoroutineClosure(_), body, .. } =
1703        tcx.hir_node_by_def_id(def_id).expect_closure()
1704    else {
1705        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
1706    };
1707
1708    let &hir::Expr {
1709        kind:
1710            hir::ExprKind::Closure(&rustc_hir::Closure {
1711                def_id,
1712                kind: hir::ClosureKind::Coroutine(_),
1713                ..
1714            }),
1715        ..
1716    } = tcx.hir_body(body).value
1717    else {
1718        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
1719    };
1720
1721    def_id.to_def_id()
1722}
1723
1724fn opaque_ty_origin<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> hir::OpaqueTyOrigin<DefId> {
1725    match tcx.hir_node_by_def_id(def_id).expect_opaque_ty().origin {
1726        hir::OpaqueTyOrigin::FnReturn { parent, in_trait_or_impl } => {
1727            hir::OpaqueTyOrigin::FnReturn { parent: parent.to_def_id(), in_trait_or_impl }
1728        }
1729        hir::OpaqueTyOrigin::AsyncFn { parent, in_trait_or_impl } => {
1730            hir::OpaqueTyOrigin::AsyncFn { parent: parent.to_def_id(), in_trait_or_impl }
1731        }
1732        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty } => {
1733            hir::OpaqueTyOrigin::TyAlias { parent: parent.to_def_id(), in_assoc_ty }
1734        }
1735    }
1736}
1737
1738fn rendered_precise_capturing_args<'tcx>(
1739    tcx: TyCtxt<'tcx>,
1740    def_id: LocalDefId,
1741) -> Option<&'tcx [PreciseCapturingArgKind<Symbol, Symbol>]> {
1742    if let Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) =
1743        tcx.opt_rpitit_info(def_id.to_def_id())
1744    {
1745        return tcx.rendered_precise_capturing_args(opaque_def_id);
1746    }
1747
1748    tcx.hir_node_by_def_id(def_id).expect_opaque_ty().bounds.iter().find_map(|bound| match bound {
1749        hir::GenericBound::Use(args, ..) => {
1750            Some(&*tcx.arena.alloc_from_iter(args.iter().map(|arg| match arg {
1751                PreciseCapturingArgKind::Lifetime(_) => {
1752                    PreciseCapturingArgKind::Lifetime(arg.name())
1753                }
1754                PreciseCapturingArgKind::Param(_) => PreciseCapturingArgKind::Param(arg.name()),
1755            })))
1756        }
1757        _ => None,
1758    })
1759}
1760
1761fn const_param_default<'tcx>(
1762    tcx: TyCtxt<'tcx>,
1763    param_def_id: LocalDefId,
1764) -> ty::EarlyBinder<'tcx, Const<'tcx>> {
1765    let hir::Node::GenericParam(hir::GenericParam {
1766        kind: hir::GenericParamKind::Const { default: Some(ct), .. },
1767        ..
1768    }) = tcx.hir_node_by_def_id(param_def_id)
1769    else {
1770        ::rustc_span::macros::bug_impl(Some(tcx.def_span(param_def_id)),
    format_args!("const_param_default: expected a const parameter with a default value"),
    Location::caller())span_bug!(
1771            tcx.def_span(param_def_id),
1772            "const_param_default: expected a const parameter with a default value"
1773        )
1774    };
1775
1776    // FIXME: Don't lower in the context of parent. Blocked on the removal of GCE. See comment in
1777    //        `type_of.rs` for details (Ctrl+F for `generics_of`).
1778    let item_def_id = tcx.local_parent(param_def_id);
1779    let icx = ItemCtxt::new(tcx, item_def_id);
1780
1781    let ct = icx
1782        .lowerer()
1783        .lower_const_arg(ct, tcx.type_of(param_def_id).instantiate_identity().skip_norm_wip());
1784    ty::EarlyBinder::bind(tcx, ct)
1785}
1786
1787fn anon_const_kind<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> ty::AnonConstKind {
1788    if true {
    {
        match tcx.def_kind(def) {
            DefKind::AnonConst => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::AnonConst", ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(tcx.def_kind(def), DefKind::AnonConst);
1789    let hir_id = tcx.local_def_id_to_hir_id(def);
1790    let parent_node_id = tcx.parent_hir_id(hir_id);
1791    match tcx.hir_node(parent_node_id) {
1792        hir::Node::ConstArg(const_arg) => {
1793            if true {
    {
        match const_arg.kind {
            hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if
                *def_id == def => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if *def_id == def",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(const_arg.kind, hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if *def_id == def);
1794            if tcx.features().generic_const_exprs() {
1795                ty::AnonConstKind::GCE
1796            } else if tcx.features().gca() {
1797                ty::AnonConstKind::MCG
1798            } else if let hir::Node::Expr(hir::Expr {
1799                kind: hir::ExprKind::Repeat(_, repeat_count),
1800                ..
1801            }) = tcx.parent_hir_node(parent_node_id)
1802                && repeat_count.hir_id == parent_node_id
1803            {
1804                ty::AnonConstKind::RepeatExprCount
1805            } else {
1806                ty::AnonConstKind::MCG
1807            }
1808        }
1809        hir::Node::Expr(hir::Expr {
1810            kind: hir::ExprKind::ConstBlock(..) | hir::ExprKind::InlineAsm(..),
1811            ..
1812        }) => ty::AnonConstKind::NonTypeSystemInline,
1813        _ => ty::AnonConstKind::NonTypeSystemAnon,
1814    }
1815}
1816
1817{}
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("const_of_item",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(1817u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                                ::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();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                Option<ty::EarlyBinder<'tcx, Const<'tcx>>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let ct_rhs =
                            match tcx.hir_node_by_def_id(def_id) {
                                hir::Node::Item(&hir::Item {
                                    kind: hir::ItemKind::Const(.., ct), .. }) => ct,
                                hir::Node::TraitItem(&hir::TraitItem {
                                    kind: hir::TraitItemKind::Const(_, ct), .. }) => ct?,
                                hir::Node::ImplItem(&hir::ImplItem {
                                    kind: hir::ImplItemKind::Const(.., ct), .. }) => ct,
                                node => {
                                    ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
                                        format_args!("`const_of_item` expected a const or assoc const item, got {0:?}",
                                            node), Location::caller())
                                }
                            };
                        let ct_arg =
                            match ct_rhs {
                                hir::ConstItemRhs::Direct(ct_arg) => ct_arg,
                                hir::ConstItemRhs::Body(_) => { return None; }
                            };
                        let icx = ItemCtxt::new(tcx, def_id);
                        let identity_args =
                            ty::GenericArgs::identity_for_item(tcx, def_id);
                        let ct =
                            icx.lowerer().lower_const_arg(ct_arg,
                                tcx.type_of(def_id.to_def_id()).instantiate(tcx,
                                        identity_args).skip_norm_wip());
                        if let Err(e) = icx.check_tainted_by_errors() &&
                                !ct.references_error() {
                            Some(ty::EarlyBinder::bind(tcx, Const::new_error(tcx, e)))
                        } else { Some(ty::EarlyBinder::bind(tcx, ct)) }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs:1817",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1a2c4797ef2570bd76ca5dee34449169bc7dc457/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(1817u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
1818fn const_of_item<'tcx>(
1819    tcx: TyCtxt<'tcx>,
1820    def_id: LocalDefId,
1821) -> Option<ty::EarlyBinder<'tcx, Const<'tcx>>> {
1822    let ct_rhs = match tcx.hir_node_by_def_id(def_id) {
1823        hir::Node::Item(&hir::Item { kind: hir::ItemKind::Const(.., ct), .. }) => ct,
1824        hir::Node::TraitItem(&hir::TraitItem {
1825            kind: hir::TraitItemKind::Const(_, ct), ..
1826        }) => ct?,
1827        hir::Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(.., ct), .. }) => ct,
1828        node => {
1829            span_bug!(
1830                tcx.def_span(def_id),
1831                "`const_of_item` expected a const or assoc const item, got {node:?}"
1832            )
1833        }
1834    };
1835    let ct_arg = match ct_rhs {
1836        hir::ConstItemRhs::Direct(ct_arg) => ct_arg,
1837        hir::ConstItemRhs::Body(_) => {
1838            return None;
1839        }
1840    };
1841    let icx = ItemCtxt::new(tcx, def_id);
1842    let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
1843    let ct = icx.lowerer().lower_const_arg(
1844        ct_arg,
1845        tcx.type_of(def_id.to_def_id()).instantiate(tcx, identity_args).skip_norm_wip(),
1846    );
1847    if let Err(e) = icx.check_tainted_by_errors()
1848        && !ct.references_error()
1849    {
1850        Some(ty::EarlyBinder::bind(tcx, Const::new_error(tcx, e)))
1851    } else {
1852        Some(ty::EarlyBinder::bind(tcx, ct))
1853    }
1854}