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 {
        Self {
            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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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 {
                                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 { 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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:326",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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 { 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 { 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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:343",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:364",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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    // FIXME: this is likely too basic, and we'll want to evolve/make this more advanced over time.
376    // For example, right now, if the user writes `forall<'a> where Foo<'a>: 'b`, that's not gonna
377    // work - that should be destructured into `where 'a: 'b`, whether by hand (and checked it was
378    // indeed done so, via compiler) or automatically by the test framework, unsure, but something.
379    fn lower_test_binder_assumptions(
380        &self,
381        predicate: &hir::WherePredicate<'tcx>,
382        type_outlives: &mut Vec<ty::Binder<'tcx, ty::OutlivesClause<'tcx, Ty<'tcx>>>>,
383        region_outlives: &mut Vec<(ty::Region<'tcx>, ty::Region<'tcx>)>,
384    ) {
385        match predicate.kind {
386            hir::WherePredicateKind::BoundPredicate(p) => {
387                let bound_vars = self.tcx.late_bound_vars(predicate.hir_id);
388                let ty = self.lower_ty(p.bounded_ty);
389                for bound in p.bounds {
390                    match bound {
391                        hir::GenericBound::Trait(poly_trait_ref) => {
392                            self.dcx()
393                                .span_err(poly_trait_ref.span, "trait bounds aren't supported yet");
394                        }
395                        hir::GenericBound::Outlives(lifetime) => {
396                            let region = self
397                                .lowerer()
398                                .lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
399                            let binder = ty::Binder::bind_with_vars(
400                                ty::OutlivesClause(ty, region),
401                                bound_vars,
402                            );
403                            type_outlives.push(binder);
404                        }
405                        hir::GenericBound::Use(_, span) => {
406                            self.dcx().span_err(*span, "use bounds aren't supported yet");
407                        }
408                    }
409                }
410            }
411            hir::WherePredicateKind::RegionPredicate(predicate) => {
412                let lhs = self
413                    .lowerer()
414                    .lower_lifetime(predicate.lifetime, RegionInferReason::RegionPredicate);
415                for bound in predicate.bounds {
416                    match bound {
417                        hir::GenericBound::Trait(poly_trait_ref) => {
418                            self.dcx()
419                                .span_err(poly_trait_ref.span, "trait bounds aren't supported yet");
420                        }
421                        hir::GenericBound::Outlives(lifetime) => {
422                            let rhs = self
423                                .lowerer()
424                                .lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
425                            region_outlives.push((lhs, rhs));
426                        }
427                        hir::GenericBound::Use(_, span) => {
428                            self.dcx().span_err(*span, "use bounds aren't supported yet");
429                        }
430                    }
431                }
432            }
433        }
434    }
435
436    fn lower_test_binder_constraint(
437        &self,
438        constraint: &hir::TestBinderConstraint<'tcx>,
439    ) -> SolverRegionConstraint<'tcx> {
440        match constraint {
441            hir::TestBinderConstraint::And { items } => items
442                .into_iter()
443                .map(|item| self.lower_test_binder_constraint(item))
444                .reduce(SolverRegionConstraint::build_and)
445                .unwrap_or(SolverRegionConstraint::new_true()),
446            hir::TestBinderConstraint::Or { items } => items
447                .into_iter()
448                .map(|item| self.lower_test_binder_constraint(item))
449                .reduce(SolverRegionConstraint::build_or)
450                .unwrap_or(SolverRegionConstraint::new_false()),
451            hir::TestBinderConstraint::Lifetime { lhs, rhs } => {
452                let span = lhs.ident.span.to(rhs.ident.span);
453                let lhs = self.lowerer().lower_lifetime(lhs, RegionInferReason::RegionPredicate);
454                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
455                SolverRegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(
456                    lhs, rhs, span,
457                ))
458            }
459            hir::TestBinderConstraint::PlaceholderOutlives { lhs, rhs } => {
460                let span = lhs.span.to(rhs.ident.span);
461                let lhs = self.lower_ty(lhs);
462                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
463                // note that we cannot check that lhs is a placeholder at this moment, as at this
464                // point it is a bound variable that is not yet instantiated with a placeholder.
465                // instead, we check it when we emit the region constraint.
466                SolverRegionConstraint::new_leaf(LeafRegionConstraint::PlaceholderTyOutlives(
467                    lhs, rhs, span,
468                ))
469            }
470            hir::TestBinderConstraint::AliasOutlives {
471                bound_type_constraint:
472                    hir::TestBinderBoundTypeConstraint { span, hir_id, params: _, lhs, rhs },
473            } => {
474                let bound_vars = self.tcx.late_bound_vars(*hir_id);
475                let &ty::Alias(_, lhs) = self.lower_ty(lhs).kind() else {
476                    self.dcx().span_err(lhs.span, "bound type test binder constraint must be alias (it's a AliasTyOutlivesViaEnv)");
477                    return SolverRegionConstraint::new_true();
478                };
479                let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
480                SolverRegionConstraint::new_leaf(LeafRegionConstraint::AliasTyOutlivesViaEnv(
481                    ty::Binder::bind_with_vars((lhs, rhs), bound_vars),
482                    *span,
483                ))
484            }
485        }
486    }
487}
488
489impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
490    fn tcx(&self) -> TyCtxt<'tcx> {
491        self.tcx
492    }
493
494    fn dcx(&self) -> DiagCtxtHandle<'_> {
495        self.tcx.dcx().into_taintable(&self.tainted_by_errors)
496    }
497
498    fn item_def_id(&self) -> LocalDefId {
499        self.item_def_id
500    }
501
502    fn mod_id(&self) -> LocalModId {
503        self.tcx.parent_module_from_def_id(self.item_def_id)
504    }
505
506    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
507        if let RegionInferReason::ObjectLifetimeDefault(sugg_sp) = reason {
508            // FIXME: Account for trailing plus `dyn Trait+`, the need of parens in
509            //        `*const dyn Trait` and `Fn() -> *const dyn Trait`.
510            let guar = self
511                .dcx()
512                .struct_span_err(
513                    span,
514                    "cannot deduce the lifetime bound for this trait object type from context",
515                )
516                .with_code(E0228)
517                .with_span_suggestion_verbose(
518                    sugg_sp,
519                    "please supply an explicit bound",
520                    " + /* 'a */",
521                    Applicability::HasPlaceholders,
522                )
523                .emit_err();
524            ty::Region::new_error(self.tcx(), guar)
525        } else {
526            // If we found elided lifetime during lowering of delegation parent or child
527            // segment then emit an error, as we need a named lifetime for proper signature
528            // inheritance (#156848).
529            if self.lowering_delegation_segment {
530                self.tcx.dcx().emit_err(ElidedLifetimesAreNotAllowedInDelegations { span });
531            }
532
533            // This indicates an illegal lifetime in a non-assoc-trait position
534            ty::Region::new_error_with_message(self.tcx(), span, "inferred lifetime in signature")
535        }
536    }
537
538    fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
539        if !self.tcx.dcx().has_stashed_diagnostic(span, StashKey::ItemNoType) {
540            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![]);
541        }
542        Ty::new_error_with_message(self.tcx(), span, "bad placeholder type")
543    }
544
545    fn ct_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
546        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![]);
547        ty::Const::new_error_with_message(self.tcx(), span, "bad placeholder constant")
548    }
549
550    fn register_trait_ascription_bounds(
551        &self,
552        _: Vec<(ty::Clause<'tcx>, Span)>,
553        _: HirId,
554        span: Span,
555    ) {
556        self.dcx().span_delayed_bug(span, "trait ascription type not allowed here");
557    }
558
559    fn probe_ty_param_bounds(
560        &self,
561        span: Span,
562        def_id: LocalDefId,
563        assoc_ident: Ident,
564    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
565        self.tcx.at(span).type_param_clauses((self.item_def_id, def_id, assoc_ident))
566    }
567
568    {}
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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(568u32),
                                ::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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:582",
                                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/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: 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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:591",
                                                                    "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                                                                    ::tracing_core::__macro_support::Option::Some(591u32),
                                                                    ::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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:568",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(568u32),
                        ::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)]
569    fn select_inherent_assoc_candidates(
570        &self,
571        _span: Span,
572        self_ty: Ty<'tcx>,
573        candidates: Vec<InherentAssocCandidate>,
574    ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>) {
575        assert!(!self_ty.has_infer());
576
577        // We don't just call the normal normalization routine here as we can't provide the
578        // correct `ParamEnv` and it would be wrong to invoke arbitrary trait solving under
579        // the wrong `ParamEnv`. Expanding free aliases doesn't need a `ParamEnv` so we do
580        // this just to make resolution a little bit smarter.
581        let self_ty = self.tcx.expand_free_alias_tys(self_ty);
582        debug!("select_inherent_assoc_candidates: self_ty={:?}", self_ty);
583
584        let candidates = candidates
585            .into_iter()
586            .filter(|&InherentAssocCandidate { impl_, .. }| {
587                let impl_ty = self.tcx().type_of(impl_).instantiate_identity().skip_norm_wip();
588
589                // See comment on doing this operation for `self_ty`
590                let impl_ty = self.tcx.expand_free_alias_tys(impl_ty);
591                debug!("select_inherent_assoc_candidates: impl_ty={:?}", impl_ty);
592
593                // We treat parameters in the self ty as rigid and parameters in the impl ty as infers
594                // because it allows `impl<T> Foo<T>` to unify with `Foo<u8>::IAT`, while also disallowing
595                // `Foo<T>::IAT` from unifying with `impl Foo<u8>`.
596                //
597                // We don't really care about a depth limit here because we're only working with user-written
598                // types and if they wrote a type that would take hours to walk then that's kind of on them. On
599                // the other hand the default depth limit is relatively low and could realistically be hit by
600                // users in normal cases.
601                //
602                // `DeepRejectCtxt` leads to slightly worse IAT resolution than real type equality in cases
603                // where the `impl_ty` has repeated uses of generic parameters. E.g. `impl<T> Foo<T, T>` would
604                // be considered a valid candidate when resolving `Foo<u8, u16>::IAT`.
605                //
606                // Not replacing escaping bound vars in `self_ty` with placeholders also leads to slightly worse
607                // resolution, but it probably won't come up in practice and it would be backwards compatible
608                // to switch over to doing that.
609                ty::DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify_with_depth(
610                    self_ty,
611                    impl_ty,
612                    usize::MAX,
613                )
614            })
615            .collect();
616
617        (candidates, thin_vec![])
618    }
619
620    fn lower_assoc_item_path(
621        &self,
622        span: Span,
623        item_def_id: DefId,
624        item_segment: &rustc_hir::PathSegment<'_>,
625        poly_trait_ref: ty::PolyTraitRef<'tcx>,
626    ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
627        if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
628            let item_args = self.lowerer().lower_generic_args_of_assoc_item(
629                span,
630                item_def_id,
631                item_segment,
632                trait_ref.args,
633            );
634            Ok((item_def_id, item_args))
635        } else {
636            // There are no late-bound regions; we can just ignore the binder.
637            let (mut mpart_sugg, mut inferred_sugg) = (None, None);
638            let mut bound = String::new();
639
640            match self.node() {
641                hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
642                    let item = self
643                        .tcx
644                        .hir_expect_item(self.tcx.hir_get_parent_item(self.hir_id()).def_id);
645                    match &item.kind {
646                        hir::ItemKind::Enum(_, generics, _)
647                        | hir::ItemKind::Struct(_, generics, _)
648                        | hir::ItemKind::Union(_, generics, _) => {
649                            let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
650                            let (lt_sp, sugg) = match generics.params {
651                                [] => (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", lt_name))
    })format!("<{lt_name}>")),
652                                [bound, ..] => (bound.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", lt_name))
    })format!("{lt_name}, ")),
653                            };
654                            mpart_sugg = Some(diagnostics::AssociatedItemTraitUninferredGenericParamsMultipartSuggestion {
655                                fspan: lt_sp,
656                                first: sugg,
657                                sspan: span.with_hi(item_segment.ident.span.lo()),
658                                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!(
659                                    "{}::",
660                                    // Replace the existing lifetimes with a new named lifetime.
661                                    self.tcx.instantiate_bound_regions_uncached(
662                                        poly_trait_ref,
663                                        |_| {
664                                            ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion {
665                                                index: 0,
666                                                name: Symbol::intern(&lt_name),
667                                            })
668                                        }
669                                    ),
670                                ),
671                            });
672                        }
673                        _ => {}
674                    }
675                }
676                hir::Node::Item(hir::Item {
677                    kind:
678                        hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
679                    ..
680                }) => {}
681                hir::Node::Item(_)
682                | hir::Node::ForeignItem(_)
683                | hir::Node::TraitItem(_)
684                | hir::Node::ImplItem(_) => {
685                    inferred_sugg = Some(span.with_hi(item_segment.ident.span.lo()));
686                    bound = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::",
                self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder()))
    })format!(
687                        "{}::",
688                        // Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
689                        self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
690                    );
691                }
692                _ => {}
693            }
694
695            Err(self.tcx().dcx().emit_err(
696                diagnostics::AssociatedItemTraitUninferredGenericParams {
697                    span,
698                    inferred_sugg,
699                    bound,
700                    mpart_sugg,
701                    what: self.tcx.def_descr(item_def_id),
702                },
703            ))
704        }
705    }
706
707    fn probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
708        // FIXME(#103640): Should we handle the case where `ty` is a projection?
709        ty.ty_adt_def()
710    }
711
712    fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
713        // There's no place to record types from signatures?
714    }
715
716    fn infcx(&self) -> Option<&InferCtxt<'tcx>> {
717        None
718    }
719
720    fn lower_fn_sig(
721        &self,
722        decl: &hir::FnDecl<'_>,
723        _generics: Option<&hir::Generics<'_>>,
724        hir_id: rustc_hir::HirId,
725        _hir_ty: Option<&hir::Ty<'_>>,
726    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
727        let tcx = self.tcx();
728
729        let mut infer_replacements = ::alloc::vec::Vec::new()vec![];
730
731        let input_tys = decl
732            .inputs
733            .iter()
734            .enumerate()
735            .map(|(i, a)| {
736                if let hir::TyKind::Infer(()) = a.kind
737                    && let Some(suggested_ty) =
738                        self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
739                {
740                    infer_replacements.push((a.span, suggested_ty.to_string()));
741                    return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string());
742                }
743
744                self.lowerer().lower_ty(a)
745            })
746            .collect();
747
748        let output_ty = match decl.output {
749            hir::FnRetTy::Return(output) => {
750                if let hir::TyKind::Infer(()) = output.kind
751                    && let Some(suggested_ty) =
752                        self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
753                {
754                    infer_replacements.push((output.span, suggested_ty.to_string()));
755                    Ty::new_error_with_message(tcx, output.span, suggested_ty.to_string())
756                } else {
757                    self.lower_ty(output)
758                }
759            }
760            hir::FnRetTy::DefaultReturn(..) => tcx.types.unit,
761        };
762
763        if !infer_replacements.is_empty() {
764            self.report_placeholder_type_error(::alloc::vec::Vec::new()vec![], infer_replacements);
765        }
766        (input_tys, output_ty)
767    }
768
769    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
770        hir_ty_lowering_dyn_compatibility_violations(self.tcx, trait_def_id)
771    }
772}
773
774/// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
775fn get_new_lifetime_name<'tcx>(
776    tcx: TyCtxt<'tcx>,
777    poly_trait_ref: ty::PolyTraitRef<'tcx>,
778    generics: &hir::Generics<'tcx>,
779) -> String {
780    let existing_lifetimes = tcx
781        .collect_referenced_late_bound_regions(poly_trait_ref)
782        .into_iter()
783        .filter_map(|lt| lt.get_name(tcx).map(|name| name.as_str().to_string()))
784        .chain(generics.params.iter().filter_map(|param| {
785            if let hir::GenericParamKind::Lifetime { .. } = &param.kind {
786                Some(param.name.ident().as_str().to_string())
787            } else {
788                None
789            }
790        }))
791        .collect::<FxHashSet<String>>();
792
793    let a_to_z_repeat_n = |n| {
794        (b'a'..=b'z').map(move |c| {
795            let mut s = '\''.to_string();
796            s.extend(std::iter::repeat_n(char::from(c), n));
797            s
798        })
799    };
800
801    // If all single char lifetime names are present, we wrap around and double the chars.
802    (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
803}
804
805pub(super) fn check_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
806    tcx.ensure_ok().generics_of(def_id);
807    tcx.ensure_ok().type_of(def_id);
808    tcx.ensure_ok().clauses_of(def_id);
809}
810
811pub(super) fn check_enum_variant_types(tcx: TyCtxt<'_>, def_id: LocalDefId) {
812    struct ReprCIssue {
813        msg: &'static str,
814    }
815
816    impl<'a> Diagnostic<'a> for ReprCIssue {
817        fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
818            let Self { msg } = self;
819            Diag::new(dcx, level, msg)
820                .with_note("`repr(C)` enums with big discriminants are non-portable, and their size in Rust might not match their size in C")
821                .with_help("use `repr($int_ty)` instead to explicitly set the size of this enum")
822        }
823    }
824
825    let def = tcx.adt_def(def_id);
826    let repr_type = def.repr().discr_type();
827    let initial = repr_type.initial_discriminant(tcx);
828    let mut prev_discr = None::<Discr<'_>>;
829    // Some of the logic below relies on `i128` being able to hold all c_int and c_uint values.
830    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);
831    let mut min_discr = i128::MAX;
832    let mut max_discr = i128::MIN;
833
834    // fill the discriminant values and field types
835    for variant in def.variants() {
836        let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
837        let cur_discr = if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
838            def.eval_explicit_discr(tcx, const_def_id).ok()
839        } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
840            Some(discr)
841        } else {
842            let span = tcx.def_span(variant.def_id);
843            tcx.dcx().emit_err(diagnostics::EnumDiscriminantOverflowed {
844                span,
845                discr: prev_discr.unwrap().to_string(),
846                item_name: tcx.item_ident(variant.def_id),
847                wrapped_discr: wrapped_discr.to_string(),
848            });
849            None
850        }
851        .unwrap_or(wrapped_discr);
852
853        if def.repr().c() {
854            let c_int = Size::from_bits(tcx.sess.target.c_int_width);
855            let c_uint_max = i128::try_from(c_int.unsigned_int_max()).unwrap();
856            // c_int is a signed type, so get a proper signed version of the discriminant
857            let discr_size = cur_discr.ty.int_size_and_signed(tcx).0;
858            let discr_val = discr_size.sign_extend(cur_discr.val);
859            min_discr = min_discr.min(discr_val);
860            max_discr = max_discr.max(discr_val);
861
862            // The discriminant range must either fit into c_int or c_uint.
863            if !(min_discr >= c_int.signed_int_min() && max_discr <= c_int.signed_int_max())
864                && !(min_discr >= 0 && max_discr <= c_uint_max)
865            {
866                let span = tcx.def_span(variant.def_id);
867                let msg = if discr_val < c_int.signed_int_min() || discr_val > c_uint_max {
868                    "`repr(C)` enum discriminant does not fit into C `int` nor into C `unsigned int`"
869                } else if discr_val < 0 {
870                    "`repr(C)` enum discriminant does not fit into C `unsigned int`, and a previous discriminant does not fit into C `int`"
871                } else {
872                    "`repr(C)` enum discriminant does not fit into C `int`, and a previous discriminant does not fit into C `unsigned int`"
873                };
874                tcx.emit_node_span_lint(
875                    REPR_C_ENUMS_LARGER_THAN_INT,
876                    tcx.local_def_id_to_hir_id(def_id),
877                    span,
878                    ReprCIssue { msg },
879                );
880            }
881        }
882
883        prev_discr = Some(cur_discr);
884
885        for f in &variant.fields {
886            tcx.ensure_ok().generics_of(f.did);
887            tcx.ensure_ok().type_of(f.did);
888            tcx.ensure_ok().clauses_of(f.did);
889        }
890
891        // Lower the ctor, if any. This also registers the variant as an item.
892        if let Some(ctor_def_id) = variant.ctor_def_id() {
893            check_ctor(tcx, ctor_def_id.expect_local());
894        }
895    }
896}
897
898#[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)]
899struct NestedSpan {
900    span: Span,
901    nested_field_span: Span,
902}
903
904impl NestedSpan {
905    fn to_field_already_declared_nested_help(&self) -> diagnostics::FieldAlreadyDeclaredNestedHelp {
906        diagnostics::FieldAlreadyDeclaredNestedHelp { span: self.span }
907    }
908}
909
910#[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)]
911enum FieldDeclSpan {
912    NotNested(Span),
913    Nested(NestedSpan),
914}
915
916impl From<Span> for FieldDeclSpan {
917    fn from(span: Span) -> Self {
918        Self::NotNested(span)
919    }
920}
921
922impl From<NestedSpan> for FieldDeclSpan {
923    fn from(span: NestedSpan) -> Self {
924        Self::Nested(span)
925    }
926}
927
928struct FieldUniquenessCheckContext<'tcx> {
929    tcx: TyCtxt<'tcx>,
930    seen_fields: FxIndexMap<Ident, FieldDeclSpan>,
931}
932
933impl<'tcx> FieldUniquenessCheckContext<'tcx> {
934    fn new(tcx: TyCtxt<'tcx>) -> Self {
935        Self { tcx, seen_fields: FxIndexMap::default() }
936    }
937
938    /// Check if a given field `ident` declared at `field_decl` has been declared elsewhere before.
939    fn check_field_decl(&mut self, field_name: Ident, field_decl: FieldDeclSpan) {
940        use FieldDeclSpan::*;
941        let field_name = field_name.normalize_to_macros_2_0();
942        match (field_decl, self.seen_fields.get(&field_name).copied()) {
943            (NotNested(span), Some(NotNested(prev_span))) => {
944                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::NotNested {
945                    field_name,
946                    span,
947                    prev_span,
948                });
949            }
950            (NotNested(span), Some(Nested(prev))) => {
951                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::PreviousNested {
952                    field_name,
953                    span,
954                    prev_span: prev.span,
955                    prev_nested_field_span: prev.nested_field_span,
956                    prev_help: prev.to_field_already_declared_nested_help(),
957                });
958            }
959            (
960                Nested(current @ NestedSpan { span, nested_field_span, .. }),
961                Some(NotNested(prev_span)),
962            ) => {
963                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::CurrentNested {
964                    field_name,
965                    span,
966                    nested_field_span,
967                    help: current.to_field_already_declared_nested_help(),
968                    prev_span,
969                });
970            }
971            (Nested(current @ NestedSpan { span, nested_field_span }), Some(Nested(prev))) => {
972                self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::BothNested {
973                    field_name,
974                    span,
975                    nested_field_span,
976                    help: current.to_field_already_declared_nested_help(),
977                    prev_span: prev.span,
978                    prev_nested_field_span: prev.nested_field_span,
979                    prev_help: prev.to_field_already_declared_nested_help(),
980                });
981            }
982            (field_decl, None) => {
983                self.seen_fields.insert(field_name, field_decl);
984            }
985        }
986    }
987}
988
989fn lower_variant<'tcx>(
990    tcx: TyCtxt<'tcx>,
991    variant_did: Option<LocalDefId>,
992    ident: Ident,
993    discr: ty::VariantDiscr,
994    def: &hir::VariantData<'tcx>,
995    adt_kind: ty::AdtKind,
996    parent_did: LocalDefId,
997) -> ty::VariantDef {
998    let mut field_uniqueness_check_ctx = FieldUniquenessCheckContext::new(tcx);
999    let fields = def
1000        .fields()
1001        .iter()
1002        .inspect(|field| {
1003            field_uniqueness_check_ctx.check_field_decl(field.ident, field.span.into());
1004        })
1005        .map(|f| ty::FieldDef {
1006            did: f.def_id.to_def_id(),
1007            name: f.ident.name,
1008            vis: tcx.visibility(f.def_id),
1009            mut_restriction: match f.mut_restriction.kind {
1010                hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1011                hir::RestrictionKind::Restricted(path) => {
1012                    ty::RestrictionKind::Restricted(path.res, f.mut_restriction.span)
1013                }
1014            },
1015            safety: f.safety,
1016            value: f.default.map(|v| v.def_id.to_def_id()),
1017        })
1018        .collect();
1019    let recovered = match def {
1020        hir::VariantData::Struct { recovered: Recovered::Yes(guar), .. } => Some(*guar),
1021        _ => None,
1022    };
1023    ty::VariantDef::new(
1024        ident.name,
1025        variant_did.map(LocalDefId::to_def_id),
1026        def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
1027        discr,
1028        fields,
1029        parent_did.to_def_id(),
1030        recovered,
1031        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(..))
1032            || variant_did
1033                .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(..))),
1034    )
1035}
1036
1037fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
1038    use rustc_hir::*;
1039
1040    let Node::Item(item) = tcx.hir_node_by_def_id(def_id) else {
1041        ::rustc_span::macros::bug_impl(None,
    format_args!("expected ADT to be an item"), Location::caller());bug!("expected ADT to be an item");
1042    };
1043
1044    let repr = tcx.repr_options_of_def(def_id);
1045    let (kind, variants) = match &item.kind {
1046        ItemKind::Enum(_, _, def) => {
1047            let mut distance_from_explicit = 0;
1048            let variants = def
1049                .variants
1050                .iter()
1051                .map(|v| {
1052                    let discr = if let Some(e) = &v.disr_expr {
1053                        distance_from_explicit = 0;
1054                        ty::VariantDiscr::Explicit(e.def_id.to_def_id())
1055                    } else {
1056                        ty::VariantDiscr::Relative(distance_from_explicit)
1057                    };
1058                    distance_from_explicit += 1;
1059
1060                    lower_variant(
1061                        tcx,
1062                        Some(v.def_id),
1063                        v.ident,
1064                        discr,
1065                        &v.data,
1066                        AdtKind::Enum,
1067                        def_id,
1068                    )
1069                })
1070                .collect();
1071
1072            (AdtKind::Enum, variants)
1073        }
1074        ItemKind::Struct(ident, _, def) | ItemKind::Union(ident, _, def) => {
1075            let adt_kind = match item.kind {
1076                ItemKind::Struct(..) => AdtKind::Struct,
1077                _ => AdtKind::Union,
1078            };
1079            let variants = std::iter::once(lower_variant(
1080                tcx,
1081                None,
1082                *ident,
1083                ty::VariantDiscr::Relative(0),
1084                def,
1085                adt_kind,
1086                def_id,
1087            ))
1088            .collect();
1089
1090            (adt_kind, variants)
1091        }
1092        _ => ::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),
1093    };
1094    tcx.mk_adt_def(def_id.to_def_id(), kind, variants, repr)
1095}
1096
1097fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
1098    let item = tcx.hir_expect_item(def_id);
1099
1100    let (constness, is_alias, is_auto, safety, impl_restriction) = match item.kind {
1101        hir::ItemKind::Trait { impl_restriction, constness, is_auto, safety, .. } => (
1102            constness,
1103            false,
1104            is_auto == hir::IsAuto::Yes,
1105            safety,
1106            match impl_restriction.kind {
1107                hir::RestrictionKind::Restricted(path) => {
1108                    ty::RestrictionKind::Restricted(path.res, impl_restriction.span)
1109                }
1110                hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1111            },
1112        ),
1113        hir::ItemKind::TraitAlias(constness, ..) => {
1114            (constness, true, false, hir::Safety::Safe, ty::RestrictionKind::Unrestricted)
1115        }
1116        _ => ::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"),
1117    };
1118
1119    // we do a bunch of find_attr calls here, probably faster to get them from the tcx just once.
1120    #[allow(deprecated)]
1121    let attrs = tcx.get_all_attrs(def_id);
1122
1123    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);
1124
1125    // Only regular traits can be marker.
1126    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);
1127
1128    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);
1129    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);
1130
1131    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!(
1132        attrs,
1133        RustcSkipDuringMethodDispatch { array, boxed_slice } => [*array, *boxed_slice]
1134    )
1135    .unwrap_or([false; 2]);
1136
1137    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) {
1138        ty::trait_def::TraitSpecializationKind::Marker
1139    } 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) {
1140        ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1141    } else {
1142        ty::trait_def::TraitSpecializationKind::None
1143    };
1144
1145    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!(
1146        attrs,
1147        RustcMustImplementOneOf { fn_names, .. } =>
1148            fn_names
1149                .iter()
1150                .cloned()
1151                .collect::<Box<[_]>>()
1152    );
1153
1154    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);
1155    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);
1156
1157    ty::TraitDef {
1158        def_id: def_id.to_def_id(),
1159        impl_restriction,
1160        safety,
1161        constness,
1162        paren_sugar,
1163        has_auto_impl: is_auto,
1164        is_marker,
1165        is_coinductive: rustc_coinductive || is_auto,
1166        is_fundamental,
1167        skip_array_during_method_dispatch,
1168        skip_boxed_slice_during_method_dispatch,
1169        specialization_kind,
1170        must_implement_one_of,
1171        force_dyn_incompatible,
1172        deny_explicit_impl,
1173    }
1174}
1175
1176{}
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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(1176u32),
                                ::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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:1176",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(1176u32),
                        ::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)]
1177fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFnSig<'_>> {
1178    use rustc_hir::Node::*;
1179    use rustc_hir::*;
1180
1181    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1182
1183    let icx = ItemCtxt::new(tcx, def_id);
1184
1185    let output = match tcx.hir_node(hir_id) {
1186        TraitItem(hir::TraitItem {
1187            kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1188            generics,
1189            ..
1190        })
1191        | Item(hir::Item { kind: ItemKind::Fn { sig, generics, .. }, .. }) => {
1192            lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1193        }
1194
1195        ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1196            // Do not try to infer the return type for a impl method coming from a trait
1197            if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) = tcx.parent_hir_node(hir_id)
1198                && i.of_trait.is_some()
1199            {
1200                icx.lowerer().lower_fn_ty(
1201                    hir_id,
1202                    sig.header.safety(),
1203                    sig.header.abi,
1204                    sig.decl,
1205                    Some(generics),
1206                    None,
1207                )
1208            } else {
1209                lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1210            }
1211        }
1212
1213        TraitItem(hir::TraitItem {
1214            kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1215            generics,
1216            ..
1217        }) => icx.lowerer().lower_fn_ty(
1218            hir_id,
1219            header.safety(),
1220            header.abi,
1221            decl,
1222            Some(generics),
1223            None,
1224        ),
1225
1226        ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
1227            let abi = tcx.hir_get_foreign_abi(hir_id);
1228            compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety())
1229        }
1230
1231        Ctor(data) => {
1232            assert_matches!(data.ctor(), Some(_));
1233            let adt_def_id = tcx.hir_get_parent_item(hir_id).def_id.to_def_id();
1234            let ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
1235            let inputs = data
1236                .fields()
1237                .iter()
1238                .map(|f| tcx.type_of(f.def_id).instantiate_identity().skip_norm_wip());
1239            ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(inputs, ty, hir::Safety::Safe))
1240        }
1241
1242        Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1243            // Closure signatures are not like other function
1244            // signatures and cannot be accessed through `fn_sig`. For
1245            // example, a closure signature excludes the `self`
1246            // argument. In any case they are embedded within the
1247            // closure type as part of the `ClosureArgs`.
1248            //
1249            // To get the signature of a closure, you should use the
1250            // `sig` method on the `ClosureArgs`:
1251            //
1252            //    args.as_closure().sig(def_id, tcx)
1253            bug!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`",);
1254        }
1255
1256        x => {
1257            bug!("unexpected sort of node in fn_sig(): {:?}", x);
1258        }
1259    };
1260    ty::EarlyBinder::bind(tcx, output)
1261}
1262
1263fn lower_fn_sig_recovering_infer_ret_ty<'tcx>(
1264    icx: &ItemCtxt<'tcx>,
1265    sig: &'tcx hir::FnSig<'tcx>,
1266    generics: &'tcx hir::Generics<'tcx>,
1267    def_id: LocalDefId,
1268) -> ty::PolyFnSig<'tcx> {
1269    if let Some(infer_ret_ty) = sig.decl.output.is_suggestable_infer_ty() {
1270        return recover_infer_ret_ty(icx, infer_ret_ty, generics, def_id);
1271    }
1272
1273    icx.lowerer().lower_fn_ty(
1274        icx.tcx().local_def_id_to_hir_id(def_id),
1275        sig.header.safety(),
1276        sig.header.abi,
1277        sig.decl,
1278        Some(generics),
1279        None,
1280    )
1281}
1282
1283/// Convert `ReLateParam`s in `value` back into `ReBound`s and bind it with `bound_vars`.
1284fn late_param_regions_to_bound<'tcx, T>(
1285    tcx: TyCtxt<'tcx>,
1286    scope: DefId,
1287    bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
1288    value: T,
1289) -> ty::Binder<'tcx, T>
1290where
1291    T: ty::TypeFoldable<TyCtxt<'tcx>>,
1292{
1293    let value = fold_regions(tcx, value, |r, debruijn| match r.kind() {
1294        ty::ReLateParam(lp) => {
1295            // Should be in scope, otherwise inconsistency happens somewhere.
1296            {
    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);
1297
1298            let br = match lp.kind {
1299                // These variants preserve the bound var index.
1300                kind @ (ty::LateParamRegionKind::Anon(idx)
1301                | ty::LateParamRegionKind::NamedAnon(idx, _)) => {
1302                    let idx = idx as usize;
1303                    let var = ty::BoundVar::from_usize(idx);
1304
1305                    let Some(ty::BoundVariableKind::Region(kind)) = bound_vars.get(idx).copied()
1306                    else {
1307                        ::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:?}");
1308                    };
1309
1310                    ty::BoundRegion { var, kind }
1311                }
1312
1313                // For named regions, look up the corresponding bound var.
1314                ty::LateParamRegionKind::Named(def_id) => bound_vars
1315                    .iter()
1316                    .enumerate()
1317                    .find_map(|(idx, bv)| match bv {
1318                        ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::Named(did))
1319                            if did == def_id =>
1320                        {
1321                            Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1322                        }
1323                        _ => None,
1324                    })
1325                    .unwrap(),
1326
1327                ty::LateParamRegionKind::ClosureEnv => bound_vars
1328                    .iter()
1329                    .enumerate()
1330                    .find_map(|(idx, bv)| match bv {
1331                        ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::ClosureEnv) => {
1332                            Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1333                        }
1334                        _ => None,
1335                    })
1336                    .unwrap(),
1337            };
1338
1339            ty::Region::new_bound(tcx, debruijn, br)
1340        }
1341        _ => r,
1342    });
1343
1344    ty::Binder::bind_with_vars(value, bound_vars)
1345}
1346
1347fn recover_infer_ret_ty<'tcx>(
1348    icx: &ItemCtxt<'tcx>,
1349    infer_ret_ty: &'tcx hir::Ty<'tcx>,
1350    generics: &'tcx hir::Generics<'tcx>,
1351    def_id: LocalDefId,
1352) -> ty::PolyFnSig<'tcx> {
1353    let tcx = icx.tcx;
1354    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1355
1356    let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1357
1358    // Typeck doesn't expect erased regions to be returned from `type_of`.
1359    // This is a heuristic approach. If the scope has region parameters,
1360    // we should change fn_sig's lifetime from `ReErased` to `ReError`,
1361    // otherwise to `ReStatic`.
1362    let has_region_params = generics.params.iter().any(|param| match param.kind {
1363        GenericParamKind::Lifetime { .. } => true,
1364        _ => false,
1365    });
1366    let fn_sig = fold_regions(tcx, fn_sig, |r, _| match r.kind() {
1367        ty::ReErased => {
1368            if has_region_params {
1369                ty::Region::new_error_with_message(
1370                    tcx,
1371                    DUMMY_SP,
1372                    "erased region is not allowed here in return type",
1373                )
1374            } else {
1375                tcx.lifetimes.re_static
1376            }
1377        }
1378        _ => r,
1379    });
1380
1381    let mut visitor = HirPlaceholderCollector::default();
1382    visitor.visit_ty_unambig(infer_ret_ty);
1383
1384    let mut diag = bad_placeholder(icx.lowerer(), visitor.spans, "return type");
1385    let ret_ty = fn_sig.output();
1386
1387    // Don't leak types into signatures unless they're nameable!
1388    // For example, if a function returns itself, we don't want that
1389    // recursive function definition to leak out into the fn sig.
1390    let mut recovered_ret_ty = None;
1391    if let Some(suggestable_ret_ty) = ret_ty.make_suggestable(tcx, false, None) {
1392        diag.span_suggestion_verbose(
1393            infer_ret_ty.span,
1394            "replace with the correct return type",
1395            suggestable_ret_ty,
1396            Applicability::MachineApplicable,
1397        );
1398        recovered_ret_ty = Some(suggestable_ret_ty);
1399    } else if let Some(sugg) = suggest_impl_trait(
1400        &tcx.infer_ctxt().build(TypingMode::non_body_analysis()),
1401        tcx.param_env(def_id),
1402        ret_ty,
1403    ) {
1404        diag.span_suggestion_verbose(
1405            infer_ret_ty.span,
1406            "replace with an appropriate return type",
1407            sugg,
1408            Applicability::MachineApplicable,
1409        );
1410    } else if ret_ty.is_closure() {
1411        diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1412    }
1413
1414    // Also note how `Fn` traits work just in case!
1415    if ret_ty.is_closure() {
1416        diag.note(
1417            "for more information on `Fn` traits and closure types, see \
1418                     https://doc.rust-lang.org/book/ch13-01-closures.html",
1419        );
1420    }
1421    let guar = diag.emit_err();
1422
1423    // If we return a dummy binder here, we can ICE later in borrowck when it encounters
1424    // `ReLateParam` regions (e.g. in a local type annotation) which weren't registered via the
1425    // signature binder. See #135845.
1426    let bound_vars = tcx.late_bound_vars(hir_id);
1427    let scope = def_id.to_def_id();
1428
1429    let fn_sig = tcx.mk_fn_sig(
1430        fn_sig.inputs().iter().copied(),
1431        recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)),
1432        fn_sig.fn_sig_kind,
1433    );
1434
1435    late_param_regions_to_bound(tcx, scope, bound_vars, fn_sig)
1436}
1437
1438pub fn suggest_impl_trait<'tcx>(
1439    infcx: &InferCtxt<'tcx>,
1440    param_env: ty::ParamEnv<'tcx>,
1441    ret_ty: Ty<'tcx>,
1442) -> Option<String> {
1443    let format_as_assoc: fn(_, _, _, _, _) -> _ =
1444        |tcx: TyCtxt<'tcx>,
1445         _: ty::GenericArgsRef<'tcx>,
1446         trait_def_id: DefId,
1447         assoc_item_def_id: DefId,
1448         item_ty: Ty<'tcx>| {
1449            let trait_name = tcx.item_name(trait_def_id);
1450            let assoc_name = tcx.item_name(assoc_item_def_id);
1451            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}>"))
1452        };
1453    let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1454        |tcx: TyCtxt<'tcx>,
1455         args: ty::GenericArgsRef<'tcx>,
1456         trait_def_id: DefId,
1457         _: DefId,
1458         item_ty: Ty<'tcx>| {
1459            let trait_name = tcx.item_name(trait_def_id);
1460            let args_tuple = args.type_at(1);
1461            let ty::Tuple(types) = *args_tuple.kind() else {
1462                return None;
1463            };
1464            let types = types.make_suggestable(tcx, false, None)?;
1465            let maybe_ret =
1466                if item_ty.is_unit() { String::new() } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" -> {0}", item_ty))
    })format!(" -> {item_ty}") };
1467            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!(
1468                "impl {trait_name}({}){maybe_ret}",
1469                types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1470            ))
1471        };
1472
1473    for (trait_def_id, assoc_item_def_id, formatter) in [
1474        (
1475            infcx.tcx.get_diagnostic_item(sym::Iterator),
1476            infcx.tcx.get_diagnostic_item(sym::IteratorItem),
1477            format_as_assoc,
1478        ),
1479        (
1480            infcx.tcx.lang_items().future_trait(),
1481            infcx.tcx.lang_items().future_output(),
1482            format_as_assoc,
1483        ),
1484        (
1485            infcx.tcx.lang_items().async_fn_trait(),
1486            infcx.tcx.lang_items().async_fn_once_output(),
1487            format_as_parenthesized,
1488        ),
1489        (
1490            infcx.tcx.lang_items().async_fn_mut_trait(),
1491            infcx.tcx.lang_items().async_fn_once_output(),
1492            format_as_parenthesized,
1493        ),
1494        (
1495            infcx.tcx.lang_items().async_fn_once_trait(),
1496            infcx.tcx.lang_items().async_fn_once_output(),
1497            format_as_parenthesized,
1498        ),
1499        (
1500            infcx.tcx.lang_items().fn_trait(),
1501            infcx.tcx.lang_items().fn_once_output(),
1502            format_as_parenthesized,
1503        ),
1504        (
1505            infcx.tcx.lang_items().fn_mut_trait(),
1506            infcx.tcx.lang_items().fn_once_output(),
1507            format_as_parenthesized,
1508        ),
1509        (
1510            infcx.tcx.lang_items().fn_once_trait(),
1511            infcx.tcx.lang_items().fn_once_output(),
1512            format_as_parenthesized,
1513        ),
1514    ] {
1515        let Some(trait_def_id) = trait_def_id else {
1516            continue;
1517        };
1518        let Some(assoc_item_def_id) = assoc_item_def_id else {
1519            continue;
1520        };
1521        if infcx.tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1522            continue;
1523        }
1524        let sugg = infcx.probe(|_| {
1525            let args = ty::GenericArgs::for_item(infcx.tcx, trait_def_id, |param, _| {
1526                if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(DUMMY_SP, param) }
1527            });
1528            if !infcx
1529                .type_implements_trait(trait_def_id, args, param_env)
1530                .must_apply_modulo_regions()
1531            {
1532                return None;
1533            }
1534            let ocx = ObligationCtxt::new(&infcx);
1535            let item_ty = ocx.normalize(
1536                &ObligationCause::dummy(),
1537                param_env,
1538                Unnormalized::new(Ty::new_projection_from_args(
1539                    infcx.tcx,
1540                    ty::IsRigid::No,
1541                    assoc_item_def_id,
1542                    args,
1543                )),
1544            );
1545            // FIXME(compiler-errors): We may benefit from resolving regions here.
1546            if ocx.try_evaluate_obligations().no_errors()
1547                && let item_ty = infcx.deeply_resolve_ignoring_regions(item_ty)
1548                && let Some(item_ty) = item_ty.make_suggestable(infcx.tcx, false, None)
1549                && let Some(sugg) = formatter(
1550                    infcx.tcx,
1551                    infcx.deeply_resolve_ignoring_regions(args),
1552                    trait_def_id,
1553                    assoc_item_def_id,
1554                    item_ty,
1555                )
1556            {
1557                return Some(sugg);
1558            }
1559
1560            None
1561        });
1562
1563        if sugg.is_some() {
1564            return sugg;
1565        }
1566    }
1567    None
1568}
1569
1570fn impl_is_fully_generic_for_reflection(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1571    tcx.impl_trait_header(def_id).is_fully_generic_for_reflection()
1572        && tcx.explicit_clauses_of(def_id).is_fully_generic_for_reflection()
1573}
1574
1575fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::ImplTraitHeader<'_> {
1576    let icx = ItemCtxt::new(tcx, def_id);
1577    let item = tcx.hir_expect_item(def_id);
1578    let impl_ = item.expect_impl();
1579    let of_trait = impl_
1580        .of_trait
1581        .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:?}"));
1582    let selfty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1583
1584    check_impl_constness(tcx, impl_.constness, &of_trait.trait_ref);
1585
1586    let trait_ref = icx.lowerer().lower_impl_trait_ref(&of_trait.trait_ref, selfty);
1587
1588    ty::ImplTraitHeader {
1589        trait_ref: ty::EarlyBinder::bind(tcx, trait_ref),
1590        safety: of_trait.safety,
1591        polarity: polarity_of_impl(of_trait),
1592        constness: impl_.constness,
1593    }
1594}
1595
1596fn check_impl_constness(
1597    tcx: TyCtxt<'_>,
1598    constness: hir::Constness,
1599    hir_trait_ref: &hir::TraitRef<'_>,
1600) {
1601    if let hir::Constness::NotConst = constness {
1602        return;
1603    }
1604
1605    let Some(trait_def_id) = hir_trait_ref.trait_def_id() else { return };
1606    if tcx.is_const_trait(trait_def_id) {
1607        return;
1608    }
1609
1610    let trait_name = tcx.item_name(trait_def_id).to_string();
1611    let (suggestion, suggestion_pre) = match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
1612    {
1613        (Some(trait_def_id), true) => {
1614            let span = tcx.hir_expect_item(trait_def_id).vis_span;
1615            let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1616
1617            (
1618                Some(span.shrink_to_hi()),
1619                if tcx.features().const_trait_impl() {
1620                    ""
1621                } else {
1622                    "enable `#![feature(const_trait_impl)]` in your crate and "
1623                },
1624            )
1625        }
1626        (None, _) | (_, false) => (None, ""),
1627    };
1628    tcx.dcx().emit_err(diagnostics::ConstImplForNonConstTrait {
1629        trait_ref_span: hir_trait_ref.path.span,
1630        trait_name,
1631        suggestion,
1632        suggestion_pre,
1633        marking: (),
1634        adding: (),
1635    });
1636}
1637
1638fn polarity_of_impl(of_trait: &hir::TraitImplHeader<'_>) -> ty::ImplPolarity {
1639    match of_trait.polarity {
1640        hir::ImplPolarity::Negative(_) => ty::ImplPolarity::Negative,
1641        hir::ImplPolarity::Positive => ty::ImplPolarity::Positive,
1642    }
1643}
1644
1645/// Returns the early-bound lifetimes declared in this generics
1646/// listing. For anything other than fns/methods, this is just all
1647/// the lifetimes that are declared. For fns or methods, we have to
1648/// screen out those that do not appear in any where-clauses etc using
1649/// `resolve_lifetime::early_bound_lifetimes`.
1650fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1651    tcx: TyCtxt<'tcx>,
1652    generics: &'a hir::Generics<'a>,
1653) -> impl Iterator<Item = &'a hir::GenericParam<'a>> {
1654    generics.params.iter().filter(move |param| match param.kind {
1655        GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1656        _ => false,
1657    })
1658}
1659
1660fn compute_sig_of_foreign_fn_decl<'tcx>(
1661    tcx: TyCtxt<'tcx>,
1662    def_id: LocalDefId,
1663    decl: &'tcx hir::FnDecl<'tcx>,
1664    abi: ExternAbi,
1665    safety: hir::Safety,
1666) -> ty::PolyFnSig<'tcx> {
1667    let hir_id = tcx.local_def_id_to_hir_id(def_id);
1668    let fty =
1669        ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, safety, abi, decl, None, None);
1670
1671    // Feature gate SIMD types in FFI, since I am not sure that the
1672    // ABIs are handled at all correctly. -huonw
1673    if !tcx.features().simd_ffi() {
1674        let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1675            if ty.is_simd() {
1676                let snip = tcx
1677                    .sess
1678                    .source_map()
1679                    .span_to_snippet(hir_ty.span)
1680                    .map_or_else(|_| String::new(), |s| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" `{0}`", s))
    })format!(" `{s}`"));
1681                tcx.dcx()
1682                    .emit_err(diagnostics::SIMDFFIHighlyExperimental { span: hir_ty.span, snip });
1683            }
1684        };
1685        for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1686            check(input, *ty)
1687        }
1688        if let hir::FnRetTy::Return(ty) = decl.output {
1689            check(ty, fty.output().skip_binder())
1690        }
1691    }
1692
1693    fty
1694}
1695
1696fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<hir::CoroutineKind> {
1697    match tcx.hir_node_by_def_id(def_id) {
1698        Node::Expr(&hir::Expr {
1699            kind:
1700                hir::ExprKind::Closure(&rustc_hir::Closure {
1701                    kind: hir::ClosureKind::Coroutine(kind),
1702                    ..
1703                }),
1704            ..
1705        }) => Some(kind),
1706        _ => None,
1707    }
1708}
1709
1710fn coroutine_for_closure(tcx: TyCtxt<'_>, def_id: LocalDefId) -> DefId {
1711    let &rustc_hir::Closure { kind: hir::ClosureKind::CoroutineClosure(_), body, .. } =
1712        tcx.hir_node_by_def_id(def_id).expect_closure()
1713    else {
1714        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
1715    };
1716
1717    let &hir::Expr {
1718        kind:
1719            hir::ExprKind::Closure(&rustc_hir::Closure {
1720                def_id,
1721                kind: hir::ClosureKind::Coroutine(_),
1722                ..
1723            }),
1724        ..
1725    } = tcx.hir_body(body).value
1726    else {
1727        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
1728    };
1729
1730    def_id.to_def_id()
1731}
1732
1733fn opaque_ty_origin<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> hir::OpaqueTyOrigin<DefId> {
1734    match tcx.hir_node_by_def_id(def_id).expect_opaque_ty().origin {
1735        hir::OpaqueTyOrigin::FnReturn { parent, in_trait_or_impl } => {
1736            hir::OpaqueTyOrigin::FnReturn { parent: parent.to_def_id(), in_trait_or_impl }
1737        }
1738        hir::OpaqueTyOrigin::AsyncFn { parent, in_trait_or_impl } => {
1739            hir::OpaqueTyOrigin::AsyncFn { parent: parent.to_def_id(), in_trait_or_impl }
1740        }
1741        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty } => {
1742            hir::OpaqueTyOrigin::TyAlias { parent: parent.to_def_id(), in_assoc_ty }
1743        }
1744    }
1745}
1746
1747fn rendered_precise_capturing_args<'tcx>(
1748    tcx: TyCtxt<'tcx>,
1749    def_id: LocalDefId,
1750) -> Option<&'tcx [PreciseCapturingArgKind<Symbol, Symbol>]> {
1751    if let Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) =
1752        tcx.opt_rpitit_info(def_id.to_def_id())
1753    {
1754        return tcx.rendered_precise_capturing_args(opaque_def_id);
1755    }
1756
1757    tcx.hir_node_by_def_id(def_id).expect_opaque_ty().bounds.iter().find_map(|bound| match bound {
1758        hir::GenericBound::Use(args, ..) => {
1759            Some(&*tcx.arena.alloc_from_iter(args.iter().map(|arg| match arg {
1760                PreciseCapturingArgKind::Lifetime(_) => {
1761                    PreciseCapturingArgKind::Lifetime(arg.name())
1762                }
1763                PreciseCapturingArgKind::Param(_) => PreciseCapturingArgKind::Param(arg.name()),
1764            })))
1765        }
1766        _ => None,
1767    })
1768}
1769
1770fn const_param_default<'tcx>(
1771    tcx: TyCtxt<'tcx>,
1772    local_def_id: LocalDefId,
1773) -> ty::EarlyBinder<'tcx, Const<'tcx>> {
1774    let hir::Node::GenericParam(hir::GenericParam {
1775        kind: hir::GenericParamKind::Const { default: Some(default_ct), .. },
1776        ..
1777    }) = tcx.hir_node_by_def_id(local_def_id)
1778    else {
1779        ::rustc_span::macros::bug_impl(Some(tcx.def_span(local_def_id)),
    format_args!("`const_param_default` expected a generic parameter with a constant"),
    Location::caller())span_bug!(
1780            tcx.def_span(local_def_id),
1781            "`const_param_default` expected a generic parameter with a constant"
1782        )
1783    };
1784
1785    let icx = ItemCtxt::new(tcx, local_def_id);
1786
1787    let def_id = local_def_id.to_def_id();
1788    let identity_args = ty::GenericArgs::identity_for_item(tcx, tcx.parent(def_id));
1789
1790    let ct = icx.lowerer().lower_const_arg(
1791        default_ct,
1792        tcx.type_of(def_id).instantiate(tcx, identity_args).skip_norm_wip(),
1793    );
1794    ty::EarlyBinder::bind(tcx, ct)
1795}
1796
1797fn anon_const_kind<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> ty::AnonConstKind {
1798    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);
1799    let hir_id = tcx.local_def_id_to_hir_id(def);
1800    let parent_node_id = tcx.parent_hir_id(hir_id);
1801    match tcx.hir_node(parent_node_id) {
1802        hir::Node::ConstArg(const_arg) => {
1803            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);
1804            if tcx.features().generic_const_exprs() {
1805                ty::AnonConstKind::GCE
1806            } else if tcx.features().gca() {
1807                ty::AnonConstKind::MCG
1808            } else if let hir::Node::Expr(hir::Expr {
1809                kind: hir::ExprKind::Repeat(_, repeat_count),
1810                ..
1811            }) = tcx.parent_hir_node(parent_node_id)
1812                && repeat_count.hir_id == parent_node_id
1813            {
1814                ty::AnonConstKind::RepeatExprCount
1815            } else {
1816                ty::AnonConstKind::MCG
1817            }
1818        }
1819        hir::Node::Expr(hir::Expr {
1820            kind: hir::ExprKind::ConstBlock(..) | hir::ExprKind::InlineAsm(..),
1821            ..
1822        }) => ty::AnonConstKind::NonTypeSystemInline,
1823        _ => ty::AnonConstKind::NonTypeSystemAnon,
1824    }
1825}
1826
1827{}
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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                                ::tracing_core::__macro_support::Option::Some(1827u32),
                                ::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/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs:1827",
                        "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/collect.rs"),
                        ::tracing_core::__macro_support::Option::Some(1827u32),
                        ::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)]
1828fn const_of_item<'tcx>(
1829    tcx: TyCtxt<'tcx>,
1830    def_id: LocalDefId,
1831) -> Option<ty::EarlyBinder<'tcx, Const<'tcx>>> {
1832    let ct_rhs = match tcx.hir_node_by_def_id(def_id) {
1833        hir::Node::Item(&hir::Item { kind: hir::ItemKind::Const(.., ct), .. }) => ct,
1834        hir::Node::TraitItem(&hir::TraitItem {
1835            kind: hir::TraitItemKind::Const(_, ct), ..
1836        }) => ct?,
1837        hir::Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(.., ct), .. }) => ct,
1838        node => {
1839            span_bug!(
1840                tcx.def_span(def_id),
1841                "`const_of_item` expected a const or assoc const item, got {node:?}"
1842            )
1843        }
1844    };
1845    let ct_arg = match ct_rhs {
1846        hir::ConstItemRhs::Direct(ct_arg) => ct_arg,
1847        hir::ConstItemRhs::Body(_) => {
1848            return None;
1849        }
1850    };
1851    let icx = ItemCtxt::new(tcx, def_id);
1852    let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
1853    let ct = icx.lowerer().lower_const_arg(
1854        ct_arg,
1855        tcx.type_of(def_id.to_def_id()).instantiate(tcx, identity_args).skip_norm_wip(),
1856    );
1857    if let Err(e) = icx.check_tainted_by_errors()
1858        && !ct.references_error()
1859    {
1860        Some(ty::EarlyBinder::bind(tcx, Const::new_error(tcx, e)))
1861    } else {
1862        Some(ty::EarlyBinder::bind(tcx, ct))
1863    }
1864}