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, TestBinderItem};
52use crate::diagnostics::{self, ElidedLifetimesAreNotAllowedInDelegations};
53use crate::hir_ty_lowering::{HirTyLowerer, InherentAssocCandidate, RegionInferReason};
54
55mod clauses_of;
56pub(crate) mod dump;
57mod generics_of;
58mod item_bounds;
59mod resolve_bound_vars;
60mod type_of;
61
62///////////////////////////////////////////////////////////////////////////
63
64/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
65pub(crate) fn provide(providers: &mut Providers) {
66    resolve_bound_vars::provide(providers);
67    *providers = Providers {
68        type_of: type_of::type_of,
69        type_of_opaque: type_of::type_of_opaque,
70        type_of_opaque_hir_typeck: type_of::type_of_opaque_hir_typeck,
71        type_alias_is_checked: type_of::type_alias_is_checked,
72        item_bounds: item_bounds::item_bounds,
73        explicit_item_bounds: item_bounds::explicit_item_bounds,
74        item_self_bounds: item_bounds::item_self_bounds,
75        explicit_item_self_bounds: item_bounds::explicit_item_self_bounds,
76        item_non_self_bounds: item_bounds::item_non_self_bounds,
77        impl_super_outlives: item_bounds::impl_super_outlives,
78        generics_of: generics_of::generics_of,
79        clauses_of: clauses_of::clauses_of,
80        explicit_clauses_of: clauses_of::explicit_clauses_of,
81        explicit_super_clauses_of: clauses_of::explicit_super_clauses_of,
82        explicit_implied_clauses_of: clauses_of::explicit_implied_clauses_of,
83        explicit_supertraits_containing_assoc_item:
84            clauses_of::explicit_supertraits_containing_assoc_item,
85        trait_explicit_clauses_and_bounds: clauses_of::trait_explicit_clauses_and_bounds,
86        const_conditions: clauses_of::const_conditions,
87        explicit_implied_const_bounds: clauses_of::explicit_implied_const_bounds,
88        type_param_clauses: clauses_of::type_param_clauses,
89        trait_def,
90        adt_def,
91        fn_sig,
92        impl_trait_header,
93        impl_is_fully_generic_for_reflection,
94        coroutine_kind,
95        coroutine_for_closure,
96        opaque_ty_origin,
97        rendered_precise_capturing_args,
98        const_param_default,
99        anon_const_kind,
100        const_of_item,
101        ..*providers
102    };
103}
104
105///////////////////////////////////////////////////////////////////////////
106
107/// Context specific to some particular item. This is what implements [`HirTyLowerer`].
108///
109/// # `ItemCtxt` vs `FnCtxt`
110///
111/// `ItemCtxt` is primarily used to type-check item signatures and lower them
112/// from HIR to their [`ty::Ty`] representation, which is exposed using [`HirTyLowerer`].
113/// It's also used for the bodies of items like structs where the body (the fields)
114/// are just signatures.
115///
116/// This is in contrast to `FnCtxt`, which is used to type-check bodies of
117/// functions, closures, and `const`s -- anywhere that expressions and statements show up.
118///
119/// An important thing to note is that `ItemCtxt` does no inference -- it has no [`InferCtxt`] --
120/// while `FnCtxt` does do inference.
121///
122/// [`InferCtxt`]: rustc_infer::infer::InferCtxt
123///
124/// # Trait predicates
125///
126/// `ItemCtxt` has information about the predicates that are defined
127/// on the trait. Unfortunately, this predicate information is
128/// available in various different forms at various points in the
129/// process. So we can't just store a pointer to e.g., the HIR or the
130/// parsed ty form, we have to be more flexible. To this end, the
131/// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
132/// `probe_ty_param_bounds` requests, drawing the information from
133/// the HIR (`hir::Generics`), recursively.
134pub(crate) struct ItemCtxt<'tcx> {
135    tcx: TyCtxt<'tcx>,
136    item_def_id: LocalDefId,
137    tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
138    lowering_delegation_segment: bool,
139}
140
141///////////////////////////////////////////////////////////////////////////
142
143#[derive(#[automatically_derived]impl ::core::default::Default for
    HirPlaceholderCollector {
    #[inline]
    fn default() -> Self {
        HirPlaceholderCollector {
            spans: ::core::default::Default::default(),
            may_contain_const_infer: ::core::default::Default::default(),
        }
    }
}Default)]
144pub(crate) struct HirPlaceholderCollector {
145    pub spans: Vec<Span>,
146    // If any of the spans points to a const infer var, then suppress any messages
147    // that may try to turn that const infer into a type parameter.
148    pub may_contain_const_infer: bool,
149}
150
151impl<'v> Visitor<'v> for HirPlaceholderCollector {
152    fn visit_infer(&mut self, _inf_id: HirId, inf_span: Span, kind: InferKind<'v>) -> Self::Result {
153        self.spans.push(inf_span);
154
155        if let InferKind::Const(_) | InferKind::Ambig(_) = kind {
156            self.may_contain_const_infer = true;
157        }
158    }
159}
160
161fn placeholder_type_error_diag<'cx, 'tcx>(
162    cx: &'cx dyn HirTyLowerer<'tcx>,
163    generics: Option<&hir::Generics<'_>>,
164    placeholder_types: Vec<Span>,
165    additional_spans: Vec<Span>,
166    suggest: bool,
167    hir_ty: Option<&hir::Ty<'_>>,
168    kind: &'static str,
169) -> Diag<'cx> {
170    if placeholder_types.is_empty() {
171        return bad_placeholder(cx, additional_spans, kind);
172    }
173
174    let params = generics.map(|g| g.params).unwrap_or_default();
175    let type_name = params.next_type_param_name(None);
176    let mut sugg: Vec<_> =
177        placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
178
179    if let Some(generics) = generics {
180        if let Some(span) = params.iter().find_map(|arg| match arg.name {
181            hir::ParamName::Plain(Ident { name: kw::Underscore, span }) => Some(span),
182            _ => None,
183        }) {
184            // Account for `_` already present in cases like `struct S<_>(_);` and suggest
185            // `struct S<T>(T);` instead of `struct S<_, T>(T);`.
186            sugg.push((span, (*type_name).to_string()));
187        } else if let Some(span) = generics.span_for_param_suggestion() {
188            // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
189            sugg.push((span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", type_name))
    })format!(", {type_name}")));
190        } else {
191            sugg.push((generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", type_name))
    })format!("<{type_name}>")));
192        }
193    }
194
195    let mut err =
196        bad_placeholder(cx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
197
198    // Suggest, but only if it is not a function in const or static
199    if suggest {
200        let mut is_fn = false;
201        let mut is_const_or_static = false;
202
203        if let Some(hir_ty) = hir_ty
204            && let hir::TyKind::FnPtr(_) = hir_ty.kind
205        {
206            is_fn = true;
207
208            // Check if parent is const or static
209            is_const_or_static = #[allow(non_exhaustive_omitted_patterns)] match cx.tcx().parent_hir_node(hir_ty.hir_id)
    {
    Node::Item(&hir::Item {
        kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..), .. }) |
        Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..),
        .. }) |
        Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), ..
        }) => true,
    _ => false,
}matches!(
210                cx.tcx().parent_hir_node(hir_ty.hir_id),
211                Node::Item(&hir::Item {
212                    kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
213                    ..
214                }) | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..), .. })
215                    | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
216            );
217        }
218
219        // if function is wrapped around a const or static,
220        // then don't show the suggestion
221        if !(is_fn && is_const_or_static) {
222            err.multipart_suggestion(
223                "use type parameters instead",
224                sugg,
225                Applicability::HasPlaceholders,
226            );
227        }
228    }
229
230    err
231}
232
233///////////////////////////////////////////////////////////////////////////
234// Utility types and common code for the above passes.
235
236fn bad_placeholder<'cx, 'tcx>(
237    cx: &'cx dyn HirTyLowerer<'tcx>,
238    mut spans: Vec<Span>,
239    kind: &'static str,
240) -> Diag<'cx> {
241    let kind = if kind.ends_with('s') { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}es", kind))
    })format!("{kind}es") } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}s", kind))
    })format!("{kind}s") };
242
243    spans.sort_by_key(|span| span.lo_hi());
244    cx.dcx().create_err(diagnostics::PlaceholderNotAllowedItemSignatures { spans, kind })
245}
246
247impl<'tcx> ItemCtxt<'tcx> {
248    pub(crate) fn new(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
249        ItemCtxt::new_internal(tcx, item_def_id, false)
250    }
251
252    fn new_internal(
253        tcx: TyCtxt<'tcx>,
254        item_def_id: LocalDefId,
255        delegation: bool,
256    ) -> ItemCtxt<'tcx> {
257        ItemCtxt {
258            tcx,
259            item_def_id,
260            tainted_by_errors: Cell::new(None),
261            lowering_delegation_segment: delegation,
262        }
263    }
264
265    pub(crate) fn new_for_delegation(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
266        ItemCtxt::new_internal(tcx, item_def_id, true)
267    }
268
269    pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
270        self.lowerer().lower_ty(hir_ty)
271    }
272
273    pub(crate) fn hir_id(&self) -> hir::HirId {
274        self.tcx.local_def_id_to_hir_id(self.item_def_id)
275    }
276
277    pub(crate) fn node(&self) -> hir::Node<'tcx> {
278        self.tcx.hir_node(self.hir_id())
279    }
280
281    fn check_tainted_by_errors(&self) -> Result<(), ErrorGuaranteed> {
282        match self.tainted_by_errors.get() {
283            Some(err) => Err(err),
284            None => Ok(()),
285        }
286    }
287
288    fn report_placeholder_type_error(
289        &self,
290        placeholder_types: Vec<Span>,
291        infer_replacements: Vec<(Span, String)>,
292    ) -> ErrorGuaranteed {
293        let node = self.tcx.hir_node_by_def_id(self.item_def_id);
294        let generics = node.generics();
295        let kind_id = match node {
296            Node::GenericParam(_) | Node::WherePredicate(_) | Node::Field(_) => {
297                self.tcx.local_parent(self.item_def_id)
298            }
299            _ => self.item_def_id,
300        };
301        let kind = self.tcx.def_descr(kind_id.into());
302        let mut diag = placeholder_type_error_diag(
303            self,
304            generics,
305            placeholder_types,
306            infer_replacements.iter().map(|&(span, _)| span).collect(),
307            false,
308            None,
309            kind,
310        );
311        if !infer_replacements.is_empty() {
312            diag.multipart_suggestion(
313                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try replacing `_` with the type{0} in the corresponding trait method signature",
                if infer_replacements.len() == 1 { "" } else { "s" }))
    })format!(
314                    "try replacing `_` with the type{} in the corresponding trait method \
315                        signature",
316                    rustc_errors::pluralize!(infer_replacements.len()),
317                ),
318                infer_replacements,
319                Applicability::MachineApplicable,
320            );
321        }
322
323        diag.emit_err()
324    }
325
326    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("lower_test_binder_body",
                                "rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/3ef0c22cdb86ac42dc6b8f0f1ec36857daa6f2a1/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("body")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("body");
                                                    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(&body)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

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